diff --git a/.agents/skills/docspring-enterprise-install/SKILL.md b/.agents/skills/docspring-enterprise-install/SKILL.md new file mode 100644 index 0000000..5251898 --- /dev/null +++ b/.agents/skills/docspring-enterprise-install/SKILL.md @@ -0,0 +1,98 @@ +--- +name: docspring-enterprise-install +description: Installs DocSpring Enterprise, the self-hosted DocSpring Docker image, on the customer's own infrastructure with the setups in the docspring-enterprise repository (Docker Compose, Kubernetes with Helm, AWS ECS with Terraform, AWS with Convox, or Aptible). Covers choosing a setup, the license key and registry credentials, PostgreSQL, Redis and file storage, the generated secrets, the release command, the first admin user and checking the install. Use when the user wants to install, deploy, set up or try DocSpring Enterprise, or works in a checkout of docspring-enterprise. Not for upgrading an install (docspring-enterprise-upgrade), running one day to day (docspring-enterprise-operate) or using DocSpring's hosted service. +license: MIT +metadata: + author: DocSpring +--- + +# Install DocSpring Enterprise + +DocSpring Enterprise is one Docker image that runs three services (`web`, `worker`, `worker_gj`), a release command +before each release goes live and three scheduled tasks. This repository has a ready-made setup for each platform; the +guide for each is at https://docspring.com/docs/enterprise/. + +## Rules + +1. **Never print a secret.** The license key, registry credentials, `SECRET_KEY_BASE`, + `DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY`, database and Redis passwords and the admin password go into files, + variables or the platform's secret store, never into your replies, logs or commit messages. To check one, say + whether it's set and how long it is. +2. **Ask before anything that costs money or deletes data:** creating cloud resources (`terraform apply`, + `./install.rb`, `aptible db:create`), `terraform destroy`, `docker compose down -v`, `helm uninstall`. Say what it + creates and roughly what it costs (the folder's README has the figures). A plan or a dry run needs no approval: + `terraform plan`, `./install.rb plan`, `helm template`. +3. **Generate `SECRET_KEY_BASE` and the encryption key once per install, and never change them.** The setups generate + them. Tell the user to copy the encryption key somewhere outside the install (a password manager): without it, + the data DocSpring stores can't be read. +4. **Pin an image version** (a 10-character tag such as `c648191044`, from https://docspring.com/enterprise-releases). + `latest` moves with each release. +5. **Start everything with `run_as_deploy`** and change none of the container settings the setup ships with (it starts + as root, drops all capabilities but a few, and runs Puma, Sidekiq and GoodJob directly). `AGENTS.md` at the + repository root says why. + +## 1. Choose a setup + +| Folder | Platform | Choose it when | +| ----------------- | ---------------------------------- | ----------------------------------------------------------------- | +| `docker-compose/` | One Linux server with Docker | A trial, or a small install where one server is enough | +| `kubernetes/` | Any Kubernetes cluster, with Helm | The user runs Kubernetes (EKS, GKE, AKS, OpenShift, on-premises) | +| `aws-ecs/` | AWS ECS Fargate, with Terraform | AWS without servers or Kubernetes to manage | +| `convox/` | AWS EKS through Convox, one script | A complete AWS setup from one script, managed with the Convox CLI | +| `aptible/` | Aptible | The user already runs apps on Aptible | + +Ask the user which platform they run, if it isn't clear from the conversation or their files. Then read that folder's +`README.md` (the steps) and `AGENTS.md` (its rules and checks) before you start. + +## 2. Gather what the install needs + +- **From DocSpring** (emailed to the customer): the license key, and credentials for one of the two registries that + hold the image: Docker Hub (`docspringcom/docspring-enterprise`, a username and access token) or Amazon ECR + (`691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise`, an access key ID and secret). If they don't + have them, they ask support@docspring.com. +- **A host name**, such as `docspring.example.com`, and how HTTPS will be served (the setup's proxy, their load + balancer, or a platform default domain for a trial). +- **PostgreSQL 14 or later** (17 recommended), **Redis 6.2 or later**, and **file storage** (an S3 bucket or other + S3-compatible storage, or Google Cloud Storage). The ECS, Convox and Aptible setups create the database and Redis; + for Compose and Kubernetes, ask whether to use managed services or the setup's own containers (a trial only). +- **An email provider** for invitations and password resets (SMTP, Postmark, SendGrid, Mailgun or Amazon SES). The + install can start without one. +- **Outbound HTTPS to `api.docspring.com`** for the license check. An air-gapped install needs a perpetual license + from DocSpring. + +https://docspring.com/docs/enterprise/requirements/ has the sizes, timeouts and settings in full. + +## 3. Install + +Follow the folder's README. The short version: + +- **Docker Compose:** `./setup.sh` (writes `.env` with new secrets), `docker compose up -d --wait`, then + `sudo ./install-schedule.sh` for the scheduled tasks. +- **Kubernetes:** create the namespace, the database, Redis and bucket, write a values file (or a Secret), then + `helm install docspring-enterprise oci://ghcr.io/docspring/charts/docspring-enterprise --namespace docspring +--values values.yaml --timeout 30m`. The chart runs the release command as a Job before the services start. +- **AWS ECS:** copy `example/`, fill in `terraform.tfvars`, keep the state in an encrypted S3 backend, then + `terraform init && terraform apply`, then the command `terraform output deploy_command` prints. +- **Convox:** `cd convox && ./install.rb plan`, then `./install.rb`. For a run without prompts, pass every setting + and add `--yes --json`. Settings, including generated secrets, are saved to `.installer_config.json`. +- **Aptible:** copy the folder into its own git repository, create the app, database and Redis, set the + configuration, `git push aptible main`, then add an HTTPS endpoint and scale the services. + +The release command (`run_as_deploy rake db:prepare`) creates the database schema and the first admin user from +`DOCSPRING_ADMIN_EMAIL` and `DOCSPRING_ADMIN_PASSWORD`. It runs again before every release and is safe to repeat. + +If a step fails, read its output, fix the cause and run the same step again. Every setup is safe to re-run. + +## 4. Check the install + +1. `https:///health/site` returns `200` (the app has booted), and `https:///health` returns `200` + (the database, Redis and the cache work too). +2. Run the checks, which test PostgreSQL, Redis, file storage and background jobs, then generate a test PDF: + `run_as_deploy rake checks:health_check checks:generate_test_submission`, run the way the folder's README runs + one-off commands (`docker compose run --rm tasks ...`, `kubectl exec ...`, the ECS `run_task_command` output, + `convox run command ...`, `aptible ssh --app docspring ...`). +3. The user signs in with the admin email and password and changes the password. + +Then point the user at what's left: their domain and HTTPS, email +(https://docspring.com/docs/enterprise/configuration/email-notifications/), backups of the database and the bucket, +and an uptime monitor on `/health`. diff --git a/.agents/skills/docspring-enterprise-operate/SKILL.md b/.agents/skills/docspring-enterprise-operate/SKILL.md new file mode 100644 index 0000000..10aac4c --- /dev/null +++ b/.agents/skills/docspring-enterprise-operate/SKILL.md @@ -0,0 +1,96 @@ +--- +name: docspring-enterprise-operate +description: Runs a DocSpring Enterprise install (the self-hosted DocSpring Docker image) day to day, on Docker Compose, Kubernetes, AWS ECS, Convox or Aptible. Covers changing settings, one-off commands and the Rails console, logs, the scheduled tasks, health checks, admin users and locked-out admins, backups, scaling, and diagnosing common problems (the license check, failed PDFs, stuck jobs, uploads, emails, timeouts). Use when the user asks to configure, troubleshoot, debug, scale, back up or check on their DocSpring Enterprise install, or to run a command or rake task on it. Not for a new install (docspring-enterprise-install) or an upgrade (docspring-enterprise-upgrade). +license: MIT +metadata: + author: DocSpring +--- + +# Run DocSpring Enterprise + +An install runs three services from one image: `web` (Puma, port 4001), `worker` (Sidekiq: PDFs, emails, webhooks) +and `worker_gj` (GoodJob: account exports and imports), plus three scheduled tasks. The settings are environment +variables, listed at https://docspring.com/docs/enterprise/configuration/environment-variables/. + +## Rules + +1. **Never print a secret.** Don't run `env`, `printenv`, `convox env`, `kubectl get secret -o yaml`, + `aptible config` or `docker compose config` where the output reaches the conversation: filter to the names you + need (`convox env | cut -d= -f1`), or check whether one is set. +2. **Never look at customer documents or submission data.** Diagnose with IDs, counts, statuses, error messages and + logs. If a problem needs a document's contents, ask the user to look. +3. **Ask before anything that changes or deletes data**: rake tasks that write, Rails console changes, restarts in + production, scaling down, deleting jobs or records. Reading logs and statuses needs no approval. +4. **Never change `DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY` or `SECRET_KEY_BASE`** on a running install. A new + encryption key makes the stored data unreadable. +5. **Start every command with `run_as_deploy`**, as the services do. + +## Running commands + +Run one-off commands with the same image and settings as the services: + +| Setup | One-off command | Logs | +| -------------- | -------------------------------------------------------------------------------------- | ------------------------------------------ | +| Docker Compose | `docker compose run --rm tasks run_as_deploy ` | `docker compose logs -f web worker` | +| Kubernetes | `kubectl exec -n docspring deploy/docspring-enterprise-web -- run_as_deploy ` | `kubectl logs -n docspring deploy/...` | +| AWS ECS | `terraform output run_task_command` (a task that runs and exits), or ECS Exec | CloudWatch (`terraform output log_groups`) | +| Convox | `convox run command ''` | `convox logs` | +| Aptible | `aptible ssh --app docspring ` | `aptible logs --app docspring` | + +A Rails console is `run_as_deploy rails console` (add `-it` for `kubectl exec`). + +## Changing settings + +Set the variable where the setup keeps it (`.env`, the Helm values or Secret, `extra_environment` or `extra_secrets` +in Terraform, `convox env set`, `aptible config:set`), then restart the services so they read it: `docker compose up -d`, +`kubectl rollout restart deployment -n docspring -l app.kubernetes.io/instance=docspring-enterprise`, the ECS deploy +command, `./update.sh` on Convox (Aptible restarts by itself). The `/admin/system` page shows the values the app sees, +with secrets hidden. + +## Checks + +- `/health/site`: the app has booted. `/health`: the database, Redis and the cache work too. +- `run_as_deploy rake checks:health_check`: PostgreSQL, Redis, file storage and Sidekiq. Add + `checks:generate_test_submission` to make a test PDF from start to finish. +- `/sidekiq` (Owners and Developers) shows Sidekiq's queues, retries and dead jobs, and `/good_job` GoodJob's. + +## Scheduled tasks + +Three tasks run every scheduled job the install needs: `rake timers:hourly` (`15 * * * *`), `timers:daily` +(`0 3 * * *`) and `timers:weekly` (`0 4 * * 0`). Run one now with the one-off command, or one step of it with `ONLY`: +`run_as_deploy rake timers:daily ONLY=submissions:expire_overdue_submissions`. Details: +https://docspring.com/docs/enterprise/scheduled-tasks/. + +## Admin users + +- Admins have the Owner, Developer or Support role (https://docspring.com/docs/enterprise/admin-users/). +- Everyone locked out: run `run_as_deploy rake db:seed` as a one-off command with `DOCSPRING_ADMIN_EMAIL` and + `DOCSPRING_ADMIN_PASSWORD` set to a new admin's. It creates that user as an Owner, and does nothing if the email + address already exists. Ask the user for the password, or have them set it themselves; never choose one they can't + see. + +## Common problems + +| Symptom | Look at | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Submissions fail with "Your DocSpring license is no longer valid" | The install can't reach `https://api.docspring.com` (it's disabled 30 days after its last passing check; the admin pages show a banner first), or the license was revoked. Check outbound HTTPS from the containers, then contact support@docspring.com | +| PDFs stay pending | Is `worker` running and healthy? Sidekiq's queues and retries; the worker's logs | +| Account exports or imports stay queued | Is `worker_gj` running? It needs a direct database connection, not a pgbouncer transaction pool | +| Uploads fail in the browser | The bucket's CORS rule allows the install's origin (https://docspring.com/docs/enterprise/requirements/) | +| Large uploads or long requests fail at a proxy | The proxy or load balancer allows 110 MB bodies and a 240-second timeout | +| No emails | `DOCSPRING_DISABLE_EMAILS` is off and an email provider is set; the worker's logs | +| Containers restart on every deploy or stop part way | The container settings match the setup's (`run_as_deploy`, capabilities, no foreman) | +| A scheduled task didn't run | The platform's schedule points at the current image; run the task by hand and read its output | + +If you can't find the cause, collect the error messages, the image version and what changed recently, and have the +user send them to support@docspring.com. + +## Backups and scaling + +- Back up the database (managed snapshots or point-in-time recovery, or `pg_dump`) and the bucket (versioning), and + keep the encryption key and `SECRET_KEY_BASE` somewhere separate. Back up Redis with them: it holds the job queues, + and a database restored without them has submissions that stay pending. Stop `worker` (Sidekiq) while you back up + the database and Redis, so a job can't finish between the two, then start it again. Docker Compose's `backup.sh` + does all of that, and `docker-compose/README.md` restores it. +- `web` and `worker` scale out to any number of containers; one `worker_gj` is enough. Sizes are at + https://docspring.com/docs/enterprise/requirements/#cpu-and-memory. diff --git a/.agents/skills/docspring-enterprise-upgrade/SKILL.md b/.agents/skills/docspring-enterprise-upgrade/SKILL.md new file mode 100644 index 0000000..a085e1b --- /dev/null +++ b/.agents/skills/docspring-enterprise-upgrade/SKILL.md @@ -0,0 +1,73 @@ +--- +name: docspring-enterprise-upgrade +description: Upgrades a DocSpring Enterprise install (the self-hosted DocSpring Docker image) to a new release, on Docker Compose, Kubernetes with Helm, AWS ECS, Convox or Aptible. Covers reading the release notes and their upgrade notes, backing up first, running the release command before the services change, checking the result and going back to the previous release. Use when the user wants to upgrade, update or patch DocSpring Enterprise, move to a new image version or tag, or asks what a release changes for their install. Not for a new install (docspring-enterprise-install) or other day-to-day work (docspring-enterprise-operate). +license: MIT +metadata: + author: DocSpring +--- + +# Upgrade DocSpring Enterprise + +Each release is an image tag: the first 10 characters of a commit, such as `c648191044`. The releases and their notes +are at https://docspring.com/enterprise-releases. The full guide is https://docspring.com/docs/enterprise/upgrades/. + +## Rules + +1. **Never print a secret** (the license key, registry credentials, `SECRET_KEY_BASE`, the encryption key, + passwords). Say whether a setting is set, not its value. +2. **Read the notes of every release between the current version and the target**, not only the target's. Each + release's **Upgrade notes** section lists what the install must change: a new service, setting or scheduled task. + Make those changes as part of the upgrade, and tell the user about each one before you do. +3. **Back up the database before the release command runs**, and confirm the backup finished. +4. **The release command runs before any service moves to the new image.** Use the setup's own upgrade path below, + which does this. Never restart services on the new image first: the new code would run before its migrations. +5. **Ask before upgrading production.** Upgrading a staging install first is worth suggesting when the user has one. + +## 1. Find the current and target versions + +- The current version is the image tag the install runs: in `convox.yml`, the Helm values (`image.tag`), + `terraform.tfvars` (`image_tag`), the Compose `.env` or the Aptible `Dockerfile`'s `FROM` line. The `/admin/system` + page shows the running commit, whose first 10 characters are the version. +- The target is the latest release unless the user names one. Releases can be skipped: the release command runs every + migration in between. + +## 2. Read the notes + +Read each release's notes from the current version up to the target. Summarize for the user what changes for their +install (upgrade notes first, then fixes and features that affect them), and list the changes you'll make. + +## 3. Back up + +- Managed databases (RDS, Cloud SQL, Azure): take a manual snapshot, or check that point-in-time recovery covers now. +- Otherwise: `pg_dump --format=custom --no-owner "$DATABASE_URL" > docspring-.dump`, from somewhere that can + reach the database. The Compose setup's `update.sh` does this itself. + +## 4. Upgrade + +| Setup | Steps | +| -------------- | -------------------------------------------------------------------------------------------------------- | +| Docker Compose | `./update.sh `: backs up, pulls, runs the release command, restarts (a minute of downtime) | +| Kubernetes | Set `image.tag`, then `helm upgrade` with the same chart, values and `--timeout 30m` as the install | +| AWS ECS | Set `image_tag`, `terraform apply` (changes nothing running), then the `terraform output deploy_command` | +| Convox | Change the tag on every `image:` line in `convox.yml`, then `./update.sh` | +| Aptible | Change the `FROM` line's tag in the `Dockerfile`, commit, `git push aptible main` | + +On Kubernetes, ECS, Convox and Aptible the release command runs first, and if it fails nothing moves: the old release +keeps running. Read its output, fix the cause and run the upgrade again. + +Make the changes the upgrade notes asked for in the same step: a new service in the setup's config, a new setting in +the platform's secret store. + +## 5. Check + +1. `https:///health` returns `200`. +2. `run_as_deploy rake checks:health_check checks:generate_test_submission` passes, run the way the setup runs one-off + commands (the folder's README). +3. The commit on `/admin/system` starts with the new version. + +## Going back + +Our migrations keep the previous release working, so going back one release needs no database restore: deploy the +previous tag the same way (`helm rollback`, set `image_tag` back and deploy, `convox releases rollback `, +`./update.sh `). Going back further than one release means restoring the backup: ask the user to +contact support@docspring.com first. Either way, tell DocSpring what went wrong. diff --git a/.claude/skills/docspring-enterprise-install b/.claude/skills/docspring-enterprise-install new file mode 120000 index 0000000..a8f4d2a --- /dev/null +++ b/.claude/skills/docspring-enterprise-install @@ -0,0 +1 @@ +../../.agents/skills/docspring-enterprise-install \ No newline at end of file diff --git a/.claude/skills/docspring-enterprise-operate b/.claude/skills/docspring-enterprise-operate new file mode 120000 index 0000000..79e1e64 --- /dev/null +++ b/.claude/skills/docspring-enterprise-operate @@ -0,0 +1 @@ +../../.agents/skills/docspring-enterprise-operate \ No newline at end of file diff --git a/.claude/skills/docspring-enterprise-upgrade b/.claude/skills/docspring-enterprise-upgrade new file mode 120000 index 0000000..b941889 --- /dev/null +++ b/.claude/skills/docspring-enterprise-upgrade @@ -0,0 +1 @@ +../../.agents/skills/docspring-enterprise-upgrade \ No newline at end of file diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 9023f88..0000000 --- a/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -convox.example.yml -install.rb -switch_rack.sh -update.sh -README.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..de1b2fb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,89 @@ +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 + # tflint --init downloads its rulesets from GitHub, which rate-limits a runner's anonymous requests + - run: tflint --init && tflint --recursive + env: + GITHUB_TOKEN: ${{ github.token }} + - 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 -no-reap -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/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index b39fbf2..0000000 --- a/.rubocop.yml +++ /dev/null @@ -1,63 +0,0 @@ -require: rubocop-rspec - -AllCops: - NewCops: enable - TargetRubyVersion: 2.5 - -Style/MixinUsage: - Exclude: - - install.rb - -Layout/LineLength: - Max: 100 - -Style/StringLiterals: - EnforcedStyle: single_quotes - -Style/Documentation: - Enabled: false - -Style/IfUnlessModifier: - Enabled: false - -Metrics/AbcSize: - Enabled: false - -Metrics/ClassLength: - Enabled: false - -Metrics/CyclomaticComplexity: - Enabled: false - -Metrics/PerceivedComplexity: - Enabled: false - -Metrics/MethodLength: - Enabled: false - -Metrics/ModuleLength: - Enabled: false - -Metrics/ParameterLists: - Enabled: false - -Metrics/BlockLength: - Enabled: false - -Metrics/BlockNesting: - Max: 7 - -RSpec/MessageSpies: - Enabled: false - -RSpec/StubbedMock: - Enabled: false - -RSpec/MultipleExpectations: - Enabled: false - -RSpec/ExampleLength: - Enabled: false - -RSpec/AnyInstance: - Enabled: false 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..c7a2da7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,58 @@ +# 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 keep the previous release working, so going back one release needs no restore; further back, the + backup is the only way to undo a migration. +- 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/aptible/.aptible.yml b/aptible/.aptible.yml new file mode 100644 index 0000000..a9a9a3b --- /dev/null +++ b/aptible/.aptible.yml @@ -0,0 +1,4 @@ +# Runs before each release's containers start: creates the database schema and the first admin user on a new app, +# and migrates the database on an upgrade +before_release: + - run_as_deploy rake db:prepare diff --git a/aptible/.dockerignore b/aptible/.dockerignore new file mode 100644 index 0000000..3e1bc29 --- /dev/null +++ b/aptible/.dockerignore @@ -0,0 +1,5 @@ +* +!Dockerfile +!crontab +!Procfile +!.aptible.yml diff --git a/aptible/AGENTS.md b/aptible/AGENTS.md new file mode 100644 index 0000000..816813a --- /dev/null +++ b/aptible/AGENTS.md @@ -0,0 +1,14 @@ +# aptible + +DocSpring Enterprise as an Aptible Dockerfile deploy. Read the root `AGENTS.md` first, and `README.md` here. + +- `Procfile` implements the services in `../reference/deployment.yml`, `.aptible.yml` its release command, and + `crontab` (run by supercronic, the `cron` service) its three scheduled tasks. `scripts/check_deployments` checks + them. +- Aptible reads `Procfile` and `.aptible.yml` from the root of the pushed repository, so customers deploy a copy of + this folder as its own repository. +- Pin supercronic by version and SHA-256 for both architectures. When you bump it, take the digests from the GitHub + release's assets (`gh release view --repo aptible/supercronic --json assets`). +- Check a change: `docker build .` (on any architecture), then + `docker run --rm --entrypoint sh -c 'supercronic -test /etc/docspring-crontab'`. +- We have no Aptible account to test in: say so in a pull request that changes how this deploys. diff --git a/aptible/Dockerfile b/aptible/Dockerfile new file mode 100644 index 0000000..4b9bc1d --- /dev/null +++ b/aptible/Dockerfile @@ -0,0 +1,19 @@ +# DocSpring Enterprise on Aptible (a Dockerfile deploy). Set the release you want here, then `git push aptible`. +# Every release: https://docspring.com/enterprise-releases +FROM docspringcom/docspring-enterprise:c648191044 + +# Aptible has no scheduler of its own, so the `cron` service runs DocSpring's three scheduled tasks with supercronic +# (MIT licensed, by Aptible): https://github.com/aptible/supercronic +ARG TARGETARCH +ARG SUPERCRONIC_VERSION=v0.2.51 +RUN set -eux; \ + case "${TARGETARCH:-amd64}" in \ + amd64) sha=cc232108374e8e2b537045f2d5eaa1229f619db314c3ba6a14d38b35dc0aa123 ;; \ + arm64) sha=4ae22576a78223d8ccdf5f3b3660a5cbb5288416bf0ca96afc4a36d195932b94 ;; \ + *) echo "Unsupported architecture: ${TARGETARCH}" >&2; exit 1 ;; \ + esac; \ + curl -fsSL -o /usr/local/bin/supercronic \ + "https://github.com/aptible/supercronic/releases/download/${SUPERCRONIC_VERSION}/supercronic-linux-${TARGETARCH:-amd64}"; \ + echo "${sha} /usr/local/bin/supercronic" | sha256sum -c -; \ + chmod 0755 /usr/local/bin/supercronic +COPY crontab /etc/docspring-crontab diff --git a/aptible/Procfile b/aptible/Procfile new file mode 100644 index 0000000..78266e2 --- /dev/null +++ b/aptible/Procfile @@ -0,0 +1,4 @@ +web: run_as_deploy puma -C config/puma.rb +worker: run_as_deploy sidekiq +worker_gj: run_as_deploy good_job +cron: supercronic /etc/docspring-crontab diff --git a/aptible/README.md b/aptible/README.md new file mode 100644 index 0000000..58d4809 --- /dev/null +++ b/aptible/README.md @@ -0,0 +1,90 @@ +# DocSpring Enterprise on Aptible + +Runs DocSpring Enterprise as an [Aptible](https://www.aptible.com) app, with Aptible's managed PostgreSQL and Redis, +and an S3 bucket in your own AWS account for files. + +The full guide is in our docs: https://docspring.com/docs/enterprise/deploy/aptible/ + +This folder is a Dockerfile deploy: Aptible builds an image from `Dockerfile`, which starts from the DocSpring +Enterprise image and adds [supercronic](https://github.com/aptible/supercronic) to run the scheduled tasks (Aptible has +no scheduler). `Procfile` lists the services and `.aptible.yml` migrates the database before each release. + +## What you need + +- An Aptible account and the [Aptible CLI](https://www.aptible.com/docs/reference/aptible-cli/overview), signed in + with `aptible login`. +- Your DocSpring license key and Docker Hub credentials, which DocSpring sends you. +- An S3 bucket for files: private, with the CORS rule from + [the file storage docs](https://docspring.com/docs/enterprise/requirements/#file-storage), and an IAM user with + access to that bucket only. + +## Install + +Aptible deploys the root of a git repository, so put this folder in a repository of its own: + +```bash +cp -R aptible ~/docspring-aptible && cd ~/docspring-aptible && git init && git add -A && git commit -m 'DocSpring' +``` + +Create the app and its databases (choose your environment with `--environment`): + +```bash +aptible apps:create docspring +aptible db:create docspring-postgres --type postgresql --version 17 +aptible db:create docspring-redis --type redis --version 7.0 +aptible db:url docspring-postgres # the DATABASE_URL +aptible db:url docspring-redis # the REDIS_URL +``` + +Set its configuration. Generate the secrets once and keep a copy: they encrypt your data. + +```bash +aptible config:set --app docspring \ + APTIBLE_PRIVATE_REGISTRY_USERNAME='' \ + APTIBLE_PRIVATE_REGISTRY_PASSWORD='' \ + DOCSPRING_LICENSE='' \ + DOCSPRING_DOMAIN_NAME=docspring.example.com \ + DOCSPRING_FORCE_SSL=true \ + DATABASE_URL='' \ + REDIS_URL='' \ + SECRET_KEY_BASE="$(openssl rand -hex 64)" \ + DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY="$(openssl rand -hex 32)" \ + DOCSPRING_ADMIN_EMAIL=admin@example.com \ + DOCSPRING_ADMIN_PASSWORD='' \ + DOCSPRING_AWS_UPLOADS_S3_BUCKET='' \ + DOCSPRING_AWS_UPLOADS_S3_REGION='' \ + DOCSPRING_AWS_ACCESS_KEY_ID='' \ + DOCSPRING_AWS_ACCESS_KEY_SECRET='' \ + DOCSPRING_DISABLE_EMAILS=true +``` + +Deploy it, then give `web` an HTTPS endpoint on container port 4001: + +```bash +git remote add aptible "$(aptible apps:info docspring | sed -n 's/^Git Remote: //p')" +git push aptible main +aptible endpoints:https:create --app docspring --default-domain web # or --managed-tls with your own domain +``` + +Scale the services (memory in MB): + +```bash +aptible apps:scale --app docspring --container-count 2 --container-size 2048 web +aptible apps:scale --app docspring --container-count 2 --container-size 4096 worker +aptible apps:scale --app docspring --container-count 1 --container-size 1024 worker_gj +aptible apps:scale --app docspring --container-count 1 --container-size 1024 cron +``` + +Sign in with `DOCSPRING_ADMIN_EMAIL` and `DOCSPRING_ADMIN_PASSWORD`, and change the password. Then set up email: +[email notifications](https://docspring.com/docs/enterprise/configuration/email-notifications/). + +## Upgrade + +Read the release's notes at https://docspring.com/enterprise-releases, change the tag in `Dockerfile`'s `FROM` +line, commit and `git push aptible main`. `.aptible.yml` migrates the database before the new containers start. + +## Notes + +- Aptible doesn't let containers add Linux capabilities, so `run_as_deploy` can't add its firewall rule for the cloud + metadata address. It logs a warning and carries on. Aptible's own network isolation applies instead. +- `worker_gj` needs a direct database connection: use the database's own URL, not a connection pooler's. diff --git a/aptible/crontab b/aptible/crontab new file mode 100644 index 0000000..559a71a --- /dev/null +++ b/aptible/crontab @@ -0,0 +1,4 @@ +# DocSpring's scheduled tasks (UTC). Each release decides what these run, so this file never needs to change. +15 * * * * run_as_deploy rake timers:hourly +0 3 * * * run_as_deploy rake timers:daily +0 4 * * 0 run_as_deploy rake timers:weekly diff --git a/aws-ecs/.tflint.hcl b/aws-ecs/.tflint.hcl new file mode 100644 index 0000000..1dfa586 --- /dev/null +++ b/aws-ecs/.tflint.hcl @@ -0,0 +1,14 @@ +config { + call_module_type = "local" +} + +plugin "terraform" { + enabled = true + preset = "recommended" +} + +plugin "aws" { + enabled = true + version = "0.50.0" + source = "github.com/terraform-linters/tflint-ruleset-aws" +} diff --git a/aws-ecs/AGENTS.md b/aws-ecs/AGENTS.md new file mode 100644 index 0000000..67fd169 --- /dev/null +++ b/aws-ecs/AGENTS.md @@ -0,0 +1,43 @@ +# aws-ecs + +Terraform for DocSpring Enterprise on ECS Fargate: `modules/docspring/` (the module), `example/` (a root module that +calls it), `scripts/deploy` (runs the release command, then moves the services and schedules). README.md is for +customers. + +## Validate + +Static checks only. Never run `plan` or `apply` against an AWS account, and use no AWS credentials. + +```sh +cd aws-ecs +terraform fmt -check -recursive +(cd example && terraform init -backend=false && terraform validate) # tofu works the same +tflint --init && tflint --chdir=example --config="$PWD/.tflint.hcl" && tflint --chdir=modules/docspring --config="$PWD/.tflint.hcl" +shellcheck scripts/deploy +trivy config . +``` + +Every `#trivy:ignore` has a comment saying why. Don't add one without, and remove one once its check stops firing. +Delete `example/.terraform/` and `example/.terraform.lock.hcl` after validating: customers create their own. + +## Invariants + +- Keep in step with `../reference/deployment.yml`: the commands, release command and scheduled tasks are in + `local.services`, `local.release_command` and `local.scheduled_tasks` (`modules/docspring/main.tf`), the sizes in + `local.default_task_sizes` (rounded up to Fargate sizes), the container settings in `ecs.tf`, the required + environment in `ecs.tf` and `secrets.tf`, the S3 CORS rule in `data_stores.tf`. When the contract changes, change + these in the same PR. +- Services and schedules ignore `task_definition` changes; only `scripts/deploy` moves them, after the release + command succeeds. Don't make services follow Terraform directly: new code would run before its migrations. + Task definitions use `skip_destroy` so old revisions stay registered for rollbacks. +- Fargate can only add `SYS_PTRACE`, so the container drops a list of capabilities instead of `ALL`, keeping + `SETUID`, `SETGID` (gosu) and `KILL` (tini forwarding SIGTERM to the deploy user's process). Don't switch to + `drop = ["ALL"]`: run_as_deploy can't switch users then. +- The database password is generated by Terraform, not `manage_master_user_password`: RDS rotates managed passwords + (every 7 days by default) and the tasks read `DATABASE_URL` only at startup. +- Never let anything regenerate `random_id.submission_data_encryption_key`: it encrypts stored data. +- Terraform and OpenTofu 1.6: no cross-variable validation (1.9), write-only arguments or ephemeral resources (1.11). + Use `lifecycle.precondition` for checks across variables. +- `scripts/deploy` runs on macOS's bash 3.2: no associative arrays, `mapfile` or `${var,,}`. Keep it shellcheck-clean + and dependent only on the AWS CLI (no jq). +- No customer names or real account IDs; examples use docspring.example.com and 123456789012. diff --git a/aws-ecs/README.md b/aws-ecs/README.md new file mode 100644 index 0000000..ed0b10e --- /dev/null +++ b/aws-ecs/README.md @@ -0,0 +1,224 @@ +# DocSpring Enterprise on AWS ECS (Fargate) + +A Terraform module that runs DocSpring Enterprise in your own AWS account on ECS Fargate, with everything it needs: + +- a VPC with public and private subnets in 2 or 3 availability zones and a NAT gateway (or your existing VPC); +- RDS PostgreSQL 17 (encrypted, 7 days of point-in-time backups, deletion protection, optional Multi-AZ); +- ElastiCache Valkey (Redis compatible) with TLS and an auth token; +- a private, versioned, encrypted S3 bucket for uploaded and generated files; +- an Application Load Balancer with HTTPS (your ACM certificate, or one the module creates in your Route 53 zone); +- the `web`, `worker` and `worker_gj` services on Fargate (Graviton by default), with CPU autoscaling for web and + worker and a deployment circuit breaker that rolls back a failed rollout; +- the release command and the hourly, daily and weekly scheduled tasks (EventBridge Scheduler); +- the app's secrets in Secrets Manager, and least-privilege IAM roles. + +`modules/docspring/` is the module. `example/` is a root module that calls it: copy it to start your own. +`scripts/deploy` puts a release live. What every DocSpring deployment runs is in +[`reference/deployment.yml`](../reference/deployment.yml). + +## Prerequisites + +- Terraform 1.6 or later, or OpenTofu 1.6 or later. +- The AWS CLI v2, and the [Session Manager plugin](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) + if you want a shell or Rails console in a running task (ECS Exec). +- Bash, for `scripts/deploy` (macOS's built-in bash 3.2 works). +- From DocSpring: your license key and the Docker Hub username and access token for the private image + `docspringcom/docspring-enterprise`. +- A host name for DocSpring, such as `docspring.example.com`, and either a Route 53 hosted zone for it (the module + then creates the certificate and DNS record) or an ACM certificate for it in the region you install in. +- An email provider (SMTP, Postmark, SendGrid, Mailgun or Amazon SES) for invitations and password resets: + [Email notifications](https://docspring.com/docs/enterprise/configuration/email-notifications/). + +### AWS credentials + +Sign in with an AWS CLI profile backed by IAM Identity Center (SSO) or an assumed role, never IAM user access keys: + +```sh +aws configure sso --profile docspring-admin # once +aws sso login --profile docspring-admin +``` + +Set `aws_profile = "docspring-admin"` in `terraform.tfvars` (or `export AWS_PROFILE=docspring-admin`), and use the +same profile for `scripts/deploy`. The person or pipeline that runs Terraform needs to create everything listed +above; the deploy script needs `ecs:RunTask`, `ecs:DescribeTasks`, `ecs:DescribeTaskDefinition`, +`ecs:DescribeServices`, `ecs:UpdateService`, `scheduler:GetSchedule`, `scheduler:UpdateSchedule`, `logs:GetLogEvents` +and `iam:PassRole` on the module's task, execution and scheduler roles. + +## Install + +1. Copy `example/` somewhere you keep infrastructure code, and in it copy `terraform.tfvars.example` to + `terraform.tfvars` and fill it in. It holds secrets: keep it out of version control (or pass the secret values as + `TF_VAR_license_key`, `TF_VAR_registry_password` and `TF_VAR_admin_password`). Settings that aren't in the example + (task sizes, counts, the database and Redis sizes, an existing VPC) are the module's variables in + `modules/docspring/variables.tf`: pass them in `main.tf`. +2. Store the state remotely. The Terraform state contains the generated secrets (the database password, the Redis + token, `SECRET_KEY_BASE` and the submission data encryption key), so keep it in an encrypted S3 bucket only your + administrators can read: uncomment the `backend "s3"` block in `main.tf`. +3. Apply: + + ```sh + terraform init + terraform apply + ``` + + This takes about 15 to 20 minutes, most of it RDS and ElastiCache. The services start, but they can't serve + anything until the database has its schema. + +4. Run the deploy command that `terraform output deploy_command` prints, from the `aws-ecs` folder: + + ```sh + ./scripts/deploy --region us-east-1 --cluster docspring --name docspring + ``` + + It runs the release command (`rake db:prepare`), which loads the schema and creates the admin user, then + restarts the services and waits until they're healthy. + +5. If you didn't give the module a Route 53 zone, point your host name at `terraform output alb_dns_name` (a CNAME, or + an alias record with `alb_zone_id`). + +6. Back up the submission data encryption key somewhere outside AWS, such as your password manager. It encrypts the + data DocSpring stores, and losing it makes that data unreadable: + + ```sh + aws secretsmanager get-secret-value --secret-id "$(terraform output -raw app_secret_arn)" \ + --query SecretString --output text | python3 -c 'import json,sys; print(json.load(sys.stdin)["DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY"])' + ``` + +### First sign-in + +Open `https://docspring.example.com` and sign in with `admin_email` and `admin_password`. Change the password straight +away (the value in Terraform is only used to create the user on an empty database). The admin dashboard is at +`/admin`. + +## Settings + +- Settings that aren't secret go in `extra_environment`, secret ones (an email provider's token, an SMTP password) in + `extra_secrets`. Every setting: + [Environment variables](https://docspring.com/docs/enterprise/configuration/environment-variables/). +- The module sets `DOCSPRING_DOMAIN_NAME`, `DOCSPRING_FORCE_SSL=true` (the load balancer terminates TLS), the S3 + bucket and region, and `PORT=4001` on web. The app uses the task role for S3: there are no access keys. +- After changing settings, run `terraform apply` and then the deploy command: new settings only reach tasks that + start after the change. + +## Upgrade + +1. Pick a release from [docspring.com/enterprise-releases](https://docspring.com/enterprise-releases) and read its + notes. +2. Set `image_tag` to it in `terraform.tfvars` and run `terraform apply`. This registers new task definitions and + changes nothing that's running: the services and schedules ignore task definition changes. +3. Run the deploy command. It runs the release command (database migrations) on the new release, and only if it + succeeds moves the services to the new release, waits until every rollout has finished, and then moves the + scheduled tasks. + +Why two steps: Terraform has no way to run a one-off task and wait for it before updating a service, short of a +local command in Terraform, which breaks in CI runners and Terraform Cloud. If the services followed Terraform +directly, `terraform apply` would start the new code before its migrations ran. With the deploy script, new code +never runs against a database that hasn't been migrated for it, and a failed migration leaves everything on the old +release (`terraform plan` still shows nothing to change for the services afterwards). If you forget step 3, nothing +moves: the old release keeps running. + +If a rollout fails, ECS rolls that service back to its previous task definition and the script stops with the +reason. The migrations have already run; the previous release works with them. To go back to an earlier release, set +`image_tag` back, apply and deploy again (migrations aren't reversed). + +`scripts/deploy` always starts new tasks, even when nothing changed. That's also how to make running tasks pick up a +changed secret. + +### Image pulls + +Fargate doesn't cache images, so every task that starts pulls the whole image from Docker Hub, through the NAT +gateway: each service task, each deploy and each scheduled task run (the hourly one alone is about 730 pulls a +month). The image is large (it includes Chromium, LibreOffice and the field detection model), so that's NAT data +charges and Docker Hub pulls. To cut both, copy the image to Amazon ECR with an +[ECR pull-through cache rule](https://docs.aws.amazon.com/AmazonECR/latest/userguide/pull-through-cache.html) for +Docker Hub (with the Docker Hub credentials in a Secrets Manager secret whose name starts with `ecr-pullthroughcache/`), +add VPC interface endpoints for `ecr.api` and `ecr.dkr`, and set `image_repository` to the cache's repository, such +as `123456789012.dkr.ecr.us-east-1.amazonaws.com/docker-hub/docspringcom/docspring-enterprise`, with +`registry_username = null`. The module then grants the execution role ECR pull permissions; the pull-through cache +also needs `ecr:CreateRepository` and `ecr:BatchImportUpstreamImage` the first time it pulls a tag. This module +doesn't build the cache. + +## One-off commands + +- A task that runs a command and exits, such as a rake task: `terraform output run_task_command` prints an + `aws ecs run-task` command (with `rake about` as the example: change the command in `--overrides`). Every command + starts with `run_as_deploy`. Its logs are in the release log group (`terraform output log_groups`). +- A shell or Rails console in a running web task (ECS Exec, on by default): `terraform output ecs_exec_command`. + In the shell, run `run_as_deploy bin/rails console`. The shell itself runs as root with the container's few + capabilities, so run the app's commands through `run_as_deploy`. Who can do this is controlled by the + `ecs:ExecuteCommand` IAM permission; turn it off with `enable_ecs_exec = false` (then apply and deploy). + +## Container security on Fargate + +`reference/deployment.yml` asks for containers that start as root with every Linux capability dropped and only +`SETUID`, `SETGID` and `KILL` added, plus `NET_ADMIN` where the platform allows it: `run_as_deploy` uses `NET_ADMIN` +to block the cloud metadata address (169.254.169.254) with iptables, then switches to the unprivileged `deploy` user. Fargate only lets a task add one +capability, `SYS_PTRACE`. So this module drops every capability in the default set except `SETUID` and `SETGID` (to +switch users) and `KILL` (so the stop signal reaches the app, which then shuts down cleanly). Once the app runs as `deploy` it has no capabilities. + +Without `NET_ADMIN`, `run_as_deploy` logs `Skipping iptables configuration` at startup and carries on. That costs +nothing on Fargate: the EC2 instance metadata service isn't reachable from a Fargate task, so there's no instance +role to protect. A task's own credentials come from the ECS credentials endpoint (169.254.170.2), and the task role +can only read and write the uploads bucket. + +If your policies require the firewall rule itself, run the tasks on ECS with EC2 container instances instead of +Fargate, where `NET_ADMIN` can be added. There, also set `ECS_AWSVPC_BLOCK_IMDS=true` in the ECS agent's config and an +IMDS hop limit of 1 on the instances, so tasks can't reach the instance role. This module doesn't build that option. + +Other settings: the containers aren't privileged, the root file system is writable (the app needs it), and Fargate +applies the container runtime's default seccomp profile. ECS has no equivalent of `allowPrivilegeEscalation: false` +on Fargate. + +## Costs + +Rough monthly costs for the defaults in us-east-1, at on-demand prices in late 2026. Check the +[AWS Pricing Calculator](https://calculator.aws/) for your region and usage. + +| Component | Defaults | About | +| --- | --- | --- | +| Fargate, web | 2 tasks, 1 vCPU and 2 GB each, ARM64 | $58 | +| Fargate, worker | 2 tasks, 1 vCPU and 3 GB each | $63 | +| Fargate, worker_gj | 1 task, 0.5 vCPU and 1 GB | $14 | +| Fargate, scheduled tasks | a few minutes an hour, 1 vCPU and 2 GB | $2 to $5 | +| RDS PostgreSQL | db.t4g.medium, single-AZ, 50 GB gp3 | $53 | +| ElastiCache Valkey | cache.t4g.small, one node | $19 | +| NAT gateway | one, plus $0.045 per GB through it (image pulls) | $33 plus data | +| Application Load Balancer | plus load balancer capacity units | $22 | +| Public IPv4 addresses | load balancer (one per AZ) and NAT gateway | $11 | +| CloudWatch Logs, Secrets Manager, S3 | depends on volume | $5 to $20 | +| **Total** | | **about $280 to $300, plus data** | + +Changes from the defaults: X86_64 adds about 25% to Fargate. Multi-AZ doubles the database (`db_multi_az`, about ++$53) or Redis (`redis_multi_az`, about +$19). One NAT gateway per AZ adds about $33 each. Autoscaling adds tasks +under load, up to `web_max_count` and `worker_max_count`. Container Insights adds CloudWatch charges. + +## Destroy + +The database and load balancer have deletion protection, the database takes a final snapshot, and S3 won't delete a +bucket that has files in it. To remove an install: + +1. Set `deletion_protection = false`, run `terraform apply`. +2. Empty the uploads bucket, including old versions (in the S3 console, "Empty"). +3. Run `terraform destroy`. + +What's left behind: the database's final snapshot (`-final`, delete it when you no longer need it), the +Secrets Manager secrets for 30 days (restorable until then), and the old task definition revisions (inactive, free). +The final snapshot needs the submission data encryption key to be useful: keep your copy of it as long as you keep +the snapshot. + +## Rotating the generated secrets + +- Database password: `terraform apply -replace=module.docspring.random_password.db`, then the deploy command. RDS + changes the password during the apply, so new database connections fail until the deploy command has restarted + the tasks: do it in a quiet period. +- Redis token: `terraform apply -replace=module.docspring.random_password.redis`, then the deploy command (ElastiCache + accepts both tokens during the rotation). +- `SECRET_KEY_BASE`: `terraform apply -replace=module.docspring.random_id.secret_key_base`, then deploy. Everyone is + signed out. +- Never replace the submission data encryption key: data encrypted with it can't be read with a new one. + +## Moving an existing install here + +Set `secret_key_base` and `submission_data_encryption_key` to the values your current install uses, restore its +database into the new RDS instance and copy its files into the new bucket before the first deploy. Ask DocSpring +support for help with the move. diff --git a/aws-ecs/example/.terraform.lock.hcl b/aws-ecs/example/.terraform.lock.hcl new file mode 100644 index 0000000..bd30ab5 --- /dev/null +++ b/aws-ecs/example/.terraform.lock.hcl @@ -0,0 +1,47 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.73.0" + constraints = "~> 6.0" + hashes = [ + "h1:87t8o/A0y2RE3PtCLx/BiASSrDrKSETYTF9jRvKc7aw=", + "zh:0f7403264fbfbcad526a5ddb9553be6ab12dba14e5901d0c2ccabc38d9ccf9a0", + "zh:26be4e8afc94ef29c98b8219dc49b19ce21a04d3f2b4e5be6116e9526ece0355", + "zh:2ba661a4a782fba053c411ce4d828dc148d7ed3998d073a28370a559400b1578", + "zh:2c422d0edd37bf7470c84f1d1f76487f30948768878204a65a18189bf878467a", + "zh:49f9d1486d48033d298977f7c288f8bbb22bb246f00926d1cb8b0bb98985451c", + "zh:4f946cf11667e1f3bce53fd5ad92eccf47fafaa1bbaa68c742173db61773a1da", + "zh:70beb5e13ddcdbeecb2a78be2b75d09a0fc6ce7e69b574c84a90924fd4262406", + "zh:8c5b974104ff9a887b29fdb2700cdbb5e6fd2eceef1cc3b28f523beda4fd8dfb", + "zh:9252068667bc6528ee6e83e837f3c2f901756136a33442455d61c6fa34e1160a", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:9d086b792598b43e87502d47c4a3f388465b3a21a6a6b2783e48c89dee1f0543", + "zh:b5e6e77a43c1655285d99145b2cf0cc2da7a6c6ea3531d000cf8cca2c717693b", + "zh:b7ebe893e5ec76b362b61ffb28c67b40d890e0f59f5f2f8829765b16ee3e53b0", + "zh:c8c1e186839ad3cba37b427181af1e62eaf06c6daa5dca29105e1981dfaeb4c2", + "zh:e988377e7aea51e1fefe0b52c78bc725a11327051e20a71f81069191ee077d2d", + "zh:ee9188027919459a48bf9bac8f8f1dd172f5be198b88c2c47789b6daa8bb8bcb", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.9.1" + constraints = "~> 3.6" + hashes = [ + "h1:PlW+UZ4EElQF3NQwf41KQwavFujab3Czc51zu9dyVM8=", + "zh:05f4734c1f0be840b711b3eff259ebc5fca436784c728955b1678078466f48d7", + "zh:0b91bf19371d012434eba1deeb6aab77158def9b39601dcbd94450b3974a2a26", + "zh:0ee6eacd47ec00183d55d726a4b6c4ce951a199f944bf22f1aa58392ebdfa7a2", + "zh:19388a4074b76a89a43a6c8328d7ae8ee2e7de3d346af51e80d3e6d3d12925f1", + "zh:23e74d48c5e2ac2e823fd527f49fee9db37d32a1990c9e3bf126ead697b843eb", + "zh:3cabf7fbd096c520064aae3aba61aba670af83ab91291a71fa1b1332929c2b7f", + "zh:5c0a3b8af0be60be4eca12ddee385cfa8babc1ec8e98cdf9de2f2274c73eabfa", + "zh:60b4f8a8ef18f52bf8e19215229dae408bee732825964092db7c989fd2de4097", + "zh:7359015acfedcbd6366f2329c854cf8d3c8ca5cd0faa89d2d37db358d6eba6c5", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7b38758402f0e13a1071162da28994023cd2ac676e54af350c9ffd8dfa73fa7b", + "zh:7c7fbb8895eb75bb4de1f933e98553bd99c8d048c89a925ddba490aa5a67f7dc", + "zh:8c2b8c6a7ccdec16b73e2fb9f3700ea097f58c592571e4c5de60c93d2301732c", + ] +} diff --git a/aws-ecs/example/main.tf b/aws-ecs/example/main.tf new file mode 100644 index 0000000..853dc0a --- /dev/null +++ b/aws-ecs/example/main.tf @@ -0,0 +1,67 @@ +terraform { + required_version = ">= 1.6" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + random = { + source = "hashicorp/random" + version = "~> 3.6" + } + } + + # The state holds the generated secrets (the database password, SECRET_KEY_BASE, the encryption key). Keep it in an + # encrypted S3 bucket that only your administrators can read, not on a laptop. Create the bucket first, then + # uncomment this and run `terraform init -migrate-state`. use_lockfile needs Terraform 1.10 or OpenTofu 1.10; on + # older versions use dynamodb_table instead. + # + # backend "s3" { + # bucket = "example-terraform-state" + # key = "docspring/terraform.tfstate" + # region = "us-east-1" + # encrypt = true + # use_lockfile = true + # } +} + +provider "aws" { + region = var.region + # An AWS CLI profile (SSO or an assumed role): `aws sso login --profile ` first. Leave it null to use + # AWS_PROFILE or the default credentials. Don't use IAM user access keys. + profile = var.aws_profile + + default_tags { + tags = { + Application = "DocSpring Enterprise" + ManagedBy = "Terraform" + } + } +} + +module "docspring" { + source = "../modules/docspring" + + name = var.name + domain_name = var.domain_name + + image_tag = var.image_tag + registry_username = var.registry_username + registry_password = var.registry_password + license_key = var.license_key + + admin_email = var.admin_email + admin_password = var.admin_password + + route53_zone_id = var.route53_zone_id + certificate_arn = var.certificate_arn + + cpu_architecture = var.cpu_architecture + db_multi_az = var.db_multi_az + redis_multi_az = var.redis_multi_az + deletion_protection = var.deletion_protection + + extra_environment = var.extra_environment + extra_secrets = var.extra_secrets +} diff --git a/aws-ecs/example/outputs.tf b/aws-ecs/example/outputs.tf new file mode 100644 index 0000000..2bde6d6 --- /dev/null +++ b/aws-ecs/example/outputs.tf @@ -0,0 +1,43 @@ +output "url" { + value = module.docspring.url +} + +output "alb_dns_name" { + value = module.docspring.alb_dns_name +} + +output "alb_zone_id" { + value = module.docspring.alb_zone_id +} + +output "cluster_name" { + value = module.docspring.cluster_name +} + +output "service_names" { + value = module.docspring.service_names +} + +output "log_groups" { + value = module.docspring.log_groups +} + +output "deploy_command" { + value = module.docspring.deploy_command +} + +output "run_task_command" { + value = module.docspring.run_task_command +} + +output "ecs_exec_command" { + value = module.docspring.ecs_exec_command +} + +output "nat_public_ips" { + value = module.docspring.nat_public_ips +} + +output "app_secret_arn" { + value = module.docspring.app_secret_arn +} diff --git a/aws-ecs/example/terraform.tfvars.example b/aws-ecs/example/terraform.tfvars.example new file mode 100644 index 0000000..e3d7ffe --- /dev/null +++ b/aws-ecs/example/terraform.tfvars.example @@ -0,0 +1,38 @@ +# Copy this to terraform.tfvars (git ignores *.tfvars) and fill it in. It holds secrets: keep it out of version +# control, or pass the secret ones as TF_VAR_license_key, TF_VAR_registry_password and TF_VAR_admin_password instead. + +region = "us-east-1" +aws_profile = "docspring-admin" # an SSO or assumed-role profile from ~/.aws/config + +name = "docspring" +domain_name = "docspring.example.com" + +# A Route 53 zone for docspring.example.com (or example.com): the module creates the certificate and DNS record. +# Without one, set certificate_arn to an ACM certificate for domain_name in this region, and point your DNS at the +# alb_dns_name output. +route53_zone_id = "Z0123456789EXAMPLE" +# certificate_arn = "arn:aws:acm:us-east-1:123456789012:certificate/00000000-0000-0000-0000-000000000000" + +# From https://docspring.com/enterprise-releases. Change it to upgrade, then terraform apply and the deploy command. +image_tag = "c648191044" + +# From DocSpring, with your license key +registry_username = "your-docker-hub-username" +registry_password = "dckr_pat_example" +license_key = "your-license-key" + +admin_email = "admin@example.com" +admin_password = "change-me-after-signing-in" + +# cpu_architecture = "X86_64" +# db_multi_az = true +# redis_multi_az = true +# deletion_protection = false # only to destroy the install + +extra_environment = { + DOCSPRING_FROM_EMAIL = "DocSpring " +} + +extra_secrets = { + # DOCSPRING_POSTMARK_API_TOKEN = "..." +} diff --git a/aws-ecs/example/variables.tf b/aws-ecs/example/variables.tf new file mode 100644 index 0000000..47f5e5d --- /dev/null +++ b/aws-ecs/example/variables.tf @@ -0,0 +1,106 @@ +# The settings most installs change. Every other module setting has a default: see ../modules/docspring/variables.tf, +# and pass any of them to the module in main.tf. + +variable "region" { + description = "The AWS region to install in." + type = string +} + +variable "aws_profile" { + description = "The AWS CLI profile to use (SSO or an assumed role). Null uses AWS_PROFILE or the default credentials." + type = string + default = null +} + +variable "name" { + description = "A short name for this install. Every resource name starts with it." + type = string + default = "docspring" +} + +variable "domain_name" { + description = "The host name people use to reach DocSpring, such as docspring.example.com." + type = string +} + +variable "route53_zone_id" { + description = "A Route 53 hosted zone for domain_name: the module creates the certificate and the DNS record in it." + type = string + default = null +} + +variable "certificate_arn" { + description = "An existing ACM certificate for domain_name, if you don't use route53_zone_id." + type = string + default = null +} + +variable "image_tag" { + description = "The DocSpring Enterprise release, such as c648191044 (https://docspring.com/enterprise-releases)." + type = string +} + +variable "registry_username" { + description = "The Docker Hub username DocSpring sent you." + type = string +} + +variable "registry_password" { + description = "The Docker Hub access token DocSpring sent you." + type = string + sensitive = true +} + +variable "license_key" { + description = "Your DocSpring Enterprise license key." + type = string + sensitive = true +} + +variable "admin_email" { + description = "The first admin user's email address." + type = string +} + +variable "admin_password" { + description = "The first admin user's password. Change it after you sign in." + type = string + sensitive = true +} + +variable "cpu_architecture" { + description = "ARM64 (Graviton) or X86_64." + type = string + default = "ARM64" +} + +variable "db_multi_az" { + description = "A standby database in a second AZ." + type = bool + default = false +} + +variable "redis_multi_az" { + description = "A Redis replica in a second AZ." + type = bool + default = false +} + +variable "deletion_protection" { + description = "Deletion protection on the database and load balancer." + type = bool + default = true +} + +variable "extra_environment" { + description = "Other settings that aren't secret." + type = map(string) + default = {} +} + +variable "extra_secrets" { + description = "Other secret settings, such as an email provider's API token." + type = map(string) + default = {} + sensitive = true +} diff --git a/aws-ecs/modules/docspring/alb.tf b/aws-ecs/modules/docspring/alb.tf new file mode 100644 index 0000000..3138334 --- /dev/null +++ b/aws-ecs/modules/docspring/alb.tf @@ -0,0 +1,137 @@ +# The load balancer terminates TLS and forwards to the web tasks on port 4001. HTTP redirects to HTTPS. + +locals { + create_certificate = var.certificate_arn == null && var.route53_zone_id != null + certificate_arn = local.create_certificate ? aws_acm_certificate_validation.this[0].certificate_arn : var.certificate_arn +} + +# Internet-facing by default: DocSpring is a website and API people reach from anywhere. Set alb_internal to keep it +# inside your network. (Access logs aren't turned on: they need a bucket with a policy for the ELB service.) +#trivy:ignore:AVD-AWS-0053 +resource "aws_lb" "this" { + name = var.name + load_balancer_type = "application" + internal = var.alb_internal + security_groups = [aws_security_group.alb.id] + subnets = var.alb_internal ? local.private_subnet_ids : local.public_subnet_ids + + idle_timeout = var.alb_idle_timeout + drop_invalid_header_fields = true + enable_deletion_protection = var.deletion_protection + + tags = local.tags +} + +resource "aws_lb_target_group" "web" { + name = "${var.name}-web" + vpc_id = local.vpc_id + target_type = "ip" + protocol = "HTTP" + port = local.web_port + + deregistration_delay = 60 + + # /health/site answers once Rails has booted (reference/deployment.yml). /health also checks the database and + # Redis: use that for uptime monitoring, not here, or a database blip would take every task out of service. + health_check { + path = "/health/site" + port = tostring(local.web_port) + protocol = "HTTP" + matcher = "200" + interval = 15 + timeout = 5 + healthy_threshold = 2 + unhealthy_threshold = 3 + } + + tags = local.tags + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_lb_listener" "http" { + load_balancer_arn = aws_lb.this.arn + port = 80 + protocol = "HTTP" + + default_action { + type = "redirect" + + redirect { + protocol = "HTTPS" + port = "443" + status_code = "HTTP_301" + } + } + + tags = local.tags +} + +resource "aws_lb_listener" "https" { + load_balancer_arn = aws_lb.this.arn + port = 443 + protocol = "HTTPS" + ssl_policy = "ELBSecurityPolicy-TLS13-1-2-Res-2021-06" + certificate_arn = local.certificate_arn + + default_action { + type = "forward" + target_group_arn = aws_lb_target_group.web.arn + } + + tags = local.tags + + lifecycle { + precondition { + condition = var.certificate_arn != null || var.route53_zone_id != null + error_message = "Set certificate_arn (an ACM certificate for domain_name) or route53_zone_id (so the module can create one)." + } + } +} + +# --- Certificate and DNS (with route53_zone_id) --------------------------------------------------------------------- + +resource "aws_acm_certificate" "this" { + count = local.create_certificate ? 1 : 0 + domain_name = var.domain_name + validation_method = "DNS" + tags = local.tags + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_route53_record" "certificate_validation" { + for_each = local.create_certificate ? { + for o in aws_acm_certificate.this[0].domain_validation_options : o.domain_name => o + } : {} + + zone_id = var.route53_zone_id + name = each.value.resource_record_name + type = each.value.resource_record_type + records = [each.value.resource_record_value] + ttl = 300 + allow_overwrite = true +} + +resource "aws_acm_certificate_validation" "this" { + count = local.create_certificate ? 1 : 0 + certificate_arn = aws_acm_certificate.this[0].arn + validation_record_fqdns = [for r in aws_route53_record.certificate_validation : r.fqdn] +} + +resource "aws_route53_record" "app" { + count = var.route53_zone_id != null && var.create_dns_record ? 1 : 0 + zone_id = var.route53_zone_id + name = var.domain_name + type = "A" + + alias { + name = aws_lb.this.dns_name + zone_id = aws_lb.this.zone_id + evaluate_target_health = false + } +} diff --git a/aws-ecs/modules/docspring/data_stores.tf b/aws-ecs/modules/docspring/data_stores.tf new file mode 100644 index 0000000..65f4440 --- /dev/null +++ b/aws-ecs/modules/docspring/data_stores.tf @@ -0,0 +1,237 @@ +# PostgreSQL, Redis (Valkey) and the S3 bucket for uploaded and generated files. + +# --- PostgreSQL ----------------------------------------------------------------------------------------------------- + +# Terraform generates the password instead of RDS managing it in Secrets Manager (manage_master_user_password). RDS +# rotates a managed password every 7 days at most (the schedule can be lengthened, not turned off), and the app reads +# DATABASE_URL once when a task starts, so after a rotation every new connection would fail until the tasks restarted. +# Letters and digits only, so it needs no escaping in DATABASE_URL. It's in the Terraform state, like the other +# generated secrets: keep the state encrypted and access to it restricted (README.md). +resource "random_password" "db" { + length = 40 + special = false +} + +resource "aws_db_subnet_group" "this" { + name = var.name + subnet_ids = local.private_subnet_ids + tags = local.tags +} + +# Performance Insights is left off (it's being replaced by CloudWatch Database Insights), and the app signs in with a +# password, not IAM database authentication. +#trivy:ignore:AVD-AWS-0133 +#trivy:ignore:AVD-AWS-0176 +resource "aws_db_instance" "this" { + identifier = var.name + + engine = "postgres" + engine_version = var.db_engine_version + auto_minor_version_upgrade = true + instance_class = var.db_instance_class + multi_az = var.db_multi_az + + db_name = "docspring" + username = "docspring" + password = random_password.db.result + + allocated_storage = var.db_allocated_storage + max_allocated_storage = var.db_max_allocated_storage + storage_type = "gp3" + storage_encrypted = true + + db_subnet_group_name = aws_db_subnet_group.this.name + vpc_security_group_ids = [aws_security_group.db.id] + publicly_accessible = false + + backup_retention_period = var.db_backup_retention_days + backup_window = "05:00-06:00" + maintenance_window = "sun:06:30-sun:07:30" + copy_tags_to_snapshot = true + deletion_protection = var.deletion_protection + skip_final_snapshot = false + final_snapshot_identifier = "${var.name}-final" + + tags = local.tags +} + +# --- Redis (Valkey) ------------------------------------------------------------------------------------------------- + +# Letters and digits only: ElastiCache refuses some punctuation, and it goes in REDIS_URL unescaped +resource "random_password" "redis" { + length = 64 + special = false +} + +resource "aws_elasticache_subnet_group" "this" { + name = var.name + subnet_ids = local.private_subnet_ids + tags = local.tags +} + +# Sidekiq's queues live in Redis: it must never evict keys to free memory +resource "aws_elasticache_parameter_group" "this" { + name = "${var.name}-valkey${split(".", var.redis_engine_version)[0]}" + family = "valkey${split(".", var.redis_engine_version)[0]}" + tags = local.tags + + parameter { + name = "maxmemory-policy" + value = "noeviction" + } +} + +resource "aws_elasticache_replication_group" "this" { + replication_group_id = var.name + description = "DocSpring Enterprise" + + engine = "valkey" + engine_version = var.redis_engine_version + node_type = var.redis_node_type + port = 6379 + parameter_group_name = aws_elasticache_parameter_group.this.name + + num_cache_clusters = var.redis_multi_az ? 2 : 1 + automatic_failover_enabled = var.redis_multi_az + multi_az_enabled = var.redis_multi_az + + subnet_group_name = aws_elasticache_subnet_group.this.name + security_group_ids = [aws_security_group.redis.id] + + at_rest_encryption_enabled = true + transit_encryption_enabled = true + auth_token = random_password.redis.result + auth_token_update_strategy = "ROTATE" + + snapshot_retention_limit = var.redis_snapshot_retention_days + snapshot_window = "04:30-05:30" + maintenance_window = "sun:07:30-sun:08:30" + auto_minor_version_upgrade = true + + tags = local.tags +} + +# --- S3 ------------------------------------------------------------------------------------------------------------- + +resource "random_id" "bucket_suffix" { + byte_length = 4 +} + +# Encrypted with S3's own keys (SSE-S3). A customer managed KMS key would add cost and KMS permissions without +# narrowing who can read the files: only the task role can. Access logging isn't turned on: it needs a second bucket, +# and CloudTrail data events cover the same ground for installs that need it. +#trivy:ignore:AVD-AWS-0089 +#trivy:ignore:AVD-AWS-0132 +resource "aws_s3_bucket" "uploads" { + bucket = "${var.name}-uploads-${random_id.bucket_suffix.hex}" + tags = local.tags +} + +resource "aws_s3_bucket_ownership_controls" "uploads" { + bucket = aws_s3_bucket.uploads.id + + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +resource "aws_s3_bucket_public_access_block" "uploads" { + bucket = aws_s3_bucket.uploads.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_versioning" "uploads" { + bucket = aws_s3_bucket.uploads.id + + versioning_configuration { + status = "Enabled" + } +} + +#trivy:ignore:AVD-AWS-0132 +resource "aws_s3_bucket_server_side_encryption_configuration" "uploads" { + bucket = aws_s3_bucket.uploads.id + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_bucket_lifecycle_configuration" "uploads" { + bucket = aws_s3_bucket.uploads.id + + rule { + id = "expire-old-versions" + status = "Enabled" + + filter {} + + noncurrent_version_expiration { + noncurrent_days = var.s3_noncurrent_version_expiration_days + } + + abort_incomplete_multipart_upload { + days_after_initiation = 7 + } + } + + rule { + id = "remove-expired-delete-markers" + status = "Enabled" + + filter {} + + expiration { + expired_object_delete_marker = true + } + } + + depends_on = [aws_s3_bucket_versioning.uploads] +} + +# Browsers upload template files straight to the bucket (reference/deployment.yml, s3_cors) +resource "aws_s3_bucket_cors_configuration" "uploads" { + bucket = aws_s3_bucket.uploads.id + + cors_rule { + allowed_methods = ["GET", "PUT", "POST"] + allowed_headers = ["Authorization", "cache-control", "x-requested-with", "content-type"] + allowed_origins = ["https://${var.domain_name}"] + max_age_seconds = 3000 + } +} + +data "aws_iam_policy_document" "uploads_bucket" { + statement { + sid = "DenyInsecureTransport" + effect = "Deny" + actions = ["s3:*"] + resources = [ + aws_s3_bucket.uploads.arn, + "${aws_s3_bucket.uploads.arn}/*", + ] + + principals { + type = "*" + identifiers = ["*"] + } + + condition { + test = "Bool" + variable = "aws:SecureTransport" + values = ["false"] + } + } +} + +resource "aws_s3_bucket_policy" "uploads" { + bucket = aws_s3_bucket.uploads.id + policy = data.aws_iam_policy_document.uploads_bucket.json + + depends_on = [aws_s3_bucket_public_access_block.uploads] +} diff --git a/aws-ecs/modules/docspring/ecs.tf b/aws-ecs/modules/docspring/ecs.tf new file mode 100644 index 0000000..1acb060 --- /dev/null +++ b/aws-ecs/modules/docspring/ecs.tf @@ -0,0 +1,260 @@ +# The cluster, a task definition for each service, the release command and each scheduled task, and the services. +# +# Terraform registers task definitions; scripts/deploy puts them live. The services ignore changes to their task +# definition, so `terraform apply` with a new image_tag (or new settings) registers new revisions and changes nothing +# that's running. scripts/deploy then runs the release command (database migrations) on the new revision, and only if +# it succeeds moves the services and the schedules to their new revisions. New code never runs against a database +# that hasn't been migrated for it, and a failed migration leaves everything on the old release. README.md, "Upgrade". + +# Container Insights is off by default because it adds CloudWatch charges; container_insights turns it on. +#trivy:ignore:AVD-AWS-0034 +resource "aws_ecs_cluster" "this" { + name = var.name + + setting { + name = "containerInsights" + value = var.container_insights + } + + tags = local.tags +} + +# CloudWatch Logs' own encryption. A customer managed KMS key would add cost and a key policy to maintain. +#trivy:ignore:AVD-AWS-0017 +resource "aws_cloudwatch_log_group" "task" { + for_each = local.task_names + name = "/ecs/${var.name}/${replace(each.key, "_", "-")}" + retention_in_days = var.log_retention_days + tags = local.tags +} + +locals { + image = "${var.image_repository}:${var.image_tag}" + + # Settings every task gets. The secrets come from Secrets Manager (secrets.tf). + base_environment = merge({ + DOCSPRING_DOMAIN_NAME = var.domain_name + DOCSPRING_FORCE_SSL = "true" # the load balancer terminates TLS + DOCSPRING_ADMIN_EMAIL = var.admin_email + DOCSPRING_AWS_UPLOADS_S3_BUCKET = aws_s3_bucket.uploads.id + DOCSPRING_AWS_UPLOADS_S3_REGION = local.region + }, var.extra_environment) + + # The container settings in reference/deployment.yml are: drop ALL capabilities, add SETUID, SETGID and KILL, and + # NET_ADMIN where the platform allows it. + # Fargate can't add capabilities (only SYS_PTRACE), so dropping ALL would also drop SETUID and SETGID, and + # run_as_deploy couldn't switch to the deploy user. Instead this drops every capability in the container runtime's + # default set except: + # - SETUID and SETGID, which gosu needs to switch to the deploy user; + # - KILL, so the stop signal (SIGTERM) reaches the app and Sidekiq and Puma shut down cleanly. + # NET_ADMIN can't be added, so run_as_deploy logs a warning and skips its firewall rule for 169.254.169.254. On + # Fargate that address (the EC2 instance metadata service) isn't reachable from a task anyway: there's no instance + # role to steal. Once the app runs as deploy it has no capabilities at all. + dropped_capabilities = [ + "AUDIT_WRITE", "CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "MKNOD", "NET_BIND_SERVICE", "NET_RAW", "SETFCAP", + "SETPCAP", "SYS_CHROOT", + ] + + container_definitions = { + for k, t in local.tasks : k => [merge( + { + name = "app" + image = local.image + essential = true + command = t.command + + environment = [ + for name, value in merge(local.base_environment, k == "web" ? { PORT = tostring(local.web_port) } : {}) : + { name = name, value = value } + ] + secrets = [ + for name in local.app_secret_names : + { name = name, valueFrom = "${aws_secretsmanager_secret.app.arn}:${name}::" } + ] + + portMappings = k == "web" ? [{ containerPort = local.web_port, protocol = "tcp", name = "http" }] : [] + + # Starts as root so run_as_deploy can switch to deploy: no `user`, not privileged + privileged = false + readonlyRootFilesystem = false + linuxParameters = { + capabilities = { add = [], drop = local.dropped_capabilities } + initProcessEnabled = true # reaps ECS Exec's processes + } + + # Fargate's maximum: time for Sidekiq to finish its jobs and Puma its requests after SIGTERM + stopTimeout = 120 + + logConfiguration = { + logDriver = "awslogs" + options = { + awslogs-group = aws_cloudwatch_log_group.task[k].name + awslogs-region = local.region + awslogs-stream-prefix = replace(k, "_", "-") + mode = "non-blocking" + max-buffer-size = "25m" + } + } + }, + local.use_registry_credentials ? { + repositoryCredentials = { credentialsParameter = aws_secretsmanager_secret.registry[0].arn } + } : {}, + )] + } +} + +resource "aws_ecs_task_definition" "task" { + for_each = local.tasks + + family = local.task_names[each.key] + requires_compatibilities = ["FARGATE"] + network_mode = "awsvpc" + cpu = tostring(local.task_sizes[each.key].cpu) + memory = tostring(local.task_sizes[each.key].memory) + execution_role_arn = aws_iam_role.execution.arn + task_role_arn = aws_iam_role.task.arn + container_definitions = jsonencode(local.container_definitions[each.key]) + + runtime_platform { + operating_system_family = "LINUX" + cpu_architecture = var.cpu_architecture + } + + # Keep old revisions registered when Terraform registers new ones: the services keep running theirs until + # scripts/deploy moves them, and the circuit breaker rolls back to them. + skip_destroy = true + + tags = local.tags +} + +# --- Services ------------------------------------------------------------------------------------------------------- + +locals { + autoscaled_services = { + web = { min = var.web_min_count, max = var.web_max_count, cpu_target = var.web_cpu_target } + worker = { min = var.worker_min_count, max = var.worker_max_count, cpu_target = var.worker_cpu_target } + } +} + +resource "aws_ecs_service" "autoscaled" { + for_each = local.autoscaled_services + + name = local.task_names[each.key] + cluster = aws_ecs_cluster.this.id + task_definition = aws_ecs_task_definition.task[each.key].arn + desired_count = each.value.min + + launch_type = "FARGATE" + platform_version = "LATEST" + + network_configuration { + subnets = local.private_subnet_ids + security_groups = [aws_security_group.app.id] + assign_public_ip = false + } + + dynamic "load_balancer" { + for_each = each.key == "web" ? [1] : [] + + content { + target_group_arn = aws_lb_target_group.web.arn + container_name = "app" + container_port = local.web_port + } + } + + # Rails takes a while to boot on a cold task + health_check_grace_period_seconds = each.key == "web" ? 180 : null + + deployment_minimum_healthy_percent = 100 + deployment_maximum_percent = 200 + + deployment_circuit_breaker { + enable = true + rollback = true + } + + enable_execute_command = var.enable_ecs_exec + enable_ecs_managed_tags = true + propagate_tags = "SERVICE" + + tags = local.tags + + lifecycle { + # scripts/deploy moves the service to new task definition revisions; autoscaling sets the count + ignore_changes = [task_definition, desired_count] + } + + depends_on = [aws_lb_listener.https, aws_iam_role_policy.execution] +} + +resource "aws_ecs_service" "worker_gj" { + name = local.task_names["worker_gj"] + cluster = aws_ecs_cluster.this.id + task_definition = aws_ecs_task_definition.task["worker_gj"].arn + desired_count = var.worker_gj_count + + launch_type = "FARGATE" + platform_version = "LATEST" + + network_configuration { + subnets = local.private_subnet_ids + security_groups = [aws_security_group.app.id] + assign_public_ip = false + } + + deployment_minimum_healthy_percent = 100 + deployment_maximum_percent = 200 + + deployment_circuit_breaker { + enable = true + rollback = true + } + + enable_execute_command = var.enable_ecs_exec + enable_ecs_managed_tags = true + propagate_tags = "SERVICE" + + tags = local.tags + + lifecycle { + # scripts/deploy moves the service to new task definition revisions + ignore_changes = [task_definition] + } + + depends_on = [aws_iam_role_policy.execution] +} + +# --- Autoscaling (web and worker, on CPU) --------------------------------------------------------------------------- + +resource "aws_appautoscaling_target" "service" { + for_each = local.autoscaled_services + + service_namespace = "ecs" + resource_id = "service/${aws_ecs_cluster.this.name}/${aws_ecs_service.autoscaled[each.key].name}" + scalable_dimension = "ecs:service:DesiredCount" + min_capacity = each.value.min + max_capacity = each.value.max + + tags = local.tags +} + +resource "aws_appautoscaling_policy" "cpu" { + for_each = local.autoscaled_services + + name = "${local.task_names[each.key]}-cpu" + policy_type = "TargetTrackingScaling" + service_namespace = aws_appautoscaling_target.service[each.key].service_namespace + resource_id = aws_appautoscaling_target.service[each.key].resource_id + scalable_dimension = aws_appautoscaling_target.service[each.key].scalable_dimension + + target_tracking_scaling_policy_configuration { + target_value = each.value.cpu_target + scale_out_cooldown = 60 + scale_in_cooldown = 300 + + predefined_metric_specification { + predefined_metric_type = "ECSServiceAverageCPUUtilization" + } + } +} diff --git a/aws-ecs/modules/docspring/iam.tf b/aws-ecs/modules/docspring/iam.tf new file mode 100644 index 0000000..f469086 --- /dev/null +++ b/aws-ecs/modules/docspring/iam.tf @@ -0,0 +1,196 @@ +# Three roles: +# - the task execution role, which ECS uses to pull the image, read the secrets and write the logs; +# - the task role, which the app itself uses (the AWS SDK's default credentials): the uploads bucket and nothing else; +# - the scheduler role, which EventBridge Scheduler uses to start the scheduled tasks. + +data "aws_iam_policy_document" "ecs_tasks_assume" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["ecs-tasks.amazonaws.com"] + } + + condition { + test = "StringEquals" + variable = "aws:SourceAccount" + values = [local.account_id] + } + } +} + +# --- Task execution role -------------------------------------------------------------------------------------------- + +resource "aws_iam_role" "execution" { + name_prefix = "${var.name}-execution-" + assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json + tags = local.tags +} + +locals { + image_is_ecr = can(regex("^[0-9]{12}\\.dkr\\.ecr\\.", var.image_repository)) +} + +data "aws_iam_policy_document" "execution" { + statement { + sid = "Logs" + actions = ["logs:CreateLogStream", "logs:PutLogEvents"] + resources = [for g in aws_cloudwatch_log_group.task : "${g.arn}:*"] + } + + statement { + sid = "Secrets" + actions = ["secretsmanager:GetSecretValue"] + resources = concat([aws_secretsmanager_secret.app.arn], aws_secretsmanager_secret.registry[*].arn) + } + + # Only when the image comes from an ECR repository (your own copy, or a pull-through cache). GetAuthorizationToken + # has no resource to scope to. + dynamic "statement" { + for_each = local.image_is_ecr ? [1] : [] + + content { + sid = "PullFromEcr" + actions = [ + "ecr:GetAuthorizationToken", + "ecr:BatchCheckLayerAvailability", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + ] + resources = ["*"] + } + } +} + +resource "aws_iam_role_policy" "execution" { + name = "execution" + role = aws_iam_role.execution.id + policy = data.aws_iam_policy_document.execution.json +} + +# --- Task role ------------------------------------------------------------------------------------------------------ + +resource "aws_iam_role" "task" { + name_prefix = "${var.name}-task-" + assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json + tags = local.tags +} + +data "aws_iam_policy_document" "task" { + statement { + sid = "UploadsBucket" + actions = [ + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:ListBucketMultipartUploads", + ] + resources = [aws_s3_bucket.uploads.arn] + } + + statement { + sid = "UploadsObjects" + actions = [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:AbortMultipartUpload", + "s3:ListMultipartUploadParts", + ] + resources = ["${aws_s3_bucket.uploads.arn}/*"] + } + + # ECS Exec: the SSM agent in the task opens its channels with these. They have no resource to scope to. + dynamic "statement" { + for_each = var.enable_ecs_exec ? [1] : [] + + content { + sid = "EcsExec" + actions = [ + "ssmmessages:CreateControlChannel", + "ssmmessages:CreateDataChannel", + "ssmmessages:OpenControlChannel", + "ssmmessages:OpenDataChannel", + ] + resources = ["*"] + } + } +} + +resource "aws_iam_role_policy" "task" { + name = "task" + role = aws_iam_role.task.id + policy = data.aws_iam_policy_document.task.json +} + +# --- Scheduler role ------------------------------------------------------------------------------------------------- + +data "aws_iam_policy_document" "scheduler_assume" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["scheduler.amazonaws.com"] + } + + condition { + test = "StringEquals" + variable = "aws:SourceAccount" + values = [local.account_id] + } + } +} + +resource "aws_iam_role" "scheduler" { + name_prefix = "${var.name}-scheduler-" + assume_role_policy = data.aws_iam_policy_document.scheduler_assume.json + tags = local.tags +} + +data "aws_iam_policy_document" "scheduler" { + # Any revision of the three scheduled task families (scripts/deploy moves the schedules to new revisions), only in + # this cluster + statement { + sid = "RunScheduledTasks" + actions = ["ecs:RunTask"] + resources = [for k in keys(local.scheduled_tasks) : "${aws_ecs_task_definition.task[k].arn_without_revision}:*"] + + condition { + test = "ArnEquals" + variable = "ecs:cluster" + values = [aws_ecs_cluster.this.arn] + } + } + + # RunTask tags the task (enable_ecs_managed_tags) + statement { + sid = "TagScheduledTasks" + actions = ["ecs:TagResource"] + resources = ["arn:${local.partition}:ecs:${local.region}:${local.account_id}:task/${aws_ecs_cluster.this.name}/*"] + + condition { + test = "StringEquals" + variable = "ecs:CreateAction" + values = ["RunTask"] + } + } + + statement { + sid = "PassTaskRoles" + actions = ["iam:PassRole"] + resources = [aws_iam_role.execution.arn, aws_iam_role.task.arn] + + condition { + test = "StringEquals" + variable = "iam:PassedToService" + values = ["ecs-tasks.amazonaws.com"] + } + } +} + +resource "aws_iam_role_policy" "scheduler" { + name = "scheduler" + role = aws_iam_role.scheduler.id + policy = data.aws_iam_policy_document.scheduler.json +} diff --git a/aws-ecs/modules/docspring/main.tf b/aws-ecs/modules/docspring/main.tf new file mode 100644 index 0000000..f15ea00 --- /dev/null +++ b/aws-ecs/modules/docspring/main.tf @@ -0,0 +1,50 @@ +data "aws_region" "current" {} +data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} + +locals { + region = data.aws_region.current.region + account_id = data.aws_caller_identity.current.account_id + partition = data.aws_partition.current.partition + + tags = merge({ "docspring:install" = var.name }, var.tags) + + # What each task runs, from reference/deployment.yml at the root of this repository. Keep these in step with it: + # services, release_command and scheduled_tasks. The keys are also the task definition families and service names + # ("-", with underscores as dashes). + services = { + web = ["run_as_deploy", "puma", "-C", "config/puma.rb"] + worker = ["run_as_deploy", "sidekiq"] + worker_gj = ["run_as_deploy", "good_job"] + } + release_command = ["run_as_deploy", "rake", "db:prepare"] + scheduled_tasks = { + # AWS cron: minutes hours day-of-month month day-of-week year, in UTC (schedule_expression_timezone) + hourly = { command = ["run_as_deploy", "rake", "timers:hourly"], cron = "cron(15 * * * ? *)" } # 15 * * * * + daily = { command = ["run_as_deploy", "rake", "timers:daily"], cron = "cron(0 3 * * ? *)" } # 0 3 * * * + weekly = { command = ["run_as_deploy", "rake", "timers:weekly"], cron = "cron(0 4 ? * SUN *)" } # 0 4 * * 0 + } + + # Fargate sizes. The contract's recommendations rounded up to sizes Fargate offers: web asks for 1 vCPU and 1536Mi, + # and 1 vCPU starts at 2 GiB. + default_task_sizes = { + web = { cpu = 1024, memory = 2048 } + worker = { cpu = 1024, memory = 3072 } + worker_gj = { cpu = 512, memory = 1024 } + release = { cpu = 1024, memory = 2048 } + hourly = { cpu = 1024, memory = 2048 } + daily = { cpu = 1024, memory = 2048 } + weekly = { cpu = 1024, memory = 2048 } + } + task_sizes = merge(local.default_task_sizes, var.task_sizes) + + # Every task definition: the services, the release command and the scheduled tasks + tasks = merge( + { for k, command in local.services : k => { command = command } }, + { release = { command = local.release_command } }, + { for k, t in local.scheduled_tasks : k => { command = t.command } }, + ) + task_names = { for k in keys(local.tasks) : k => "${var.name}-${replace(k, "_", "-")}" } + + web_port = 4001 +} diff --git a/aws-ecs/modules/docspring/network.tf b/aws-ecs/modules/docspring/network.tf new file mode 100644 index 0000000..d085f7d --- /dev/null +++ b/aws-ecs/modules/docspring/network.tf @@ -0,0 +1,254 @@ +# A VPC with public subnets (the load balancer, the NAT gateways) and private subnets (the tasks, database and Redis), +# unless var.vpc_id names an existing one. + +locals { + create_vpc = var.vpc_id == null + azs = local.create_vpc ? slice(data.aws_availability_zones.available[0].names, 0, var.az_count) : [] + nat_count = local.create_vpc ? (var.one_nat_gateway_per_az ? var.az_count : 1) : 0 + + vpc_id = local.create_vpc ? aws_vpc.this[0].id : var.vpc_id + public_subnet_ids = local.create_vpc ? aws_subnet.public[*].id : var.public_subnet_ids + private_subnet_ids = local.create_vpc ? aws_subnet.private[*].id : var.private_subnet_ids +} + +data "aws_availability_zones" "available" { + count = local.create_vpc ? 1 : 0 + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +# Flow logs aren't turned on: they cost per GB and most installs never read them. Add an aws_flow_log if your policies +# require them. +#trivy:ignore:AVD-AWS-0178 +resource "aws_vpc" "this" { + count = local.create_vpc ? 1 : 0 + + cidr_block = var.vpc_cidr + enable_dns_support = true + enable_dns_hostnames = true + + tags = merge(local.tags, { Name = var.name }) +} + +# Nothing uses the default security group: take its rules away so nothing can by accident +resource "aws_default_security_group" "this" { + count = local.create_vpc ? 1 : 0 + vpc_id = aws_vpc.this[0].id + tags = merge(local.tags, { Name = "${var.name}-default-unused" }) +} + +resource "aws_internet_gateway" "this" { + count = local.create_vpc ? 1 : 0 + vpc_id = aws_vpc.this[0].id + tags = merge(local.tags, { Name = var.name }) +} + +# /20s: the first three for public subnets, the next three for private ones +resource "aws_subnet" "public" { + count = local.create_vpc ? var.az_count : 0 + + vpc_id = aws_vpc.this[0].id + availability_zone = local.azs[count.index] + cidr_block = cidrsubnet(var.vpc_cidr, 20 - tonumber(split("/", var.vpc_cidr)[1]), count.index) + + tags = merge(local.tags, { Name = "${var.name}-public-${local.azs[count.index]}" }) +} + +resource "aws_subnet" "private" { + count = local.create_vpc ? var.az_count : 0 + + vpc_id = aws_vpc.this[0].id + availability_zone = local.azs[count.index] + cidr_block = cidrsubnet(var.vpc_cidr, 20 - tonumber(split("/", var.vpc_cidr)[1]), count.index + 3) + + tags = merge(local.tags, { Name = "${var.name}-private-${local.azs[count.index]}" }) +} + +resource "aws_route_table" "public" { + count = local.create_vpc ? 1 : 0 + vpc_id = aws_vpc.this[0].id + tags = merge(local.tags, { Name = "${var.name}-public" }) +} + +resource "aws_route" "public_internet" { + count = local.create_vpc ? 1 : 0 + route_table_id = aws_route_table.public[0].id + destination_cidr_block = "0.0.0.0/0" + gateway_id = aws_internet_gateway.this[0].id +} + +resource "aws_route_table_association" "public" { + count = local.create_vpc ? var.az_count : 0 + subnet_id = aws_subnet.public[count.index].id + route_table_id = aws_route_table.public[0].id +} + +resource "aws_eip" "nat" { + count = local.nat_count + domain = "vpc" + tags = merge(local.tags, { Name = "${var.name}-nat-${count.index}" }) + + depends_on = [aws_internet_gateway.this] +} + +resource "aws_nat_gateway" "this" { + count = local.nat_count + allocation_id = aws_eip.nat[count.index].id + subnet_id = aws_subnet.public[count.index].id + tags = merge(local.tags, { Name = "${var.name}-${local.azs[count.index]}" }) + + depends_on = [aws_internet_gateway.this] +} + +# One route table per private subnet, each through its own AZ's NAT gateway or the single one +resource "aws_route_table" "private" { + count = local.create_vpc ? var.az_count : 0 + vpc_id = aws_vpc.this[0].id + tags = merge(local.tags, { Name = "${var.name}-private-${local.azs[count.index]}" }) +} + +resource "aws_route" "private_nat" { + count = local.create_vpc ? var.az_count : 0 + route_table_id = aws_route_table.private[count.index].id + destination_cidr_block = "0.0.0.0/0" + nat_gateway_id = aws_nat_gateway.this[var.one_nat_gateway_per_az ? count.index : 0].id +} + +resource "aws_route_table_association" "private" { + count = local.create_vpc ? var.az_count : 0 + subnet_id = aws_subnet.private[count.index].id + route_table_id = aws_route_table.private[count.index].id +} + +# S3 traffic goes through this free gateway endpoint instead of the NAT gateway, which charges per GB +resource "aws_vpc_endpoint" "s3" { + count = local.create_vpc ? 1 : 0 + vpc_id = aws_vpc.this[0].id + service_name = "com.amazonaws.${local.region}.s3" + vpc_endpoint_type = "Gateway" + route_table_ids = aws_route_table.private[*].id + tags = merge(local.tags, { Name = "${var.name}-s3" }) +} + +# --- Security groups ------------------------------------------------------------------------------------------------ + +resource "aws_security_group" "alb" { + name_prefix = "${var.name}-alb-" + description = "DocSpring load balancer" + vpc_id = local.vpc_id + tags = merge(local.tags, { Name = "${var.name}-alb" }) + + lifecycle { + create_before_destroy = true + } +} + +# The app is a public website by default. Narrow alb_ingress_cidr_blocks (or set alb_internal) to restrict it. +resource "aws_vpc_security_group_ingress_rule" "alb_https" { + for_each = toset(var.alb_ingress_cidr_blocks) + security_group_id = aws_security_group.alb.id + description = "HTTPS" + ip_protocol = "tcp" + from_port = 443 + to_port = 443 + cidr_ipv4 = each.value +} + +# Only answers with a redirect to HTTPS +resource "aws_vpc_security_group_ingress_rule" "alb_http" { + for_each = toset(var.alb_ingress_cidr_blocks) + security_group_id = aws_security_group.alb.id + description = "HTTP, redirected to HTTPS" + ip_protocol = "tcp" + from_port = 80 + to_port = 80 + cidr_ipv4 = each.value +} + +resource "aws_vpc_security_group_egress_rule" "alb_to_web" { + security_group_id = aws_security_group.alb.id + description = "To the web tasks" + ip_protocol = "tcp" + from_port = local.web_port + to_port = local.web_port + referenced_security_group_id = aws_security_group.app.id +} + +resource "aws_security_group" "app" { + name_prefix = "${var.name}-app-" + description = "DocSpring tasks" + vpc_id = local.vpc_id + tags = merge(local.tags, { Name = "${var.name}-app" }) + + lifecycle { + create_before_destroy = true + + precondition { + condition = local.create_vpc || (length(var.public_subnet_ids) >= 2 && length(var.private_subnet_ids) >= 2) + error_message = "With vpc_id, set public_subnet_ids and private_subnet_ids, each with subnets in two or more AZs." + } + } +} + +resource "aws_vpc_security_group_ingress_rule" "app_from_alb" { + security_group_id = aws_security_group.app.id + description = "From the load balancer" + ip_protocol = "tcp" + from_port = local.web_port + to_port = local.web_port + referenced_security_group_id = aws_security_group.alb.id +} + +# The tasks pull the image from Docker Hub, check the license at api.docspring.com, send email and webhooks, and fetch +# the images and fonts HTML templates link to: hosts whose addresses aren't known in advance. +#trivy:ignore:AVD-AWS-0104 +resource "aws_vpc_security_group_egress_rule" "app_all" { + security_group_id = aws_security_group.app.id + description = "Outbound" + ip_protocol = "-1" + cidr_ipv4 = "0.0.0.0/0" +} + +resource "aws_security_group" "db" { + name_prefix = "${var.name}-db-" + description = "DocSpring PostgreSQL" + vpc_id = local.vpc_id + tags = merge(local.tags, { Name = "${var.name}-db" }) + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_vpc_security_group_ingress_rule" "db_from_app" { + security_group_id = aws_security_group.db.id + description = "PostgreSQL from the tasks" + ip_protocol = "tcp" + from_port = 5432 + to_port = 5432 + referenced_security_group_id = aws_security_group.app.id +} + +resource "aws_security_group" "redis" { + name_prefix = "${var.name}-redis-" + description = "DocSpring Redis" + vpc_id = local.vpc_id + tags = merge(local.tags, { Name = "${var.name}-redis" }) + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_vpc_security_group_ingress_rule" "redis_from_app" { + security_group_id = aws_security_group.redis.id + description = "Redis from the tasks" + ip_protocol = "tcp" + from_port = 6379 + to_port = 6379 + referenced_security_group_id = aws_security_group.app.id +} diff --git a/aws-ecs/modules/docspring/outputs.tf b/aws-ecs/modules/docspring/outputs.tf new file mode 100644 index 0000000..7ec24c9 --- /dev/null +++ b/aws-ecs/modules/docspring/outputs.tf @@ -0,0 +1,91 @@ +output "url" { + description = "DocSpring's address." + value = "https://${var.domain_name}" +} + +output "alb_dns_name" { + description = "The load balancer's DNS name. Without route53_zone_id, point domain_name at it (a CNAME or an alias record)." + value = aws_lb.this.dns_name +} + +output "alb_zone_id" { + description = "The load balancer's hosted zone ID, for an alias record in a zone this module doesn't manage." + value = aws_lb.this.zone_id +} + +output "region" { + description = "The AWS region." + value = local.region +} + +output "cluster_name" { + description = "The ECS cluster." + value = aws_ecs_cluster.this.name +} + +output "service_names" { + description = "The ECS services." + value = { + web = aws_ecs_service.autoscaled["web"].name + worker = aws_ecs_service.autoscaled["worker"].name + worker_gj = aws_ecs_service.worker_gj.name + } +} + +output "task_definition_families" { + description = "The task definition family of each service, the release command and each scheduled task." + value = local.task_names +} + +output "log_groups" { + description = "The CloudWatch log group of each task definition family." + value = { for k, g in aws_cloudwatch_log_group.task : k => g.name } +} + +output "deploy_command" { + description = "Run this from the aws-ecs folder after every terraform apply: it runs the release command, then puts the new task definitions live." + value = "./scripts/deploy --region ${local.region} --cluster ${aws_ecs_cluster.this.name} --name ${var.name}" +} + +output "run_task_command" { + description = "Runs a one-off command (here `rake about`) as a task with the release task definition. Follow its logs in the release log group." + value = join(" ", [ + "aws ecs run-task --region ${local.region} --cluster ${aws_ecs_cluster.this.name}", + "--task-definition ${local.task_names["release"]} --launch-type FARGATE", + "--network-configuration '${jsonencode({ awsvpcConfiguration = { subnets = local.private_subnet_ids, securityGroups = [aws_security_group.app.id], assignPublicIp = "DISABLED" } })}'", + "--overrides '{\"containerOverrides\":[{\"name\":\"app\",\"command\":[\"run_as_deploy\",\"rake\",\"about\"]}]}'", + ]) +} + +output "ecs_exec_command" { + description = "Opens a shell in a running web task (needs enable_ecs_exec and the Session Manager plugin for the AWS CLI). In the shell, `run_as_deploy bin/rails console` starts a Rails console as the deploy user." + value = var.enable_ecs_exec ? join(" ", [ + "aws ecs execute-command --region ${local.region} --cluster ${aws_ecs_cluster.this.name} --container app --interactive --command /bin/bash", + "--task \"$(aws ecs list-tasks --region ${local.region} --cluster ${aws_ecs_cluster.this.name} --service-name ${aws_ecs_service.autoscaled["web"].name} --query 'taskArns[0]' --output text)\"", + ]) : "ECS Exec is off: set enable_ecs_exec = true, apply and run the deploy command (tasks started before keep it off)." +} + +output "uploads_bucket" { + description = "The S3 bucket for uploaded and generated files." + value = aws_s3_bucket.uploads.id +} + +output "database_endpoint" { + description = "The PostgreSQL host and port." + value = aws_db_instance.this.endpoint +} + +output "redis_endpoint" { + description = "The Valkey primary endpoint." + value = aws_elasticache_replication_group.this.primary_endpoint_address +} + +output "app_secret_arn" { + description = "The Secrets Manager secret with the app's secret settings (a JSON object)." + value = aws_secretsmanager_secret.app.arn +} + +output "nat_public_ips" { + description = "The public addresses the tasks' outbound traffic comes from (when the module created the VPC), for allowlists such as your SMTP server's." + value = aws_eip.nat[*].public_ip +} diff --git a/aws-ecs/modules/docspring/scheduler.tf b/aws-ecs/modules/docspring/scheduler.tf new file mode 100644 index 0000000..1c94b1a --- /dev/null +++ b/aws-ecs/modules/docspring/scheduler.tf @@ -0,0 +1,56 @@ +# The scheduled tasks in reference/deployment.yml (hourly, daily and weekly rake buckets), started by EventBridge +# Scheduler on Fargate. The image decides what each bucket runs, and a run still going when the next starts makes the +# next one exit, so a late or doubled start does no harm. + +resource "aws_scheduler_schedule_group" "this" { + name = var.name + tags = local.tags +} + +resource "aws_scheduler_schedule" "task" { + for_each = local.scheduled_tasks + + name = local.task_names[each.key] + group_name = aws_scheduler_schedule_group.this.name + schedule_expression = each.value.cron + schedule_expression_timezone = "UTC" + state = "ENABLED" + + flexible_time_window { + mode = "OFF" + } + + target { + arn = aws_ecs_cluster.this.arn + role_arn = aws_iam_role.scheduler.arn + + ecs_parameters { + task_definition_arn = aws_ecs_task_definition.task[each.key].arn + task_count = 1 + launch_type = "FARGATE" + platform_version = "LATEST" + enable_ecs_managed_tags = true + propagate_tags = "TASK_DEFINITION" + + network_configuration { + subnets = local.private_subnet_ids + security_groups = [aws_security_group.app.id] + assign_public_ip = false + } + } + + # Retries only cover RunTask failing to start the task (such as Fargate capacity), not the task's own exit code. + # Give up after 15 minutes so a retried hourly run can't drift into the next one. + retry_policy { + maximum_retry_attempts = 2 + maximum_event_age_in_seconds = 900 + } + } + + lifecycle { + # scripts/deploy moves the schedule to the new revision after the release command succeeds + ignore_changes = [target[0].ecs_parameters[0].task_definition_arn] + } + + depends_on = [aws_iam_role_policy.scheduler] +} diff --git a/aws-ecs/modules/docspring/secrets.tf b/aws-ecs/modules/docspring/secrets.tf new file mode 100644 index 0000000..2acc90c --- /dev/null +++ b/aws-ecs/modules/docspring/secrets.tf @@ -0,0 +1,79 @@ +# The app's secrets, in one Secrets Manager secret (a JSON object). Each task gets them as environment variables +# through the container definition's `secrets`, read when the task starts: after a change, scripts/deploy restarts +# the services. The generated values are also in the Terraform state, so keep the state encrypted and restricted. + +# SECRET_KEY_BASE: 64 random bytes as 128 hex characters (openssl rand -hex 64) +resource "random_id" "secret_key_base" { + byte_length = 64 +} + +# DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY: 32 random bytes as 64 hex characters (openssl rand -hex 32). It encrypts +# stored data and must never change: back it up somewhere outside AWS too (README.md). +resource "random_id" "submission_data_encryption_key" { + byte_length = 32 +} + +locals { + database_url = "postgres://${aws_db_instance.this.username}:${random_password.db.result}@${aws_db_instance.this.address}:${aws_db_instance.this.port}/${aws_db_instance.this.db_name}?sslmode=require" + redis_url = "rediss://:${random_password.redis.result}@${aws_elasticache_replication_group.this.primary_endpoint_address}:6379/0" + + app_secrets = merge(var.extra_secrets, { + DATABASE_URL = local.database_url + REDIS_URL = local.redis_url + SECRET_KEY_BASE = coalesce(var.secret_key_base, random_id.secret_key_base.hex) + DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY = coalesce(var.submission_data_encryption_key, random_id.submission_data_encryption_key.hex) + DOCSPRING_LICENSE = var.license_key + DOCSPRING_ADMIN_PASSWORD = var.admin_password + }) + + # The names aren't secret, only the values + app_secret_names = sort(concat( + nonsensitive(keys(var.extra_secrets)), + ["DATABASE_URL", "REDIS_URL", "SECRET_KEY_BASE", "DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY", "DOCSPRING_LICENSE", "DOCSPRING_ADMIN_PASSWORD"], + )) + + use_registry_credentials = var.registry_username != null +} + +# Encrypted with Secrets Manager's AWS managed key: a customer managed key would add cost and key policy upkeep, and +# access is already limited to the task execution role by IAM. +#trivy:ignore:AVD-AWS-0098 +resource "aws_secretsmanager_secret" "app" { + name_prefix = "${var.name}/app-" + description = "DocSpring Enterprise settings (DATABASE_URL, REDIS_URL, keys and the license)" + recovery_window_in_days = 30 + tags = local.tags +} + +resource "aws_secretsmanager_secret_version" "app" { + secret_id = aws_secretsmanager_secret.app.id + secret_string = jsonencode(local.app_secrets) +} + +# The Docker Hub credentials ECS pulls the private image with (repositoryCredentials). ECS wants exactly these two keys. +#trivy:ignore:AVD-AWS-0098 +resource "aws_secretsmanager_secret" "registry" { + count = local.use_registry_credentials ? 1 : 0 + + name_prefix = "${var.name}/registry-" + description = "Docker Hub credentials for the DocSpring Enterprise image" + recovery_window_in_days = 30 + tags = local.tags +} + +resource "aws_secretsmanager_secret_version" "registry" { + count = local.use_registry_credentials ? 1 : 0 + + secret_id = aws_secretsmanager_secret.registry[0].id + secret_string = jsonencode({ + username = var.registry_username + password = var.registry_password + }) + + lifecycle { + precondition { + condition = var.registry_password != null + error_message = "Set registry_password (the Docker Hub access token) with registry_username." + } + } +} diff --git a/aws-ecs/modules/docspring/variables.tf b/aws-ecs/modules/docspring/variables.tf new file mode 100644 index 0000000..8807425 --- /dev/null +++ b/aws-ecs/modules/docspring/variables.tf @@ -0,0 +1,425 @@ +# --- Naming and the app --------------------------------------------------------------------------------------------- + +variable "name" { + description = "A short name for this install. Every resource name starts with it." + type = string + default = "docspring" + + validation { + condition = can(regex("^[a-z][a-z0-9-]{1,18}[a-z0-9]$", var.name)) + error_message = "name must be 3 to 20 lowercase letters, digits and dashes, starting with a letter." + } +} + +variable "domain_name" { + description = "The host name people use to reach DocSpring, such as docspring.example.com (DOCSPRING_DOMAIN_NAME)." + type = string + + validation { + condition = can(regex("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$", var.domain_name)) + error_message = "domain_name must be a lowercase host name without a scheme or port, such as docspring.example.com." + } +} + +variable "image_repository" { + description = "The DocSpring Enterprise image, without a tag. Change it only if you copy the image to your own registry." + type = string + default = "docspringcom/docspring-enterprise" +} + +variable "image_tag" { + description = "The release to run: the version DocSpring lists at https://docspring.com/enterprise-releases, such as c648191044. Pin a version; don't use latest in production." + type = string + + validation { + condition = can(regex("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$", var.image_tag)) + error_message = "image_tag must be a Docker image tag, such as c648191044." + } +} + +variable "registry_username" { + description = "The Docker Hub username DocSpring sent with your license key. Leave it null only if image_repository is a registry your tasks can pull from without credentials (such as your own ECR repository)." + type = string + default = null +} + +variable "registry_password" { + description = "The Docker Hub access token DocSpring sent with your license key." + type = string + default = null + sensitive = true +} + +variable "license_key" { + description = "Your DocSpring Enterprise license key (DOCSPRING_LICENSE)." + type = string + sensitive = true + + validation { + condition = length(var.license_key) > 0 + error_message = "license_key is required." + } +} + +variable "admin_email" { + description = "The first admin user's email address. The release command creates this user on an empty database." + type = string + + validation { + condition = can(regex("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$", var.admin_email)) + error_message = "admin_email must be an email address." + } +} + +variable "admin_password" { + description = "The first admin user's password. Change it after you sign in." + type = string + sensitive = true + + validation { + condition = length(var.admin_password) >= 12 + error_message = "admin_password must be at least 12 characters." + } +} + +variable "secret_key_base" { + description = "Leave null to generate one. Set it only when you move an existing install here (128 hex characters, from openssl rand -hex 64)." + type = string + default = null + sensitive = true + + validation { + condition = var.secret_key_base == null || can(regex("^[0-9a-f]{128}$", var.secret_key_base)) + error_message = "secret_key_base must be 128 lowercase hex characters (openssl rand -hex 64)." + } +} + +variable "submission_data_encryption_key" { + description = "Leave null to generate one. Set it only when you move an existing install here: it must be the key that install uses, or its stored data can't be read (64 hex characters, from openssl rand -hex 32)." + type = string + default = null + sensitive = true + + validation { + condition = var.submission_data_encryption_key == null || can(regex("^[0-9a-f]{64}$", var.submission_data_encryption_key)) + error_message = "submission_data_encryption_key must be 64 lowercase hex characters (openssl rand -hex 32)." + } +} + +variable "extra_environment" { + description = "Other settings that aren't secret, such as DOCSPRING_FROM_EMAIL. Every setting: https://docspring.com/docs/enterprise/configuration/environment-variables/" + type = map(string) + default = {} + + validation { + condition = alltrue([for k in keys(var.extra_environment) : !contains([ + "DATABASE_URL", "REDIS_URL", "SECRET_KEY_BASE", "DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY", "DOCSPRING_LICENSE", + "DOCSPRING_ADMIN_EMAIL", "DOCSPRING_ADMIN_PASSWORD", "DOCSPRING_DOMAIN_NAME", "DOCSPRING_AWS_UPLOADS_S3_BUCKET", + "DOCSPRING_AWS_UPLOADS_S3_REGION", "PORT", + ], k)]) + error_message = "extra_environment can't set a variable the module sets: use domain_name, license_key, admin_email, admin_password, secret_key_base or submission_data_encryption_key instead." + } + + validation { + condition = alltrue([for k in keys(var.extra_environment) : can(regex("^[A-Za-z_][A-Za-z0-9_]*$", k))]) + error_message = "extra_environment keys must be environment variable names." + } +} + +variable "extra_secrets" { + description = "Other secret settings, such as DOCSPRING_POSTMARK_API_TOKEN or DOCSPRING_SMTP_PASSWORD. They're stored in Secrets Manager with the generated secrets." + type = map(string) + default = {} + sensitive = true + + validation { + condition = alltrue([for k in keys(var.extra_secrets) : !contains([ + "DATABASE_URL", "REDIS_URL", "SECRET_KEY_BASE", "DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY", "DOCSPRING_LICENSE", + "DOCSPRING_ADMIN_EMAIL", "DOCSPRING_ADMIN_PASSWORD", "DOCSPRING_DOMAIN_NAME", "DOCSPRING_AWS_UPLOADS_S3_BUCKET", + "DOCSPRING_AWS_UPLOADS_S3_REGION", "PORT", + ], k) && can(regex("^[A-Za-z_][A-Za-z0-9_]*$", k))]) + error_message = "extra_secrets keys must be environment variable names that the module doesn't already set." + } +} + +# --- ECS ------------------------------------------------------------------------------------------------------------ + +variable "cpu_architecture" { + description = "ARM64 (Graviton, about 20% cheaper) or X86_64. The image is built for both." + type = string + default = "ARM64" + + validation { + condition = contains(["ARM64", "X86_64"], var.cpu_architecture) + error_message = "cpu_architecture must be ARM64 or X86_64." + } +} + +variable "task_sizes" { + description = "CPU units and memory (MiB) per task, to override the defaults (see local.default_task_sizes). Keys: web, worker, worker_gj, release, hourly, daily, weekly. Each pair must be a valid Fargate size." + type = map(object({ + cpu = number + memory = number + })) + default = {} + + validation { + condition = alltrue([for k in keys(var.task_sizes) : contains(["web", "worker", "worker_gj", "release", "hourly", "daily", "weekly"], k)]) + error_message = "task_sizes keys must be web, worker, worker_gj, release, hourly, daily or weekly." + } +} + +variable "web_min_count" { + description = "The fewest web tasks. Autoscaling adds more up to web_max_count." + type = number + default = 2 +} + +variable "web_max_count" { + description = "The most web tasks autoscaling runs." + type = number + default = 6 +} + +variable "web_cpu_target" { + description = "The average CPU use (percent) autoscaling keeps the web service at." + type = number + default = 60 +} + +variable "worker_min_count" { + description = "The fewest worker (Sidekiq) tasks. Autoscaling adds more up to worker_max_count." + type = number + default = 2 +} + +variable "worker_max_count" { + description = "The most worker tasks autoscaling runs." + type = number + default = 6 +} + +variable "worker_cpu_target" { + description = "The average CPU use (percent) autoscaling keeps the worker service at." + type = number + default = 70 +} + +variable "worker_gj_count" { + description = "How many worker_gj (GoodJob) tasks to run." + type = number + default = 1 +} + +variable "enable_ecs_exec" { + description = "Allow ECS Exec into running tasks (a shell or Rails console). Who can use it is controlled by the ecs:ExecuteCommand IAM permission." + type = bool + default = true +} + +variable "container_insights" { + description = "CloudWatch Container Insights for the cluster: disabled, enabled or enhanced. It adds CloudWatch charges." + type = string + default = "disabled" + + validation { + condition = contains(["disabled", "enabled", "enhanced"], var.container_insights) + error_message = "container_insights must be disabled, enabled or enhanced." + } +} + +variable "log_retention_days" { + description = "How long CloudWatch keeps each service's logs, in days." + type = number + default = 30 + + validation { + condition = contains([1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653], var.log_retention_days) + error_message = "log_retention_days must be a value CloudWatch Logs accepts, such as 30, 90 or 365." + } +} + +# --- Network -------------------------------------------------------------------------------------------------------- + +variable "vpc_id" { + description = "Leave null to create a VPC. Set it, with public_subnet_ids and private_subnet_ids, to use an existing one." + type = string + default = null +} + +variable "public_subnet_ids" { + description = "With vpc_id: the public subnets (two or more AZs) for the load balancer." + type = list(string) + default = [] +} + +variable "private_subnet_ids" { + description = "With vpc_id: the private subnets (two or more AZs) for the tasks, database and Redis. They need a route to the internet (a NAT gateway) to pull the image and reach api.docspring.com." + type = list(string) + default = [] +} + +variable "vpc_cidr" { + description = "The new VPC's address range." + type = string + default = "10.0.0.0/16" + + validation { + condition = can(cidrhost(var.vpc_cidr, 0)) && tonumber(split("/", var.vpc_cidr)[1]) <= 20 + error_message = "vpc_cidr must be an IPv4 range of /20 or larger." + } +} + +variable "az_count" { + description = "How many availability zones the new VPC spans (2 or 3)." + type = number + default = 2 + + validation { + condition = contains([2, 3], var.az_count) + error_message = "az_count must be 2 or 3." + } +} + +variable "one_nat_gateway_per_az" { + description = "One NAT gateway per AZ (survives an AZ outage, costs more) instead of one for the whole VPC." + type = bool + default = false +} + +# --- Load balancer, certificate and DNS ----------------------------------------------------------------------------- + +variable "certificate_arn" { + description = "An ACM certificate for domain_name in this region. Leave null to have the module create one, which needs route53_zone_id." + type = string + default = null +} + +variable "route53_zone_id" { + description = "A Route 53 hosted zone for domain_name. The module then creates and validates the certificate (unless certificate_arn is set) and, with create_dns_record, the DNS record." + type = string + default = null +} + +variable "create_dns_record" { + description = "With route53_zone_id: create an alias record for domain_name that points at the load balancer." + type = bool + default = true +} + +variable "alb_internal" { + description = "Make the load balancer internal (reachable only from your network) instead of internet-facing." + type = bool + default = false +} + +variable "alb_ingress_cidr_blocks" { + description = "The IPv4 ranges that can reach the load balancer on ports 80 and 443." + type = list(string) + default = ["0.0.0.0/0"] +} + +variable "alb_idle_timeout" { + description = "Seconds the load balancer keeps an idle connection open. At least 240: Enterprise requests can run for 210 seconds (the Admin API's synchronous imports and exports)." + type = number + default = 240 + + validation { + condition = var.alb_idle_timeout >= 240 && var.alb_idle_timeout <= 4000 + error_message = "alb_idle_timeout must be between 240 and 4000 seconds." + } +} + +variable "deletion_protection" { + description = "Deletion protection on the database and the load balancer. Turn it off (and apply) before terraform destroy." + type = bool + default = true +} + +# --- Database ------------------------------------------------------------------------------------------------------- + +variable "db_instance_class" { + description = "The RDS instance class." + type = string + default = "db.t4g.medium" +} + +variable "db_engine_version" { + description = "The PostgreSQL version. A major version (17) gets the latest minor version, and minor upgrades are applied in the maintenance window." + type = string + default = "17" +} + +variable "db_allocated_storage" { + description = "The database's starting storage in GiB." + type = number + default = 50 +} + +variable "db_max_allocated_storage" { + description = "RDS grows the storage on its own up to this many GiB." + type = number + default = 500 +} + +variable "db_multi_az" { + description = "Keep a standby database in a second AZ that RDS fails over to. Doubles the database cost." + type = bool + default = false +} + +variable "db_backup_retention_days" { + description = "How many days of automated backups (point-in-time recovery) RDS keeps." + type = number + default = 7 + + validation { + condition = var.db_backup_retention_days >= 7 && var.db_backup_retention_days <= 35 + error_message = "db_backup_retention_days must be between 7 and 35." + } +} + +# --- Redis (Valkey) ------------------------------------------------------------------------------------------------- + +variable "redis_node_type" { + description = "The ElastiCache node type." + type = string + default = "cache.t4g.small" +} + +variable "redis_engine_version" { + description = "The Valkey version." + type = string + default = "8.0" + + validation { + condition = can(regex("^[0-9]+\\.[0-9]+$", var.redis_engine_version)) + error_message = "redis_engine_version must be a major.minor version, such as 8.0." + } +} + +variable "redis_multi_az" { + description = "Run a replica in a second AZ that ElastiCache fails over to. Doubles the Redis cost." + type = bool + default = false +} + +variable "redis_snapshot_retention_days" { + description = "How many days of daily Redis snapshots to keep (0 turns them off)." + type = number + default = 1 +} + +# --- S3 ------------------------------------------------------------------------------------------------------------- + +variable "s3_noncurrent_version_expiration_days" { + description = "Days the bucket keeps a file's old versions (after it's replaced or deleted) before removing them." + type = number + default = 30 +} + +variable "tags" { + description = "Tags for every resource the module creates." + type = map(string) + default = {} +} diff --git a/aws-ecs/modules/docspring/versions.tf b/aws-ecs/modules/docspring/versions.tf new file mode 100644 index 0000000..6bac4d1 --- /dev/null +++ b/aws-ecs/modules/docspring/versions.tf @@ -0,0 +1,16 @@ +terraform { + # Terraform 1.6 or later, or OpenTofu 1.6 or later. Don't use features newer than 1.6 (cross-variable validation, + # write-only arguments, ephemeral resources): customers run whichever version they have. + required_version = ">= 1.6" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + random = { + source = "hashicorp/random" + version = "~> 3.6" + } + } +} diff --git a/aws-ecs/scripts/deploy b/aws-ecs/scripts/deploy new file mode 100755 index 0000000..11e712e --- /dev/null +++ b/aws-ecs/scripts/deploy @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +# Puts the task definitions that `terraform apply` registered live, in the order that keeps the database ahead of the +# code: +# 1. runs the release command (rake db:prepare: migrations, and on the first install the schema and admin user) as a +# one-off task on the newest release task definition, and stops if it fails; +# 2. moves the web, worker and worker-gj services to their newest task definitions and waits for each rollout to +# finish (the circuit breaker rolls a failed one back, and this script then fails); +# 3. moves the hourly, daily and weekly schedules to their newest task definitions. +# It always starts new tasks, even when nothing changed, so it's also how to apply a changed secret. +# +# Usage: scripts/deploy --cluster --name [--region ] [--release-timeout ] +# [--rollout-timeout ] +# `terraform output deploy_command` prints the command for your install. Needs the AWS CLI v2 and credentials that can +# run tasks, update services and schedules, and pass the task roles. +set -euo pipefail + +export AWS_PAGER="" + +usage() { + sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//' >&2 +} + +die() { + echo "Error: $*" >&2 + exit 1 +} + +log() { + echo "[$(date -u +%H:%M:%S)] $*" +} + +CLUSTER="" +NAME="" +REGION="" +RELEASE_TIMEOUT=3600 +ROLLOUT_TIMEOUT=1800 + +while [[ $# -gt 0 ]]; do + case "$1" in + --cluster | --name | --region | --release-timeout | --rollout-timeout) + [[ $# -ge 2 ]] || die "$1 needs a value" + case "$1" in + --cluster) CLUSTER="$2" ;; + --name) NAME="$2" ;; + --region) REGION="$2" ;; + --release-timeout) RELEASE_TIMEOUT="$2" ;; + --rollout-timeout) ROLLOUT_TIMEOUT="$2" ;; + esac + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage + die "unknown argument: $1" + ;; + esac +done + +[[ -n "$CLUSTER" && -n "$NAME" ]] || { + usage + die "--cluster and --name are required" +} +[[ "$RELEASE_TIMEOUT" =~ ^[0-9]+$ && "$ROLLOUT_TIMEOUT" =~ ^[0-9]+$ ]] || die "timeouts are whole numbers of seconds" +command -v aws > /dev/null || die "the AWS CLI isn't installed: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html" + +AWS=(aws) +if [[ -n "$REGION" ]]; then + AWS+=(--region "$REGION") +fi + +SERVICES=(web worker worker-gj) +SCHEDULES=(hourly daily weekly) + +# Bash 3.2 (macOS's /bin/bash) has no associative arrays: each key's value is in a variable named after it +set_value() { printf -v "${1}_${2//-/_}" '%s' "$3"; } +get_value() { + local var="${1}_${2//-/_}" + echo "${!var}" +} + +# The newest ACTIVE revision of a task definition family +latest_revision() { + local arn + arn="$("${AWS[@]}" ecs describe-task-definition --task-definition "$NAME-$1" \ + --query 'taskDefinition.taskDefinitionArn' --output text)" || + die "can't find the task definition family $NAME-$1: has terraform apply run?" + echo "$arn" +} + +log "Finding the newest task definitions" +for key in release "${SERVICES[@]}" "${SCHEDULES[@]}"; do + revision="$(latest_revision "$key")" + set_value REVISION "$key" "$revision" + echo " $key: ${revision##*/}" +done +RELEASE_REVISION="$(get_value REVISION release)" + +# The release task runs in the same subnets and security group as the services +NETWORK="$("${AWS[@]}" ecs describe-services --cluster "$CLUSTER" --services "$NAME-worker" \ + --query 'services[0].networkConfiguration' --output json)" +[[ -n "$NETWORK" && "$NETWORK" != "null" ]] || die "can't read the network configuration of the service $NAME-worker" + +# --- 1. The release command --------------------------------------------------------------------------------------- + +log "Running the release command (${RELEASE_REVISION##*/})" +IFS=$'\t' read -r TASK_ARN FAILURE_REASON < <( + "${AWS[@]}" ecs run-task --cluster "$CLUSTER" --task-definition "$RELEASE_REVISION" \ + --launch-type FARGATE --platform-version LATEST --network-configuration "$NETWORK" \ + --started-by docspring-deploy --query '[tasks[0].taskArn, failures[0].reason]' --output text +) +[[ "$TASK_ARN" == arn:* ]] || die "ECS didn't start the release task: $FAILURE_REASON" +TASK_ID="${TASK_ARN##*/}" +LOG_GROUP="$("${AWS[@]}" ecs describe-task-definition --task-definition "$RELEASE_REVISION" \ + --query "taskDefinition.containerDefinitions[?name=='app'] | [0].logConfiguration.options.\"awslogs-group\"" \ + --output text)" +LOG_STREAM="release/app/$TASK_ID" +echo " task $TASK_ID, logs: aws logs tail $LOG_GROUP --log-stream-names $LOG_STREAM --follow" + +deadline=$((SECONDS + RELEASE_TIMEOUT)) +last_status="" +while :; do + status="$("${AWS[@]}" ecs describe-tasks --cluster "$CLUSTER" --tasks "$TASK_ARN" \ + --query 'tasks[0].lastStatus' --output text)" + if [[ "$status" != "$last_status" ]]; then + echo " $status" + last_status="$status" + fi + [[ "$status" == "STOPPED" ]] && break + if ((SECONDS > deadline)); then + die "the release task is still running after $RELEASE_TIMEOUT seconds. It hasn't been stopped: watch it with" \ + "the logs command above, then run this script again. Nothing has been moved to the new release." + fi + sleep 10 +done + +IFS=$'\t' read -r EXIT_CODE STOPPED_REASON < <( + "${AWS[@]}" ecs describe-tasks --cluster "$CLUSTER" --tasks "$TASK_ARN" \ + --query "tasks[0].[containers[?name=='app'] | [0].exitCode, stoppedReason]" --output text +) +if [[ "$EXIT_CODE" != "0" ]]; then + echo "The release task's last log lines:" >&2 + "${AWS[@]}" logs get-log-events --log-group-name "$LOG_GROUP" --log-stream-name "$LOG_STREAM" --limit 50 \ + --query 'events[].[message]' --output text >&2 || echo " (no logs: the container may not have started)" >&2 + die "the release command failed (exit code $EXIT_CODE: $STOPPED_REASON). Nothing has been moved to the new" \ + "release: the services and schedules still run the old one." +fi +log "The release command succeeded" + +# --- 2. The services ---------------------------------------------------------------------------------------------- + +for key in "${SERVICES[@]}"; do + revision="$(get_value REVISION "$key")" + log "Moving $NAME-$key to ${revision##*/}" + deployment="$("${AWS[@]}" ecs update-service --cluster "$CLUSTER" --service "$NAME-$key" \ + --task-definition "$revision" --force-new-deployment \ + --query "service.deployments[?status=='PRIMARY'] | [0].id" --output text)" + [[ "$deployment" == ecs-svc/* ]] || die "ECS didn't start a deployment for $NAME-$key" + set_value DEPLOYMENT "$key" "$deployment" +done + +log "Waiting for the rollouts to finish" +deadline=$((SECONDS + ROLLOUT_TIMEOUT)) +pending=("${SERVICES[@]}") +while [[ ${#pending[@]} -gt 0 ]]; do + still_pending=() + for key in "${pending[@]}"; do + IFS=$'\t' read -r status rollout reason < <( + "${AWS[@]}" ecs describe-services --cluster "$CLUSTER" --services "$NAME-$key" \ + --query "services[0].deployments[?id=='$(get_value DEPLOYMENT "$key")'] | [0].[status, rolloutState, rolloutStateReason]" \ + --output text + ) + if [[ "$status" == "PRIMARY" && "$rollout" == "COMPLETED" ]]; then + echo " $NAME-$key: done" + elif [[ "$rollout" != "FAILED" && "$status" == "PRIMARY" ]]; then + still_pending+=("$key") + else + # The circuit breaker marked it FAILED and started a rollback, which replaced it as the PRIMARY deployment + die "the rollout of $NAME-$key failed and ECS rolled it back to the previous task definition: $reason." \ + "Its stopped tasks' reasons: aws ecs list-tasks --cluster $CLUSTER --service-name $NAME-$key" \ + "--desired-status STOPPED. The database has the new release's migrations; the old code works with them." + fi + done + pending=(${still_pending[@]+"${still_pending[@]}"}) + [[ ${#pending[@]} -eq 0 ]] && break + ((SECONDS <= deadline)) || die "still waiting for ${pending[*]} after $ROLLOUT_TIMEOUT seconds; check the ECS console" + sleep 15 +done + +# --- 3. The schedules --------------------------------------------------------------------------------------------- + +for key in "${SCHEDULES[@]}"; do + schedule="$NAME-$key" + revision="$(get_value REVISION "$key")" + log "Moving the schedule $schedule to ${revision##*/}" + IFS=$'\t' read -r expression timezone state current < <( + "${AWS[@]}" scheduler get-schedule --group-name "$NAME" --name "$schedule" \ + --query '[ScheduleExpression, ScheduleExpressionTimezone, State, Target.EcsParameters.TaskDefinitionArn]' \ + --output text + ) + window="$("${AWS[@]}" scheduler get-schedule --group-name "$NAME" --name "$schedule" \ + --query 'FlexibleTimeWindow' --output json)" + target="$("${AWS[@]}" scheduler get-schedule --group-name "$NAME" --name "$schedule" \ + --query 'Target' --output json)" + old="\"$current\"" + new="\"$revision\"" + [[ "$target" == *"$old"* ]] || die "can't find the task definition in the schedule $schedule's target" + # UpdateSchedule replaces the whole schedule: send it back as it was, with only the task definition changed + target="${target//"$old"/$new}" + "${AWS[@]}" scheduler update-schedule --group-name "$NAME" --name "$schedule" \ + --schedule-expression "$expression" --schedule-expression-timezone "$timezone" --state "$state" \ + --flexible-time-window "$window" --target "$target" > /dev/null +done + +log "Deployed: every service and schedule runs the newest task definitions" diff --git a/convox.example.yml b/convox.example.yml deleted file mode 100644 index 75f289f..0000000 --- a/convox.example.yml +++ /dev/null @@ -1,95 +0,0 @@ -services: - web: - image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise - # domain: docspring.example.com - health: - path: ${HEALTH_CHECK_PATH} - grace: 50 - interval: 5 - command: run_command deploy DATABASE_URL foreman start -m web=1 - deployment: - minimum: 50 - maximum: 200 - # To see available CPU/RAM: convox api get /system/capacity - scale: - memory: 1400 - cpu: 600 - count: 3-6 - targets: - cpu: 90 - environment: - - "*" - - 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. - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - add: - - NET_ADMIN - - SETUID - - SETGID - 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 - deployment: - minimum: 50 - maximum: 200 - scale: - memory: 2000 - cpu: 700 - count: 3-6 - targets: - cpu: 90 - environment: - - "*" - - FORCE_SSL=true - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - add: - - NET_ADMIN - - SETUID - - SETGID - seccompProfile: RuntimeDefault - - command: - image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise - command: echo "You can use this service to run rake tasks, rails console, etc." - scale: - memory: 512 - cpu: 250 - count: 0 - environment: - - "*" - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - add: - - NET_ADMIN - - SETUID - - SETGID - seccompProfile: RuntimeDefault - -timers: - update-submissions: - schedule: 0 3 * * ? - command: run_command deploy DATABASE_URL rake submissions:expire_overdue_submissions - service: command diff --git a/.convox/.keep b/convox/.convox/.keep similarity index 100% rename from .convox/.keep rename to convox/.convox/.keep diff --git a/convox/.dockerignore b/convox/.dockerignore new file mode 100644 index 0000000..7f4fbfa --- /dev/null +++ b/convox/.dockerignore @@ -0,0 +1,11 @@ +# convox build uploads this folder. The services use DocSpring's image and build nothing from it, so upload none of +# these, above all the settings file with its generated secrets. +.installer_config* +.rack_name +.convox +.rubocop.yml +AGENTS.md +README.md +convox.example.yml +install.rb +update.sh 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/convox/.rubocop.yml b/convox/.rubocop.yml new file mode 100644 index 0000000..cb53212 --- /dev/null +++ b/convox/.rubocop.yml @@ -0,0 +1,15 @@ +AllCops: + NewCops: enable + TargetRubyVersion: 3.2 + SuggestExtensions: false + +# install.rb uses the convox_installer DSL at the top level +Style/MixinUsage: + Exclude: + - install.rb + +Layout/LineLength: + Max: 120 + +Style/StringLiterals: + EnforcedStyle: single_quotes diff --git a/convox/AGENTS.md b/convox/AGENTS.md new file mode 100644 index 0000000..c94d428 --- /dev/null +++ b/convox/AGENTS.md @@ -0,0 +1,33 @@ +# convox + +The Convox install: `install.rb` (a script on the `convox_installer` gem, 4.x), `convox.example.yml` (copied to +`convox.yml` on install) and `update.sh` (build, release command, promote). README.md is for customers. + +## Validate + +Static checks only. Never run `install.rb` (not even `plan`) against an AWS account, and use no AWS credentials. + +```sh +cd convox +ruby -c install.rb +shellcheck update.sh +ruby -ryaml -e 'YAML.load_file("convox.example.yml")' +../scripts/check_deployments +``` + +To try the script with an unreleased gem, point `CONVOX_INSTALLER_PATH` at a checkout of the gem. + +## Invariants + +- Keep in step with `../reference/deployment.yml`: each service's `command`, the `timers`, the securityContext + (Convox 3.24.10 or later), `web`'s `timeout` and `termination.grace`, the health check path, and the release + command in both `install.rb` and `update.sh`. +- New code never runs before its migrations: `install.rb` and `update.sh` run the release command with a built + release, then promote it. Never use plain `convox deploy` in either. +- `install.rb` sets `DOCSPRING_DOMAIN_NAME` and `DOCSPRING_DISABLE_EMAILS` only when they're missing, so running it + again doesn't undo a custom domain or an email setup. Every other value it sets comes from Terraform or the settings + file and doesn't change. +- Never let anything regenerate `secret_key_base` or `data_encryption_key` in an existing `.installer_config.json`. +- `install.rb` never prints a secret. The gem masks known secrets in its output; tell people where a value is saved + instead of printing it. +- Use the `DOCSPRING_` names for settings (the docs' environment variables page), not their older aliases. diff --git a/convox/README.md b/convox/README.md new file mode 100644 index 0000000..25203f4 --- /dev/null +++ b/convox/README.md @@ -0,0 +1,39 @@ +# DocSpring Enterprise on AWS with Convox + +`install.rb` sets up DocSpring Enterprise in your AWS account on a [Convox](https://github.com/convox/convox) rack: an +EKS cluster, RDS PostgreSQL 17, ElastiCache Redis with TLS and a versioned, encrypted S3 bucket, then the DocSpring app. +It uses the [convox_installer](https://github.com/DocSpring/convox_installer) gem. The full guide is +[Install DocSpring on AWS with Convox](https://docspring.com/docs/enterprise/aws-convox/installation/). + +| File | What it is | +| -------------------- | --------------------------------------------------------------------------------------------------- | +| `install.rb` | The install script. Run it again to resume; finished steps are skipped. | +| `convox.example.yml` | The app's services, scheduled tasks and container settings. `install.rb` copies it to `convox.yml`. | +| `update.sh` | Deploys `convox.yml`: builds a release, runs the release command with it, then promotes it. | + +## Install + +You need Ruby 3.2 or later, the Convox CLI 3.24.10 or later, the AWS CLI v2.9 or later, Terraform 1.6 or later (or +OpenTofu), your DocSpring license key and the Docker registry credentials we email you. + +```sh +aws sso login --profile docspring-admin +export AWS_PROFILE=docspring-admin +./install.rb plan # what it would create, without changing anything +./install.rb # install (about 35 minutes) +``` + +The script saves its settings, including generated passwords and the data encryption key, to `.installer_config.json`. +Keep that file out of git and somewhere safe, and copy `data_encryption_key` to a place outside AWS. + +For CI or a coding agent, pass every setting and add `--yes --json`; `./install.rb --help` lists them. + +## Upgrade + +Read the [release notes](https://docspring.com/enterprise-releases), back up the database, change the tag on every +`image:` line in `convox.yml`, then run `./update.sh`. + +## Remove + +The script prints the steps when it finishes, and +[Uninstall](https://docspring.com/docs/enterprise/aws-convox/uninstall/) lists them. diff --git a/convox/convox.example.yml b/convox/convox.example.yml new file mode 100644 index 0000000..0d1f638 --- /dev/null +++ b/convox/convox.example.yml @@ -0,0 +1,146 @@ +# DocSpring Enterprise on Convox. install.rb copies this file to convox.yml, which you then edit and deploy with +# ./update.sh. Pin a version: add its tag to every image line (enterprise:c648191044). Without one, Convox deploys +# the latest release. The versions: https://docspring.com/enterprise-releases +services: + web: + image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise + # domain: docspring.example.com + # /health/site answers once the app has booted. Don't use /health here: it also checks the database and Redis, so + # a short database outage would take every web container out of service at once. + health: + path: /health/site + grace: 50 + interval: 5 + 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 + # To see available CPU/RAM: convox api get /system/capacity + scale: + memory: 1400 + cpu: 600 + count: 3-6 + targets: + cpu: 90 + environment: + - "*" + - WEB_CONCURRENCY=2 + - RAILS_MAX_THREADS=5 + - FORCE_SSL=true + - PORT=4001 + port: 4001 + ingressAnnotations: + - nginx.ingress.kubernetes.io/proxy-buffer-size=32k + # 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: + drop: + - ALL + add: + - NET_ADMIN + - SETUID + - SETGID + - KILL + seccompProfile: RuntimeDefault + + worker: + image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise + command: run_as_deploy sidekiq + termination: + grace: 60 + deployment: + minimum: 50 + maximum: 200 + scale: + memory: 3072 + cpu: 1000 + count: 3-6 + targets: + cpu: 90 + environment: + - "*" + - FORCE_SSL=true + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + add: + - 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: + image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise + command: echo "You can use this service to run rake tasks, rails console, etc." + scale: + memory: 512 + cpu: 250 + count: 0 + environment: + - "*" + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + add: + - 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: + hourly: + schedule: 15 * * * ? + command: run_as_deploy rake timers:hourly + service: command + daily: + schedule: 0 3 * * ? + 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/convox/install.rb b/convox/install.rb new file mode 100755 index 0000000..21c6cf5 --- /dev/null +++ b/convox/install.rb @@ -0,0 +1,212 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Installs DocSpring Enterprise on a Convox rack in your AWS account: the rack, an S3 bucket, an RDS PostgreSQL +# database and an ElastiCache Redis cluster, then the DocSpring app. Run it again to resume after a failure; finished +# steps are skipped. +# +# AWS_PROFILE=docspring ./install.rb # install, asking for anything missing +# AWS_PROFILE=docspring ./install.rb plan # what would change, without changing anything +# AWS_PROFILE=docspring ./install.rb status # what exists +# ./install.rb --help # every option and setting +# +# Non-interactive (CI and coding agents): add --yes --json and pass every setting as a flag or environment variable. +# The settings are saved to .installer_config.json, which holds generated passwords: keep it safe. + +if ENV['CONVOX_INSTALLER_PATH'] + # A local checkout of the convox_installer gem, for developing the gem + $LOAD_PATH.unshift File.join(ENV.fetch('CONVOX_INSTALLER_PATH'), 'lib') +else + require 'bundler/inline' + + gemfile do + source 'https://rubygems.org' + gem 'convox_installer', '~> 4.0' + end +end + +require 'convox_installer' +require 'fileutils' +require 'securerandom' +include ConvoxInstaller + +Dir.chdir(__dir__) + +S3_BUCKET_CORS_RULE = <<~TERRAFORM + cors_rule { + allowed_headers = ["Authorization", "cache-control", "x-requested-with"] + allowed_methods = ["PUT", "POST", "GET"] + allowed_origins = ["*"] + expose_headers = [] + max_age_seconds = 3000 + } +TERRAFORM + +@prompts = ConvoxInstaller::Config::DEFAULT_PROMPTS.reject { |p| p[:key] == :stack_name } + [ + { + key: :stack_name, + title: 'Convox Rack Name', + prompt: 'Please enter a name for your Convox rack', + default: 'docspring-enterprise' + }, + { + section: 'DocSpring Enterprise', + info: "We email you your license key and the credentials for our Docker registry.\n" \ + 'If you don\'t have them, contact support@docspring.com.' + }, + { + key: :docker_registry_url, + title: 'Docker Registry URL', + value: '691950705664.dkr.ecr.us-east-1.amazonaws.com' + }, + { + key: :docker_registry_username, + title: 'Docker Registry Username (Access Key ID)' + }, + { + key: :docker_registry_password, + title: 'Docker Registry Password (Secret Access Key)' + }, + { + key: :docspring_license, + title: 'DocSpring License' + }, + { + key: :admin_email, + title: 'Admin User Email', + prompt: 'Please enter the email address for the first admin user', + default: 'admin@example.com', + validate: /\A[^@\s]+@[^@\s]+\z/ + }, + { + key: :convox_app_name, + title: 'Convox App Name', + value: 'docspring' + }, + { + key: :admin_password, + title: 'Admin User Password', + value: -> { SecureRandom.hex(12) } + }, + { + key: :s3_bucket_name, + title: 'S3 Bucket for templates and PDFs', + value: -> { "docspring-docs-#{SecureRandom.hex(4)}" } + }, + { + key: :s3_bucket_cors_rule, + value: S3_BUCKET_CORS_RULE, + hidden: true + }, + { + key: :secret_key_base, + value: -> { SecureRandom.hex(64) }, + hidden: true + }, + { + key: :data_encryption_key, + value: -> { SecureRandom.hex(32) }, + hidden: true + }, + { + key: :database_username, + value: 'docspring', + hidden: true + } +] + +ensure_requirements! +settings = prompt_for_config + +# Your copy of the app's configuration, which you edit (the image version, a domain) and deploy with ./update.sh +FileUtils.cp('convox.example.yml', 'convox.yml') unless dry_run? || File.exist?('convox.yml') + +backup_convox_host_and_rack +install_convox +validate_convox_rack_and_write_current! +validate_convox_rack_api! + +# update.sh and the docs' commands read the rack's name from this file +File.write('.rack_name', settings.fetch(:stack_name)) unless dry_run? + +create_convox_app! +set_default_app_for_directory! +add_docker_registry! + +add_s3_bucket +add_rds_database +add_elasticache_cluster +apply_terraform_update! + +domain = default_service_domain_name +result_output(:domain, domain) + +app_exists = !dry_run? || convox_api_get('/apps').any? { |app| app['name'] == settings.fetch(:convox_app_name) } +current_env = app_exists ? convox_env_vars : {} + +env = { + 'DATABASE_URL' => rds_details[:postgres_url], + 'REDIS_URL' => elasticache_details[:redis_url], + 'DOCSPRING_AWS_ACCESS_KEY_ID' => s3_bucket_details[:access_key_id], + 'DOCSPRING_AWS_ACCESS_KEY_SECRET' => s3_bucket_details[:secret_access_key], + 'DOCSPRING_AWS_UPLOADS_S3_BUCKET' => s3_bucket_details[:name], + 'DOCSPRING_AWS_UPLOADS_S3_REGION' => settings.fetch(:aws_region), + 'SECRET_KEY_BASE' => settings.fetch(:secret_key_base), + 'DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY' => settings.fetch(:data_encryption_key), + 'DOCSPRING_ADMIN_EMAIL' => settings.fetch(:admin_email), + 'DOCSPRING_ADMIN_PASSWORD' => settings.fetch(:admin_password), + 'DOCSPRING_LICENSE' => settings.fetch(:docspring_license) +} +# Set once, so a custom domain or email provider set up later isn't changed back when this script runs again. +# Emails stay off until you configure an email provider. +env['DOCSPRING_DOMAIN_NAME'] = domain unless current_env.key?('DOCSPRING_DOMAIN_NAME') +env['DOCSPRING_DISABLE_EMAILS'] = 'true' unless current_env.key?('DOCSPRING_DISABLE_EMAILS') +set_convox_env!(env) + +# The same steps as update.sh: build a release, run its release command (which creates the database schema and the +# first admin user), then start the services on it +step 'initial_deploy', 'Deploy DocSpring Enterprise for the first time', + check: -> { convox_processes.any? { |process| process['name'] == 'web' } } do + release_id = capture_convox_command!('build --id').to_s.strip + raise ConvoxInstaller::StepFailed, 'convox build --id printed no release ID' if release_id.empty? + + run_convox_command! ['run', 'command', 'run_as_deploy rake db:prepare', '--release', release_id] + run_convox_command! ['releases', 'promote', release_id, '--wait'] +end + +step 'health_check', 'Check PostgreSQL, Redis, S3, background jobs and PDF generation', + check: -> { config[:health_check_passed] == 'true' } do + run_convox_command! ['run', 'command', 'run_as_deploy rake checks:health_check checks:generate_test_submission'] + config[:health_check_passed] = 'true' +end + +return if dry_run? + +rds_identifier = "#{settings.fetch(:stack_name)}-rds-#{settings.fetch(:random_id)}" + +puts +logger.info 'All done!' +puts +puts "Open https://#{domain} and sign in as #{settings.fetch(:admin_email)}, then change the password." +puts "The first password is admin_password in #{File.join(__dir__, '.installer_config.json')}:" +puts +puts ' ruby -rjson -e \'puts JSON.parse(File.read(".installer_config.json"))["config"]["admin_password"]\'' +puts +puts 'Keep a copy of data_encryption_key from that file somewhere outside AWS, such as your password manager.' +puts 'Without it, the data DocSpring stores can\'t be read.' +puts +puts 'Next:' +puts ' * Set up your domain and an email provider: https://docspring.com/docs/enterprise/aws-convox/custom-domain/' +puts ' * Upgrade DocSpring: change the image tag in convox.yml, then run ./update.sh' +puts ' * Documentation: https://docspring.com/docs/enterprise/' +puts +puts 'To remove everything from your AWS account, in this order:' +puts +puts " 1) Turn off the database's deletion protection:" +puts " aws rds modify-db-instance --db-instance-identifier #{rds_identifier} \\" +puts ' --no-deletion-protection --apply-immediately' +puts " 2) Empty the #{s3_bucket_details[:name]} bucket, including old versions (the S3 console's Empty button)." +puts " 3) Delete the app: convox apps delete #{settings.fetch(:convox_app_name)}" +puts " 4) Uninstall the rack and its AWS resources: convox rack uninstall #{settings.fetch(:stack_name)}" +puts +puts 'Contact support@docspring.com if you need any help.' 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/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..00b16e6 --- /dev/null +++ b/docker-compose/README.md @@ -0,0 +1,140 @@ +# 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, a copy of Redis (the job queues) and, without a bucket, the uploads volume to +`./backups`, and keeps the last 14 of each. It stops the `worker` service while it copies them, so the copies match, +and starts it again after; the site stays up. 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. + +## Restore + +Restore the files from one backup, with the same `.env`. `