From bada583fc42cc685695d221eaa9c7107602ed604 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 18 Nov 2026 12:13:02 +1300 Subject: [PATCH] 4.0.0: Convox v3, the AWS credential chain, non-interactive runs Scripts run for a person or for CI and coding agents: install, plan and status commands, --yes and --json, settings from flags, environment variables and the config file, named resumable steps and exit codes. AWS credentials come from the standard chain (SSO, profiles, roles) and are checked against the saved account. The Terraform templates use the current AWS provider resources: an encrypted, versioned S3 bucket, Postgres 17 with deletion protection, and Redis with TLS and AUTH for new installs, while existing installs keep theirs. capture_convox_command! returns a command's output. Needs Ruby 3.2, Terraform 1.6 or OpenTofu, and the AWS CLI v2.9. CHANGELOG.md explains upgrading a 3.x script. --- .github/workflows/ci.yml | 26 + .gitignore | 3 + .rubocop.yml | 24 +- AGENTS.md | 101 ++ CHANGELOG.md | 52 + Gemfile | 15 +- Gemfile.lock | 109 -- README.md | 477 ++++--- convox_installer.gemspec | 21 +- examples/full_installation.rb | 234 +--- lib/convox/client.rb | 1159 +++++++++++++---- lib/convox_installer.rb | 181 ++- lib/convox_installer/aws_session.rb | 150 +++ lib/convox_installer/config.rb | 375 ++++-- lib/convox_installer/context.rb | 32 + lib/convox_installer/errors.rb | 83 ++ lib/convox_installer/masker.rb | 64 + lib/convox_installer/options.rb | 152 +++ lib/convox_installer/platform.rb | 70 + lib/convox_installer/reporter.rb | 50 + lib/convox_installer/requirements.rb | 160 ++- lib/convox_installer/runner.rb | 210 +++ lib/convox_installer/settings.rb | 182 +++ lib/convox_installer/shell.rb | 110 ++ lib/convox_installer/version.rb | 2 +- spec/fixtures/fake_tools.rb | 193 +++ spec/lib/convox/client_spec.rb | 692 +++++++++- spec/lib/convox_installer/aws_session_spec.rb | 69 + spec/lib/convox_installer/config_spec.rb | 411 +++--- spec/lib/convox_installer/masker_spec.rb | 40 + spec/lib/convox_installer/options_spec.rb | 68 + spec/lib/convox_installer/platform_spec.rb | 35 + .../lib/convox_installer/requirements_spec.rb | 158 ++- spec/lib/convox_installer/runner_spec.rb | 137 ++ spec/lib/convox_installer/shell_spec.rb | 56 + spec/lib/convox_installer_spec.rb | 154 +++ spec/spec_helper.rb | 121 +- spec/support/fake_executor.rb | 81 ++ spec/support/fake_rack.rb | 42 + spec/support/spec_helpers.rb | 32 + terraform/convox_installer.tf.erb | 11 + terraform/elasticache.tf.erb | 39 +- terraform/elasticache_legacy.tf.erb | 44 + terraform/rds.tf.erb | 43 +- terraform/s3_bucket.tf.erb | 121 +- 45 files changed, 5062 insertions(+), 1527 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md delete mode 100644 Gemfile.lock create mode 100644 lib/convox_installer/aws_session.rb create mode 100644 lib/convox_installer/context.rb create mode 100644 lib/convox_installer/errors.rb create mode 100644 lib/convox_installer/masker.rb create mode 100644 lib/convox_installer/options.rb create mode 100644 lib/convox_installer/platform.rb create mode 100644 lib/convox_installer/reporter.rb create mode 100644 lib/convox_installer/runner.rb create mode 100644 lib/convox_installer/settings.rb create mode 100644 lib/convox_installer/shell.rb create mode 100644 spec/fixtures/fake_tools.rb create mode 100644 spec/lib/convox_installer/aws_session_spec.rb create mode 100644 spec/lib/convox_installer/masker_spec.rb create mode 100644 spec/lib/convox_installer/options_spec.rb create mode 100644 spec/lib/convox_installer/platform_spec.rb create mode 100644 spec/lib/convox_installer/runner_spec.rb create mode 100644 spec/lib/convox_installer/shell_spec.rb create mode 100644 spec/lib/convox_installer_spec.rb create mode 100644 spec/support/fake_executor.rb create mode 100644 spec/support/fake_rack.rb create mode 100644 spec/support/spec_helpers.rb create mode 100644 terraform/convox_installer.tf.erb create mode 100644 terraform/elasticache_legacy.tf.erb diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..05a41b5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: [main, master] + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Ruby ${{ matrix.ruby }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby: ['3.2', '3.3', '3.4'] + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - run: bundle exec rspec + - run: bundle exec rubocop diff --git a/.gitignore b/.gitignore index fd21efe..63d53dd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ log convox.yml .convox convox_installer-*.gem +Gemfile.lock +.installer_config.json +.rspec_status diff --git a/.rubocop.yml b/.rubocop.yml index fd0ab22..6d7a3ce 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,15 +1,20 @@ -require: rubocop-rspec +plugins: + - rubocop-rspec AllCops: NewCops: enable - TargetRubyVersion: 2.5 + TargetRubyVersion: 3.2 + SuggestExtensions: false + Exclude: + - vendor/**/* + - tmp/**/* Style/MixinUsage: Exclude: - examples/**/* Layout/LineLength: - Max: 100 + Max: 120 Style/StringLiterals: EnforcedStyle: single_quotes @@ -47,6 +52,9 @@ Metrics/BlockLength: Metrics/BlockNesting: Max: 7 +Naming/PredicateMethod: + Enabled: false + RSpec/MessageSpies: Enabled: false @@ -59,5 +67,13 @@ RSpec/MultipleExpectations: RSpec/ExampleLength: Enabled: false -RSpec/AnyInstance: +RSpec/MultipleMemoizedHelpers: Enabled: false + +RSpec/NestedGroups: + Max: 4 + +# The fake convox, aws and terraform commands print their output. +RSpec/Output: + Exclude: + - spec/fixtures/**/* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a432848 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,101 @@ +# AGENTS.md + +Notes for coding agents. The first part covers running an install script built with this gem; the second covers changing the gem. People should start with [README.md](./README.md). + +## Running an install script + +An install script (`install.rb`) uses this gem's DSL. It creates real AWS resources that cost money, so: + +- Run `plan` first and show the person what it reports. Run `install` only when they've asked for it. +- Never pass AWS keys on the command line. Use the person's AWS profile or SSO session (`AWS_PROFILE=...`). If credentials are missing or expired, the run exits 3 and says which command to run (for example `aws sso login --profile prod`); ask the person to run it. +- `.installer_config.json` holds generated passwords and tokens. Don't print it, paste it or commit it. + +### Commands and flags + +```sh +ruby install.rb plan --yes --json # what would change; changes nothing +ruby install.rb status --yes --json # the same checks, to see what exists +ruby install.rb install --yes --json # set everything up (also: apply, or no command) +ruby install.rb --help # every flag and setting +``` + +- `--yes` (or `--non-interactive`, or `CONVOX_INSTALLER_NON_INTERACTIVE=1`): never prompt. Always pass it: without a terminal and without `--yes`, the run stops before changing anything (exit 2, `missing: ["confirmation"]`). +- `--json` (or `CONVOX_INSTALLER_JSON=1`): JSON events on stdout, one per line. Human logs, and all output from `convox`, `terraform` and the script itself, go to stderr. +- Settings: `--stack-name prod`, `--set key=value`, `CONVOX_INSTALLER_=value`, the config file (`--config FILE`, default `./.installer_config.json`). Flags win over environment variables, which win over the file. Prompt keys also read bare names (`STACK_NAME`). Pass secrets as environment variables rather than flags, so they stay out of the process list. + +### Exit codes + +| Code | Type | What to do | +| --- | --- | --- | +| 0 | | Done. For `plan` and `status`, read `changes_pending` and `pending`. | +| 1 | `unexpected_error` | A bug in the gem or the script. Report it with the stderr output. | +| 2 | `missing_input`, `usage` | Supply the settings in `error.missing` or fix `error.invalid`, then run the same command again. | +| 3 | `precondition_failed` | Fix the environment (install a tool, sign in to AWS, use the right account), then run again. | +| 4 | `step_failed` | A command failed in `error.step`. Read stderr, fix the cause, run the same command again. | +| 5 | `cancelled` | The input ended at a prompt. Use `--yes`. | +| 130 | `interrupted` | Interrupted. Run the same command again to resume. | + +### JSON events + +Every event has `event` and `time` (UTC, ISO 8601). Secrets are replaced with `[hidden]` in every event and log line. + +- `start`: `version` (gem), `command` (`install`, `plan` or `status`), `dry_run` (true for `plan` and `status`). +- `config`: `file`, `settings` (visible settings, secrets hidden) and `sources` (where each came from: `flag`, `env:`, `file`, `default`, `generated`, `prompt`). +- `step`: `step` (a stable name), `status`, and `description`. Statuses: + - `started`: the step began (install only). + - `done`: it made its change, or a check passed. + - `skipped`: nothing to do; `state` is `present` and `reason` says why. + - `pending`: in `plan` and `status`, the step would make a change. `action` (`create`, `update`, `resume`, `apply`, `run`, `check`), `state` (`missing`, `outdated`, `incomplete`, `unknown`) and an optional `reason`. + - `failed`: `error` with `type`, `message`, `next_step`. + - Some steps add fields: `rack_dir`, `command`, `files` (Terraform files that would change), `resources` (each address `present` or `missing`), `keys` (environment variable names that changed), `version`, `file`. +- `would_run`: in `plan` and `status`, a `convox` command the script would run (`command`, secrets masked). +- `result`: always the last event. `command`, `status` (`succeeded`, `failed`, `cancelled`), `exit_code`, `steps` (each `step`, `status`, `action`, `state`), `outputs` (values the script added with `result_output`), `config_file`, and on failure `error` (`type`, `message`, `step`, `next_step`, plus `missing` and `invalid` for input errors). `plan` and `status` add `pending` (step names), `changes_pending`, and `stopped_early` (`reason`) when a later step needs a resource that doesn't exist yet. + +### Resuming + +Every step checks the current state first, so after a failure, fix the cause and run the same command again: finished steps report `skipped`. An interrupted `convox rack install` is resumed with `terraform apply` in the rack directory. Generated names and passwords are saved to the config file as soon as they're made, so a re-run reuses them. If the config file is lost, a re-run generates new ones and tries to create new resources, so keep it. + +### Steps + +`requirements`, `config`, `convox_rack`, `convox_current_rack`, `convox_rack_api`, `convox_app`, `convox_app_directory`, `docker_registry`, `terraform_s3_bucket`, `terraform_rds_database`, `terraform_elasticache`, `terraform_apply`, `convox_env`, then any custom steps the script defines. The `terraform_*` steps that write files are skipped when the file on disk already matches; `terraform_apply` is skipped when `terraform plan` finds no changes. `requirements`, `config` and `convox_rack_api` are checks and report `done` on every run. + +## Changing the gem + +```sh +bundle install +bundle exec rspec # must pass; no network +bundle exec rubocop # must be clean +``` + +CI (`.github/workflows/ci.yml`) runs both on Ruby 3.2, 3.3 and 3.4. Gemfile.lock isn't committed (it's a gem, and the newest RuboCop dependencies need a newer Ruby than 3.2). + +### Layout + +- `lib/convox_installer.rb`: the DSL that scripts `include`. It parses the command line on first use, sets up the context and prints the result at exit (`at_exit` calls `Runner#finish`, then exits with its code). +- `lib/convox_installer/`: + - `options.rb` (command line), `settings.rb` (the gem's own settings: drives `--help`, flags and env names), `config.rb` (loading, prompting, validating and saving settings). + - `runner.rb` (named steps and the result), `reporter.rb` (JSON events and the logger), `errors.rb` (error classes and exit codes). + - `shell.rb` (every subprocess goes through `Shell`), `masker.rb` (hides secrets in logs and events), `aws_session.rb` (credential chain, `sts get-caller-identity`, exported credentials), `requirements.rb` (tool checks), `platform.rb` (OS, Convox config directory, install hints), `context.rb` (holds them together). +- `lib/convox/client.rb`: the steps that touch Convox, Terraform and AWS. +- `terraform/*.tf.erb`: templates written into the rack directory. `s(:key)` renders an escaped HCL string, `v(:key)` a raw value. +- `spec/`: unit specs use `FakeExecutor` (`spec/support/fake_executor.rb`) to answer commands. `spec/lib/convox_installer_spec.rb` runs `examples/full_installation.rb` as a real process with fake `convox`, `aws` and `terraform` executables (`spec/fixtures/fake_tools.rb`). + +### Rules + +- **No real commands or network in specs.** `spec_helper.rb` installs `RefusingExecutor`, which raises on any command not stubbed, and WebMock blocks HTTP. Never run `convox rack install`, `terraform apply` or any AWS command while developing. +- **Every subprocess goes through `context.shell`** (`capture` or `stream`), with an argv array. Pass secrets on stdin or in the environment, never as arguments; when that can't be avoided, register them with `context.masker.add`. +- **Steps check before they change.** Inside `runner.step`, look at the current state, call `step.skip!(reason)` when there's nothing to do, and call `step.plan!(action:)` immediately before the first change. In `plan` and `status`, `plan!` ends the step as pending; code after it must be the only code that changes anything. Step names are part of the interface: don't rename them. +- **Errors say what to do next.** Raise `MissingInput`, `PreconditionFailed` or `StepFailed` with a `next_step:`. Anything else becomes exit code 1. +- **Templates must stay compatible with existing installs.** Resource addresses (`aws_db_instance.rds_database`, `aws_s3_bucket.docs_s3_bucket`, `aws_iam_access_key.docspring_user_access_key` and the rest) and names are in real Terraform state; changing one makes Terraform destroy and recreate the resource. Defaults for an existing resource come from its state (`resource_attributes`), and new defaults apply only to new resources. Don't add a `required_providers` block: Convox pins the AWS provider (5.100.0 in Convox 3.26.0), and `convox rack update` and `uninstall` run `terraform init -upgrade`. +- **New settings** go in `Settings::KNOWN` with a title and description, and in the README's settings table. Bare environment names are read only for a script's prompt keys. + +### Convox facts the code relies on + +Checked against the Convox source at tag 3.26.0 (`pkg/cli/rack.go`, `pkg/rack/terraform.go`, `vendor/github.com/convox/stdcli`): + +- `convox rack install aws [key=value ...]` takes `--version` and writes the rack's Terraform config to `/racks//` (`main.tf`, `vars.json`, local `terraform.tfstate` unless `CONVOX_TERRAFORM_BACKEND` is set). It fails with "rack name in use" if that directory exists. +- The config directory is `$CONVOX_CONFIG`, otherwise `~/Library/Preferences/convox` on macOS and `$XDG_CONFIG_HOME/convox` (`~/.config/convox`) on Linux. `convox switch ` writes `current` there. +- For AWS, the CLI requires `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` in the environment and runs a binary named `terraform` (no OpenTofu option; the gem puts a `terraform` symlink to `tofu` first on `PATH`). +- The rack's Terraform outputs include `api` (the rack API URL with credentials, sensitive); `module.system.cluster` has `vpc` and `subnets`. +- Rack names match `^[a-z][a-z0-9-]*$`, at most 26 characters. +- Most commands have no JSON output; `convox api get ` returns the API's JSON. `convox env` prints `KEY=value` lines, and `convox env set` reads `KEY=value` lines from stdin when stdin isn't a terminal. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..de90bcc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,52 @@ +# Changelog + +## 4.0.0 + +4.0.0 brings the gem up to date with the current Convox v3 CLI, Terraform or OpenTofu, the AWS provider and Ruby. It also adds a non-interactive mode for CI and coding agents. Scripts written for 3.x keep working with a few changes (see "Upgrading a 3.x script" below). + +### Breaking changes + +- **Ruby 3.2 or later.** The gem no longer depends on ActiveSupport, HTTParty, `os` or `json`. If your script used ActiveSupport methods (`present?`, `symbolize_keys`, `1.day`) because the gem loaded it, require ActiveSupport yourself or replace those calls. +- **AWS credentials come from the standard AWS credential chain** (`AWS_PROFILE`, SSO, environment variables, instance roles). The installer no longer prompts for an access key, and `Config::DEFAULT_PROMPTS` no longer has `aws_access_key_id` or `aws_secret_access_key`. `config.fetch(:aws_access_key_id)` raises `KeyError` on a new install. Use `aws_env` (an environment hash for your own `aws` commands) and `aws_identity` (account and principal) instead. Explicit keys in `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` still work. Keys saved in a 3.x config file are kept and used. +- **The installer checks the AWS account.** It shows the account and principal from `aws sts get-caller-identity` in the summary, saves the account ID to the config file, and stops if a later run uses credentials for a different account. +- **Convox v2 support is gone.** The gem needs the Convox v3 CLI. The last version for Convox v2 is 1.0.9. +- **Terraform 1.6 or later, or OpenTofu.** Set `terraform_binary` to `tofu` to use OpenTofu; the installer uses `tofu` on its own when `terraform` isn't installed. The AWS CLI must be v2.9 or later. +- **New Terraform resources:** + - The S3 bucket uses the separate resources the AWS provider now expects: versioning, KMS encryption (now with a bucket key), a public access block, ownership controls (new buckets) and CORS. The deprecated inline `acl`, `cors_rule` and encryption blocks are gone. Versioning is on for new buckets, with old versions expiring after 30 days. Existing buckets keep their versioning setting. + - New RDS databases use Postgres 17, gp3 storage, encryption, 7 days of backups and deletion protection. Existing databases keep their engine version (read from AWS, so Terraform doesn't plan a downgrade), storage type and encryption. Changing `database_storage_encrypted` on an existing database is refused, since it would replace the database. + - New installs get an ElastiCache replication group with TLS, encryption at rest and an AUTH token, so `elasticache_details[:redis_url]` starts with `rediss://`. Your app's Redis client must support TLS. Installs that already have the 3.x `aws_elasticache_cluster` keep it unchanged (or set `elasticache_legacy_cluster`). + - `convox_installer.tf` now holds the `provider "aws"` block and a data source for the rack's VPC. The installer stops with instructions if an older file in the rack directory still configures the provider. +- **`apply_terraform_update!` runs `terraform plan` and applies that saved plan**, instead of `terraform apply -auto-approve`. It skips the apply when the plan has no changes. The installer reads the rack's state with `terraform state pull` instead of the local `terraform.tfstate` file, so remote backends work. +- **Environment variables:** every setting reads `CONVOX_INSTALLER_` first. Bare names (`STACK_NAME`) still work for the keys in your script's prompts, as in 3.x. The gem's own optional settings (`database_instance_class` and the rest) read only the prefixed name, so a `DATABASE_PASSWORD` in your shell for another project isn't picked up. +- **Output and exit codes:** each step prints `==> : `, and the script ends with a summary and an exit code that says how it went (see the README). Errors from the gem no longer print a Ruby backtrace. `run_convox_command!` prints the command with secrets masked. +- `backup_convox_host_and_rack` does nothing when the rack is already installed, so a re-run keeps your current rack. +- The config file (`.installer_config.json`) is written with mode 0600 and records the gem version. AWS credentials passed in the environment or on the command line are not saved to it. + +### New + +- **Commands:** `install` (the default, also called `apply`), `plan` (shows which steps would change something, and changes nothing) and `status` (the same checks, to see what exists). +- **Non-interactive mode:** `--yes` (or `--non-interactive`, or `CONVOX_INSTALLER_NON_INTERACTIVE=1`) never prompts. A run with missing settings exits with code 2 and lists them. A run without a terminal and without `--yes` stops before it changes anything and asks for `--yes`. +- **Settings from anywhere:** flags (`--stack-name prod`, `--set key=value`), environment variables, a config file (`--config FILE`), then defaults. +- **`--json`:** one JSON event per line on stdout (`start`, `config`, `step`, `would_run`, `result`), with human logs on stderr. Secrets are masked in every event and log line. +- **Named, resumable steps.** Each step checks the current state first and is skipped when it's done, so a failed run can be repeated. Custom steps in your script: `step 'name', 'description', check: -> { ... } do ... end`. +- `set_convox_env!(values, promote: false)` sets only the app environment variables that changed, sending values on stdin rather than the command line. `convox_env_vars`, `convox_processes` and `convox_api_get(path)` read the app's state. +- `capture_convox_command!(cmd)` runs a `convox` command and returns its output, such as the release ID from `convox build --id`. +- `result_output(key, value)` adds a value to the final result. +- Resuming an interrupted `convox rack install`: if the rack directory exists without an API endpoint, the installer runs `terraform apply` in it. +- Linux support, with install hints for macOS and Linux. +- Rack options: `convox_rack_version`, `convox_rack_params`, `convox_proxy_protocol`, `availability_zones`. + +### Upgrading a 3.x script + +1. Change the gem version to `'~> 4.0'` and run with Ruby 3.2 or later. +2. Remove anything that reads `config.fetch(:aws_access_key_id)` or `:aws_secret_access_key`. For your own `aws` commands, pass `aws_env` as the environment: `system(aws_env, 'aws', 's3', 'rm', ...)`. +3. Replace backtick calls such as `` `convox env --rack ...` `` and `` `convox ps --rack ...` `` with `convox_env_vars` and `convox_processes`. They use the same credentials as the installer and raise a clear error when they fail. +4. Replace `run_convox_command! "env set #{...}"` with `set_convox_env!(desired_env)`. It compares with the current values, sets only what changed and keeps the values off the command line. +5. Wrap your own changes in `step` blocks with a `check:`, so re-runs and `plan` report them properly. +6. If your app connects to Redis, make sure it accepts `rediss://` URLs for new installs. + +Existing installs keep their resources: the installer reads the Terraform state and keeps the current database version, storage, bucket versioning and the 3.x Redis cluster. Run `ruby install.rb plan` first to see what would change. + +## 3.2.1 and earlier + +See the [git history](https://github.com/DocSpring/convox_installer/commits/master). diff --git a/Gemfile b/Gemfile index 2d7c3a4..ad3b9c2 100644 --- a/Gemfile +++ b/Gemfile @@ -4,13 +4,10 @@ source 'https://rubygems.org' gemspec -group :test do - gem 'pry', require: false - gem 'pry-byebug', require: false - gem 'rspec' - gem 'rubocop' - gem 'rubocop-daemon' - gem 'rubocop-rspec' - gem 'vcr' - gem 'webmock' +group :development, :test do + gem 'rake' + gem 'rspec', '~> 3.13' + gem 'rubocop', '~> 1.75' + gem 'rubocop-rspec', '~> 3.6' + gem 'webmock', '~> 3.25' end diff --git a/Gemfile.lock b/Gemfile.lock deleted file mode 100644 index 677865d..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,109 +0,0 @@ -PATH - remote: . - specs: - convox_installer (3.0.0) - activesupport (>= 5.2.3) - highline (>= 1.7.10) - httparty (>= 0.17.0) - json (>= 2.2.0) - os (>= 1.0.1) - -GEM - remote: https://rubygems.org/ - specs: - activesupport (7.0.2.3) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 1.6, < 2) - minitest (>= 5.1) - tzinfo (~> 2.0) - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - ast (2.4.2) - byebug (11.1.3) - coderay (1.1.3) - concurrent-ruby (1.1.10) - crack (0.4.5) - rexml - diff-lcs (1.5.0) - hashdiff (1.0.1) - highline (2.0.3) - httparty (0.20.0) - mime-types (~> 3.0) - multi_xml (>= 0.5.2) - i18n (1.10.0) - concurrent-ruby (~> 1.0) - json (2.6.1) - method_source (1.0.0) - mime-types (3.4.1) - mime-types-data (~> 3.2015) - mime-types-data (3.2022.0105) - minitest (5.15.0) - multi_xml (0.6.0) - os (1.1.4) - parallel (1.22.1) - parser (3.1.1.0) - ast (~> 2.4.1) - pry (0.14.1) - coderay (~> 1.1) - method_source (~> 1.0) - pry-byebug (3.8.0) - byebug (~> 11.0) - pry (~> 0.10) - public_suffix (4.0.6) - rainbow (3.1.1) - regexp_parser (2.2.1) - rexml (3.2.5) - rspec (3.11.0) - rspec-core (~> 3.11.0) - rspec-expectations (~> 3.11.0) - rspec-mocks (~> 3.11.0) - rspec-core (3.11.0) - rspec-support (~> 3.11.0) - rspec-expectations (3.11.0) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.11.0) - rspec-mocks (3.11.1) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.11.0) - rspec-support (3.11.0) - rubocop (1.26.1) - parallel (~> 1.10) - parser (>= 3.1.0.0) - rainbow (>= 2.2.2, < 4.0) - regexp_parser (>= 1.8, < 3.0) - rexml - rubocop-ast (>= 1.16.0, < 2.0) - ruby-progressbar (~> 1.7) - unicode-display_width (>= 1.4.0, < 3.0) - rubocop-ast (1.16.0) - parser (>= 3.1.1.0) - rubocop-daemon (0.3.2) - rubocop - rubocop-rspec (2.9.0) - rubocop (~> 1.19) - ruby-progressbar (1.11.0) - tzinfo (2.0.4) - concurrent-ruby (~> 1.0) - unicode-display_width (2.1.0) - vcr (6.1.0) - webmock (3.14.0) - addressable (>= 2.8.0) - crack (>= 0.3.2) - hashdiff (>= 0.4.0, < 2.0.0) - -PLATFORMS - ruby - -DEPENDENCIES - convox_installer! - pry - pry-byebug - rspec - rubocop - rubocop-daemon - rubocop-rspec - vcr - webmock - -BUNDLED WITH - 1.17.3 diff --git a/README.md b/README.md index 266245a..b2046d6 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,31 @@ # Convox Installer -A Ruby gem that makes it easier to build a Convox installation script. The main purpose of this gem is to make it easier to set up on-premise installations of your app for enterprise users. +A Ruby gem for writing installation scripts that set up an app on [Convox](https://convox.com/) in your customer's (or your own) AWS account. DocSpring uses it to install DocSpring Enterprise. -This gem provides a DSL so that you can write a script that walks your users through setting up Convox and getting your app and running, setting up S3 buckets, etc. +Your script describes the installation with a small DSL. The gem asks for the settings it needs, installs a Convox v3 rack, creates the app, adds a private Docker registry, and adds an S3 bucket, an RDS Postgres database and an ElastiCache Redis cluster to the rack's Terraform configuration. Each step checks what already exists first, so you can run the script again after a failure and it carries on where it stopped. -## Requirements - -- MacOS -- Convox v3 CLI - -_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._ - -### Requires Convox >= 3 - -This version of `convox_installer` is only designed to work with Convox 3 and later. You can run `convox version` to check your version. Please install the Convox v3 CLI by following the instructions here: https://docs.convox.com/getting-started/introduction/ +Scripts run interactively for a person at a terminal, or non-interactively for CI and coding agents, with JSON output and exit codes. -_If you want to set up a Convox v2 rack (deprecated), the last version of `convox_installer` that supports the v2 CLI is `1.0.9`. (Take a look at [the `convox2` branch](https://github.com/DocSpring/convox_installer/tree/convox2).)_ - -## USE AT YOUR OWN RISK! THIS CODE IS PROVIDED WITHOUT ANY WARRANTIES OR GUARANTEES - -We have successfully set up a number of test and production deployments using this gem. Everything seems to work very well. The library also facilitates idempotency and crash-resistance, so you can easily re-run your installation script if something goes wrong. However, if anything goes wrong, then you can end up with a large AWS bill if you're not careful. If anything crashes then make sure you double-check everything in your AWS account and shut down any leftover resources. **USE THIS SOFTWARE AT YOUR OWN RISK.** - -## Features +## Requirements -- Idempotent. If this script crashes, you can restart it and it will pick up - where it left off. Every step looks up the existing state, and only makes a change - if things are not yet set up (or out of sync). -- Ensures that the `convox` and `terraform` CLI tools are installed -- Wraps the `convox` CLI and parses JSON output from API calls -- Add a Docker Repository (e.g. ECR registry) -- Set up an S3 bucket with an optional CORS policy -- Set up an RDS database (Postgres) -- Set up an Elasticache cluster (Redis) +- macOS or Linux +- Ruby 3.2 or later +- [Convox v3 CLI](https://docs.convox.com/installation/cli) (tested with 3.26.0) +- [AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), version 2.9 or later +- [Terraform](https://developer.hashicorp.com/terraform/install) 1.6 or later, or [OpenTofu](https://opentofu.org/docs/intro/install/) +- AWS credentials for the account you're installing into, with permission to create VPCs, EKS clusters, IAM roles, RDS, ElastiCache and S3 resources -## Introduction +On macOS: `brew install awscli hashicorp/tap/terraform` (or `brew install awscli opentofu`), then install the Convox CLI from the link above. `ensure_requirements!` checks all of these and prints install instructions for your system. -[Convox](https://convox.com/) is an awesome open source PaaS, which is like Heroku for your own AWS account. [`convox/rack`](https://github.com/convox/rack) is completely open source and free to use, but you can also sign up for a free or paid account to use the hosted service on convox.com. +For Convox v2 racks, use `convox_installer` 1.0.9. -`convox_installer` is a Ruby gem that makes it much easier to build an installation script for `convox/rack` (the open source PaaS). The Convox CLI is awesome, but it's missing a nice way to script a full deployment. I originally wrote a bash script that made API calls and used [`jq`](https://stedolan.github.io/jq/) and `sed`, but this was very error-prone and it did not have good cross-platform support. +## AWS costs -I've written this installation script in Ruby, which provides very good cross-platform support, and also allows me to write tests. +An installation creates AWS resources that cost money for as long as they exist: an EKS cluster and its EC2 nodes, NAT gateways, an RDS database, an ElastiCache cluster and an S3 bucket. If an install fails part way and you decide not to continue, check your AWS account and remove what was created. `convox rack uninstall ` runs `terraform destroy` in the rack's directory, which also removes the database, Redis cluster and bucket the installer added there. Turn off the database's deletion protection and empty the bucket first, or the destroy stops part way. The software is provided without warranty (see the [licence](./LICENSE)). -## Usage +## Quick start -Create a new Ruby file (e.g. `install.rb`), and use `bundler/inline` to install and require the `convox_installer` gem. Your install script should start like this: +Create `install.rb` in a new repository for your installer: ```ruby #!/usr/bin/env ruby @@ -51,303 +33,288 @@ require 'bundler/inline' gemfile do source 'https://rubygems.org' - gem 'convox_installer', '3.0.0' + gem 'convox_installer', '~> 4.0' end -require "convox_installer" +require 'convox_installer' include ConvoxInstaller -``` -Including the `include ConvoxInstaller` gives you some Ruby methods that you can call to construct an installation workflow. See the "`ConvoxInstaller` DSL" section below. - -You should create a new git repo for your own installation script, and then use the provided classes and methods to build your own installation workflow. You must also include a `convox.yml` (or a `convox.example.yml`). - -You can see a complete example in [`examples/full_installation.rb`](./examples/full_installation.rb). - -## Config - -Config is loaded from ENV vars, or from saved JSON data at -`./.installer_config.json`. The script will save all of the user's responses into `./.installer_config.json` (in the current directory). - -## Customize the Config Prompts - -You can set your own config prompts in your own installation script, by setting a `@prompts` instance variable. You can extend the default config prompts like this: - -```ruby @prompts = ConvoxInstaller::Config::DEFAULT_PROMPTS + [ - { - section: "Docker Authentication", - info: "You should have received authentication details for the Docker Registry\n" \ - "via email. If not, please contact support@example.com", - }, - { - key: :docker_registry_url, - title: "Docker Registry URL", - value: "1234567890.dkr.ecr.us-east-1.amazonaws.com", - }, - { - key: :docker_registry_username, - title: "Docker Registry Username", - }, - { - key: :docker_registry_password, - title: "Docker Registry Password", - } + { key: :convox_app_name, title: 'Convox App Name', value: 'myapp' }, + { key: :docker_registry_url, title: 'Docker Registry URL', value: '123456789012.dkr.ecr.us-east-1.amazonaws.com' }, + { key: :docker_registry_username, title: 'Docker Registry Username' }, + { key: :docker_registry_password, title: 'Docker Registry Password' }, + { key: :s3_bucket_name, title: 'S3 Bucket', value: -> { "myapp-uploads-#{SecureRandom.hex(4)}" } } ] -``` -## Prompt API: +ensure_requirements! +prompt_for_config -The `@prompts` variable must be an array of hashes. There are two kinds of hashes: +backup_convox_host_and_rack +install_convox +validate_convox_rack_and_write_current! +validate_convox_rack_api! -#### Section Heading +create_convox_app! +set_default_app_for_directory! +add_docker_registry! -Shows a heading and optional details. +add_s3_bucket +add_rds_database +add_elasticache_cluster +apply_terraform_update! -```ruby -{ - section: "The heading for this config section", - info: "Description about this config section" -} -``` - -#### Config Prompt - -- A config prompt with a default value: - -```ruby -{ - key: :config_key_name, - title: "Title to show in the user prompt / config summary", - prompt: "Question to show the user", - default: "default value", -} -``` - -- Set a value from a `Proc`, and don't prompt the user: +set_convox_env!( + 'DATABASE_URL' => rds_details[:postgres_url], + 'REDIS_URL' => elasticache_details[:redis_url], + 'AWS_S3_BUCKET' => s3_bucket_details[:name] +) -```ruby - { - key: :config_key_name, - title: "Title to show in the config summary", - value: -> () { "string-with-random-suffix-#{SecureRandom.hex(4)}" }, - } +step 'deploy', 'Deploy the app', check: -> { convox_processes.any? } do + run_convox_command! 'deploy --wait' +end ``` -- Set a value, and hide this setting from the user (even in the summary): +Sign in to AWS (for example `aws sso login --profile prod`), then: -```ruby - { - key: :config_key_name, - value: "Config Value", - hidden: true, - }, +```sh +AWS_PROFILE=prod ruby install.rb # install, asking for anything missing +AWS_PROFILE=prod ruby install.rb plan # what would change, without changing anything ``` -## `ConvoxInstaller` DSL - -#### `ensure_requirements!` - -Makes sure that the `convox` and `terraform` CLI tools are installed on this system. If not, shows installation instructions and exits. - -#### `prompt_for_config` +Your installer repository also needs the app's `convox.yml`. [`examples/full_installation.rb`](./examples/full_installation.rb) is a complete script. -Loads config from ENV vars, or from saved config at `./.installer_config.json`. -If any config settings are missing, it prompts the user for input. Finally, it shows a summary of the config, and asks the user if they want to proceed with the installation. If the user enters `y` (or `yes`), the `prompt_for_config` method completes. If they enter `n` (or `no`), we loop over every setting and let them press "enter" to keep the current value, or provide a new value to correct any mistakes. +## Commands and options -#### `install_convox` - -- **Required Config:** `aws_region`, `aws_access_key_id`, `aws_secret_access_key`, - `stack_name`, `instance_type` - -Runs `convox rack install ...`. Has some validations to ensure that all required settings are present. +``` +ruby install.rb [install|apply|plan|status] [options] +``` -#### `validate_convox_rack_and_write_current!` +| Command | What it does | +| --- | --- | +| `install` (default) | Sets everything up. Run it again to resume; finished steps are skipped. `apply` is the same. | +| `plan` | Runs every step's checks and reports which steps would make changes. Changes nothing. | +| `status` | The same checks as `plan`, to see what exists. Changes nothing. | -Ensures that the local machine contains a directory for the rack's terraform config, and sets the current rack for Convox CLI commands. +| Option | | +| --- | --- | +| `-y`, `--yes`, `--non-interactive` | Never prompt, and start without asking for confirmation. Missing settings are an error. | +| `--json` | One JSON event per line on stdout; human-readable logs go to stderr. | +| `--config FILE` | Config file to use (default `./.installer_config.json`). | +| `--set KEY=VALUE` | Set any setting. Repeatable. | +| `-- VALUE` | Set one setting, for example `--stack-name prod` or `--docker-registry-password ...`. | +| `--log-level LEVEL`, `--debug` | `debug`, `info`, `warn` or `error`. | +| `-h`, `--help` | List every option and setting. | -#### `validate_convox_rack_api!` +`plan` stops early, with exit code 0, when a later step needs something that doesn't exist yet (for example the database URL before the database is created). Everything after that point is pending. -Makes an API request (`convox api get /system`) to get the rack details, and makes sure that everything is correct. +### Exit codes -#### `convox_rack_data` +| Code | Meaning | +| --- | --- | +| 0 | Success. For `plan` and `status`, the checks ran (whether or not changes are pending). | +| 1 | Unexpected error: a bug in the gem or the script. | +| 2 | A setting is missing or invalid, or the command line couldn't be parsed. | +| 3 | A precondition failed: a tool is missing or too old, there are no AWS credentials, or they belong to a different account. | +| 4 | A step failed (a `convox`, `aws` or `terraform` command returned an error). | +| 5 | The input ended at a prompt before an answer. | +| 130 | Interrupted (Ctrl-C). | -Returns a Ruby hash with all convox rack data. +When a run fails, the last lines say what went wrong and what to do next. Fix it and run the same command again. -#### `create_convox_app!` +## Settings -- **Required Config:** `convox_app_name` +Each setting comes from, highest precedence first: -Checks if the app already exists. If not, calls `convox apps create ... --wait` to create a new app. Then waits for the app to be ready. (Avoids an occasional race condition.) +1. Command-line flags: `--stack-name prod` or `--set stack_name=prod`. +2. Environment variables: `CONVOX_INSTALLER_STACK_NAME`. The keys in your script's `@prompts` also read the bare name (`STACK_NAME`), as in 3.x. A few settings read their usual names (`AWS_REGION`, `AWS_DEFAULT_REGION`, `AWS_PROFILE`). +3. The config file, `./.installer_config.json`. +4. The prompt's `value:` (generated, never asked) or `default:` (offered at the prompt, used as is with `--yes`). -#### `set_default_app_for_directory!` +Interactive runs ask for anything still missing, show a summary with secrets masked, and ask before starting. The installer saves every value to the config file (mode 0600) as soon as it's known, so generated names and passwords stay the same on the next run. Keep that file safe: it holds the generated passwords. AWS credentials given in the environment or on the command line are never saved. -Writes the app name into `./.convox/app` (in the current directory.) The `convox` CLI reads this file, so you don't need to specify the `--app` flag for future commands. +### Default prompts -#### `add_s3_bucket` +`ConvoxInstaller::Config::DEFAULT_PROMPTS` asks for `stack_name` (the rack name, default `convox`), `aws_region` (default `us-east-1`) and `instance_type` (default `t3.medium`), and generates `random_id`, a short suffix that keeps resource names unique. -Adds an S3 bucket to your Terraform config. +### Writing prompts -- **Required Config:** `s3_bucket_name` +`@prompts` is an array of hashes. A section heading: -NOTE: This method just writes a new Terraform configuration file. You must run `apply_terraform_update!` to apply the changes and create the S3 bucket. +```ruby +{ section: 'Docker Registry', info: 'You should have received these details by email.' } +``` -Creates an S3 bucket from the `:s3_bucket_name` config setting. This is not a default setting, so you can add something like this to your custom `@prompts`: +A setting: ```ruby - { - key: :s3_bucket_name, - title: "S3 Bucket for uploads", - value: -> () { "yourapp-uploads-#{SecureRandom.hex(4)}" }, - } +{ + key: :admin_email, + title: 'Admin Email', # shown in the prompt and the summary + prompt: 'Email for the admin user: ', # optional question text + default: 'admin@example.com', # optional default + validate: /@/, # optional Regexp, or a Proc returning true, false or an error message + secret: true # optional; keys containing password, secret, token, license and similar are secret anyway +} ``` -The `:value` `Proc` will generate a bucket name with a random suffix. (Avoids conflicts when you are setting up multiple deployments for your app.) - -You can also set a CORS policy for your S3 bucket. (`:s3_bucket_name`) -We set the `cors_rule` option for the `aws_s3_bucket` resource in the Terraform configuration. Example: +A generated value that's never asked for, and a hidden setting that isn't shown in the summary: -``` - cors_rule { - allowed_headers = ["*"] - allowed_methods = ["PUT", "POST"] - allowed_origins = ["https://s3-website-test.hashicorp.com"] - expose_headers = ["ETag"] - max_age_seconds = 3000 - } +```ruby +{ key: :admin_password, title: 'Admin Password', value: -> { SecureRandom.hex(8) } } +{ key: :database_username, value: 'myapp', hidden: true } ``` -See: https://registry.terraform.io/providers/hashicorp/aws/3.33.0/docs/resources/s3_bucket#using-cors +### Gem settings + +These change what the gem creates. Set them like any other setting (`--database-instance-class db.t4g.medium` or `CONVOX_INSTALLER_DATABASE_INSTANCE_CLASS=db.t4g.medium`), or add them to `@prompts`. `ruby install.rb --help` lists them all. + +| Setting | Default | +| --- | --- | +| `aws_profile` | The default AWS credential chain | +| `aws_account_id` | Saved after the first run; later runs stop if the credentials belong to another account | +| `terraform_binary` | `terraform`, or `tofu` when Terraform isn't installed | +| `convox_rack_version` | The latest Convox release | +| `convox_rack_params` | Extra `convox rack install` parameters, `key=value` pairs separated by spaces | +| `convox_proxy_protocol` | `true` (passes client IPs to the app) | +| `availability_zones` | Chosen by AWS, except in us-east-1, where us-east-1c is left out | +| `database_engine_version` | `17` for new databases; existing databases keep theirs | +| `database_instance_class` | `db.t3.small` | +| `database_allocated_storage` | `30` (GiB) | +| `database_storage_type`, `database_storage_encrypted` | `gp3`, `true` for new databases | +| `database_multi_az`, `database_deletion_protection` | `true` | +| `database_backup_retention_period` | `7` days for new databases | +| `database_allow_major_version_upgrade` | `false`; set it to `true` when you raise `database_engine_version` to a new major version | +| `database_username`, `database_password` | `app`, generated | +| `elasticache_engine`, `elasticache_engine_version` | `redis`, `7.1` (`valkey` defaults to `8.0`) | +| `elasticache_node_type`, `elasticache_num_cache_nodes` | `cache.t3.medium`, `1` (2 or more turns on failover and Multi-AZ) | +| `elasticache_auth_token` | Generated | +| `elasticache_legacy_cluster` | `true` when the 3.x cluster already exists | +| `s3_bucket_versioning` | `Enabled` for new buckets; existing buckets keep theirs | +| `s3_bucket_noncurrent_version_expiration_days` | `30` | +| `s3_bucket_cors_rule` | None | +| `default_service` | `web` | +| `convox_api_timeout` | `360` seconds | + +## AWS credentials + +The installer uses the standard AWS credential chain: `AWS_PROFILE` (or the `aws_profile` setting), SSO, `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, or an instance role. It never asks for keys. Before it starts, it shows the account and principal from `aws sts get-caller-identity` and the region, so you can check you're installing into the right place. + +The Convox CLI only reads keys from environment variables, so the installer resolves the chain with `aws configure export-credentials` and passes short-lived keys to `convox` and `terraform`. They're refreshed before they expire, and never printed or saved. + +## Non-interactive runs (CI and coding agents) + +```sh +AWS_PROFILE=prod \ +CONVOX_INSTALLER_DOCKER_REGISTRY_PASSWORD="$REGISTRY_PASSWORD" \ +ruby install.rb --yes --json --stack-name prod --aws-region eu-west-1 --docker-registry-username ci +``` -_Note: If the `:s3_bucket_cors_rule` setting is not provided, then it is skipped._ +- `--yes` never prompts. If settings are missing, the run exits with code 2 and lists them, with the flag and environment variable for each. +- Without a terminal and without `--yes`, the installer stops before it changes anything and asks you to check the settings and add `--yes`. +- Run `plan --json` first to see what would change. -Here's how we set up a CORS policy in our own `install.rb` script: +With `--json`, stdout carries only JSON events, one per line. Everything else, including output from `convox` and `terraform` and anything your script prints, goes to stderr. -```ruby -xxxxc = <<-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 = [ - { - key: :s3_bucket_cors_rule, - value: S3_BUCKET_CORS_RULE, - hidden: true, - } -] +```json +{"event":"start","time":"2026-11-18T09:00:00Z","version":"4.0.0","command":"install","dry_run":false} +{"event":"config","time":"...","file":"/path/.installer_config.json","settings":{"stack_name":"prod","docker_registry_password":"[hidden]"},"sources":{"stack_name":"flag","docker_registry_password":"env:CONVOX_INSTALLER_DOCKER_REGISTRY_PASSWORD"}} +{"event":"step","time":"...","step":"convox_rack","status":"started","description":"Install the Convox rack prod"} +{"event":"step","time":"...","step":"convox_rack","description":"Install the Convox rack prod","status":"done","rack_dir":"..."} +{"event":"step","time":"...","step":"convox_app","description":"Create the myapp app","status":"skipped","state":"present","reason":"myapp already exists"} +{"event":"result","time":"...","command":"install","status":"succeeded","exit_code":0,"steps":[{"step":"convox_rack","status":"done"}],"outputs":{"domain":"web.myapp.0a1b2c.convox.cloud"},"config_file":"/path/.installer_config.json"} ``` -#### `add_rds_database` +[AGENTS.md](./AGENTS.md) describes every event and field. -Adds an RDS database to your Terraform config. +## Steps -- **Required Config:** - - `database_username` - - `database_password` -- **Optional Config:** - - `database_allocated_storage` _(default: 30)_ - - `database_engine` _(default: 'postgres')_ - - `database_engine_version` _(default: '15.7')_ - - `database_instance_class` _(default: 'db.t3.small')_ - - `database_multi_az` _(default: true)_ +Every DSL method that changes something is a named step. Before it changes anything, a step checks the current state; when there's nothing to do it's skipped. The names are stable, so you can refer to them in logs and runbooks. -#### `add_elasticache_cluster` +| Step | Method | What it does | +| --- | --- | --- | +| `requirements` | `ensure_requirements!` | Checks for `convox` (v3), `aws` (v2.9+) and `terraform` (1.6+) or `tofu` | +| `config` | `prompt_for_config` | Loads and checks the settings and AWS credentials, shows the summary and asks to start; returns the settings hash | +| | `backup_convox_host_and_rack` | Before a new install, moves the Convox CLI's current-rack file to `current.bak` | +| `convox_rack` | `install_convox` | Runs `convox rack install aws ...`, or resumes an unfinished install | +| `convox_current_rack` | `validate_convox_rack_and_write_current!` | Makes the rack the CLI's current rack (`convox switch`) | +| `convox_rack_api` | `validate_convox_rack_api!` | Waits for the rack API and checks it's the right rack | +| `convox_app` | `create_convox_app!` | Creates the app (`convox_app_name`) | +| `convox_app_directory` | `set_default_app_for_directory!` | Writes `./.convox/app`, so `convox` commands here don't need `--app` | +| `docker_registry` | `add_docker_registry!` | Adds `docker_registry_url` with its username and password | +| `terraform_s3_bucket` | `add_s3_bucket` | Writes `s3_bucket.tf`: the bucket `-`, a KMS key and an IAM user for the app | +| `terraform_rds_database` | `add_rds_database` | Writes `rds.tf`: an RDS Postgres database in the rack's VPC | +| `terraform_elasticache` | `add_elasticache_cluster` | Writes `elasticache.tf`: a Redis replication group with TLS and AUTH | +| `terraform_apply` | `apply_terraform_update!` | Runs `terraform plan` and applies the plan when there are changes | +| `convox_env` | `set_convox_env!(values, promote: false)` | Sets the app environment variables that changed | -Adds an Elasticache cluster to your Terraform config. +The Terraform files go in the rack's directory, next to Convox's own `main.tf`: `~/Library/Preferences/convox/racks/` on macOS, `~/.config/convox/racks/` on Linux (or `$CONVOX_CONFIG/racks/`). The `add_*` methods only write files; `apply_terraform_update!` creates the resources. -- **Optional Config:** - - `engine` _(default: 'redis')_ - - `engine_version` _(default: '7.1')_ - - `node_type` _(default: 'cache.t3.medium')_ - - `num_cache_nodes` _(default: 1)_ - - `port` _(default: 6379)_ +Methods that read state: -#### `apply_terraform_update!` +- `rds_details`: `{ postgres_url:, host:, port:, username: }` +- `elasticache_details`: `{ redis_url:, host:, port: }` +- `s3_bucket_details`: `{ name:, access_key_id:, secret_access_key: }` (the IAM user's key, for the app) +- `default_service_domain_name`: the `*.convox.cloud` domain of `default_service`, such as `web.myapp.0a1b2c.convox.cloud` +- `convox_rack_data`, `convox_env_vars`, `convox_processes`, `convox_api_get(path)`, `terraform_state`, `terraform_outputs` +- `aws_env` (environment for your own `aws` commands), `aws_identity`, `installer_command`, `dry_run?`, `config`, `logger` -Runs `terraform apply -auto-approve` to apply any changes to your Terraform configuration (add new resources, etc.) +`run_convox_command!(cmd)` runs a `convox` command with `--rack ` and the installer's credentials, and raises when it fails. In `plan` and `status` it prints the command instead of running it. `capture_convox_command!(cmd)` does the same and returns the command's output, as in `capture_convox_command!('build --id').strip`; in `plan` and `status` it returns `nil`. -#### `rds_details` - -Returns information about the created RDS database resource. +### Your own steps ```ruby -{ - postgres_url: "Full URL for the RDS database (including auth)", -} +step 'database_setup', 'Set up the database', check: -> { config[:database_setup_done] } do + run_convox_command! 'run web rake db:prepare' + config[:database_setup_done] = 'true' # saved to the config file +end ``` -#### `elasticache_details` - -Returns information about the created RDS database resource. +In `install` the block runs unless `check` returns true. In `plan` and `status` the block doesn't run: the step is reported as done when `check` returns true, and pending otherwise. If your block can check for itself, pass `plan_aware: true` and call `s.skip!('reason')` or `s.plan!(action: 'create')` before changing anything: ```ruby -{ - redis_url: "Full URL for the Redis cluster", -} +step 'seed_data', plan_aware: true do |s| + s.skip!('already seeded') if convox_env_vars['SEEDED'] == 'true' + s.plan!(action: 'run') + run_convox_command! 'run web rake db:seed' + run_convox_command! 'env set SEEDED=true' +end ``` -#### `s3_bucket_details` +`result_output(:domain, domain)` adds a value to the final result event. -- **Required Config:** `s3_bucket_name` +### S3 CORS rules -Get the S3 bucket details for `s3_bucket_name`. Parses the URL and returns a hash: +`s3_bucket_cors_rule` takes a Terraform `cors_rule` block, or a list of rule hashes in the config file: ```ruby { - access_key_id: "AWS Access Key ID", - secret_access_key: "AWS Secret Access Key", - name: "Full S3 Bucket Name (includes the rack/app)", + key: :s3_bucket_cors_rule, + hidden: true, + value: <<~TERRAFORM + cors_rule { + allowed_headers = ["Authorization", "cache-control", "x-requested-with"] + allowed_methods = ["PUT", "POST", "GET"] + allowed_origins = ["*"] + max_age_seconds = 3000 + } + TERRAFORM } ``` -I use these S3 bucket details to set env variables for my app. (`convox env set ...`) - -#### `add_docker_registry!` - -- **Required Config:** `docker_registry_url`, `docker_registry_username`, `docker_registry_password` - -Checks the list of registries to see if `docker_registry_url` has already been added. If not, runs `convox registries add ...` to add a new Docker registry (e.g. Docker Hub, ECR). - -#### `default_service_domain_name` - -- **Required Config:** `convox_app_name` -- **Optional Config:** `default_service` +## Upgrading from 3.x -Finds the default `*.convox.cloud` URL for the web service. (You can visit this URL in the browser to access your app.) +See [CHANGELOG.md](./CHANGELOG.md#upgrading-a-3x-script). Existing installs keep their database version, storage settings, bucket versioning and Redis cluster. Run `ruby install.rb plan` before `install` to see what would change. -Example: `web.docspring.dc6bae48c2e36366.convox.cloud` +## Development -You can override the default service name in your config (e.g. `web`): - -```ruby -@prompts = [ - # ... - { - key: :default_service, - title: "Default Convox Service (for domain)", - value: "web", - hidden: true, - } -] +```sh +bundle install +bundle exec rspec +bundle exec rubocop ``` -> (This hidden setting isn't visible to the user.) - -#### `run_convox_command!(cmd)` - -Runs a `convox` CLI command, and shows all output in the terminal. Crashes the script with an error if the `convox` command has a non-zero exit code. - -If you want to run `convox env set MYVAR=value`, then you would call: - -```ruby -run_convox_command! 'env set MYVAR=value' -``` +The specs never call AWS or Convox. [AGENTS.md](./AGENTS.md) explains how the code fits together. ## License diff --git a/convox_installer.gemspec b/convox_installer.gemspec index 16dedcf..3b97357 100644 --- a/convox_installer.gemspec +++ b/convox_installer.gemspec @@ -10,20 +10,21 @@ Gem::Specification.new do |s| s.authors = ['DocSpring, Inc.'] s.email = ['support@docspring.com'] s.homepage = 'https://github.com/DocSpring/convox_installer' - s.summary = 'Build a Convox installation workflow' - s.description = 'Build a Convox installation workflow' + s.summary = 'Write installation scripts that set up a Convox v3 rack and an app on AWS' + s.description = 'A Ruby DSL for installation scripts that install a Convox v3 rack on AWS, add an S3 bucket, ' \ + 'RDS Postgres and ElastiCache Redis with Terraform, and deploy an app. Scripts are idempotent ' \ + 'and resumable, and run interactively or unattended with JSON output.' s.license = 'MIT' - s.required_ruby_version = '>= 2.5' + s.required_ruby_version = '>= 3.2' - s.add_runtime_dependency 'activesupport', '>= 5.2.3' - s.add_runtime_dependency 'highline', '>= 1.7.10' - s.add_runtime_dependency 'httparty', '>= 0.17.0' - s.add_runtime_dependency 'json', '>= 2.2.0' - s.add_runtime_dependency 'os', '>= 1.0.1' + s.add_dependency 'highline', '>= 2.0', '< 4' + # logger leaves Ruby's default gems in Ruby 3.5. + s.add_dependency 'logger', '>= 1.5' - s.files = `git ls-files`.split("\n").uniq.sort.reject(&:empty?) - ['Gemfile.lock'] - s.test_files = `git ls-files spec test`.split("\n") + s.files = Dir['lib/**/*.rb', 'terraform/*.erb', 'examples/*.rb', 'README.md', 'CHANGELOG.md', 'AGENTS.md', 'LICENSE'] s.executables = [] s.require_paths = ['lib'] s.metadata['rubygems_mfa_required'] = 'true' + s.metadata['changelog_uri'] = 'https://github.com/DocSpring/convox_installer/blob/master/CHANGELOG.md' + s.metadata['source_code_uri'] = 'https://github.com/DocSpring/convox_installer' end diff --git a/examples/full_installation.rb b/examples/full_installation.rb index 3421391..bc022d0 100755 --- a/examples/full_installation.rb +++ b/examples/full_installation.rb @@ -1,27 +1,27 @@ #!/usr/bin/env ruby # frozen_string_literal: true -# Use Bundler inline for your real installation script -# require "bundler/inline" - -# gemfile do -# source "https://rubygems.org" -# gem "convox_installer" -# end - -require 'English' -$LOAD_PATH << File.expand_path('../lib', __dir__) -require 'pry-byebug' - +# A complete installation script. Copy it into your own repository, then change the prompts +# and the app setup at the end. A real script loads the gem with bundler/inline: +# +# require 'bundler/inline' +# gemfile do +# source 'https://rubygems.org' +# gem 'convox_installer', '~> 4.0' +# end +# +# Run it: +# +# ruby install.rb # interactive install (re-run to resume) +# ruby install.rb plan # what would change, without changing anything +# ruby install.rb status # what exists now +# ruby install.rb --yes --json --docker-registry-username ... --docker-registry-password ... + +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'convox_installer' include ConvoxInstaller -@log_level = Logger::DEBUG - -MINIMAL_HEALTH_CHECK_PATH = '/health/site' -COMPLETE_HEALTH_CHECK_PATH = '/health' - -S3_BUCKET_CORS_RULE = <<-TERRAFORM +S3_BUCKET_CORS_RULE = <<~TERRAFORM cors_rule { allowed_headers = ["Authorization", "cache-control", "x-requested-with"] allowed_methods = ["PUT", "POST", "GET"] @@ -40,7 +40,7 @@ { key: :docker_registry_url, title: 'Docker Registry URL', - value: '691950705664.dkr.ecr.us-east-1.amazonaws.com' + value: '123456789012.dkr.ecr.us-east-1.amazonaws.com' }, { key: :docker_registry_username, @@ -53,19 +53,12 @@ { key: :convox_app_name, title: 'Convox App Name', - value: 'convox-app' - }, - { - key: :default_service, - title: 'Default Convox Service (for domain)', - value: 'web', - hidden: true + value: 'example-app' }, { key: :admin_email, title: 'Admin User Email', - prompt: 'Please enter the email address you would like to use ' \ - 'for the default admin user', + prompt: 'Please enter the email address you would like to use for the default admin user', default: 'admin@example.com' }, { @@ -84,19 +77,19 @@ hidden: true }, { - key: :database_username, - value: 'example_app', + key: :secret_key_base, + value: -> { SecureRandom.hex(64) }, hidden: true }, { - key: :database_password, - value: -> { SecureRandom.hex(16) }, + key: :database_username, + value: 'example_app', hidden: true } ] ensure_requirements! -config = prompt_for_config +settings = prompt_for_config backup_convox_host_and_rack install_convox @@ -110,167 +103,52 @@ add_s3_bucket add_rds_database add_elasticache_cluster - apply_terraform_update! -unless config[:sidekiq_cloudwatch_iam_credentials] - logger.info "Looking up IAM user for Sidekiq CloudWatch metrics (#{config.fetch(:sidekiq_cloudwatch_iam_username)})..." - - aws_cli_credentials = "AWS_ACCESS_KEY_ID=#{config.fetch(:aws_access_key_id)} " \ - "AWS_SECRET_ACCESS_KEY=#{config.fetch(:aws_secret_access_key)}" - `#{aws_cli_credentials} aws iam get-user \ - --user-name #{config.fetch(:sidekiq_cloudwatch_iam_username)} 2>/dev/null` - unless $CHILD_STATUS.success? - logger.info "Creating IAM user: #{config.fetch(:sidekiq_cloudwatch_iam_username)} with CloudWatchAgentServerPolicy..." - # IAM user needs the CloudWatchAgentServerPolicy policy - `#{aws_cli_credentials} aws iam create-user \ - --user-name #{config.fetch(:sidekiq_cloudwatch_iam_username)}` - unless $CHILD_STATUS.success? - raise "Sorry, something went wrong while creating the #{config.fetch(:sidekiq_cloudwatch_iam_username)} IAM user!" - end - - logger.info 'Attaching CloudWatchAgentServerPolicy...' - `#{aws_cli_credentials} aws iam attach-user-policy \ - --user-name #{config.fetch(:sidekiq_cloudwatch_iam_username)} \ - --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy` - unless $CHILD_STATUS.success? - raise 'Sorry, something went wrong while attaching the CloudWatchAgentServerPolicy policy!' - end - end - logger.info "Creating IAM access token for #{config.fetch(:sidekiq_cloudwatch_iam_username)}..." - - create_access_key_output_json = `#{aws_cli_credentials} aws iam create-access-key \ - --user-name #{config.fetch(:sidekiq_cloudwatch_iam_username)}` - unless $CHILD_STATUS.success? - raise "Sorry, something went wrong while creating the access token for #{config.fetch(:sidekiq_cloudwatch_iam_username)}!" - end - - config[:sidekiq_cloudwatch_iam_credentials] = - JSON.parse(create_access_key_output_json)['AccessKey'] - - # Save credentials in the cached config file - File.open('./.installer_config.json', 'w') do |f| - f.puts(JSON.pretty_generate(config: config)) - end -end - -logger.info "======> Default domain: #{default_service_domain_name}" -logger.info ' You can use this as a CNAME record after configuring a domain in convox.yml' -logger.info ' (Note: SSL will be configured automatically.)' - -logger.info 'Checking convox env...' -convox_env_output = `convox env --rack #{config.fetch(:stack_name)}` -raise 'Error running convox env' unless $CHILD_STATUS.success? +domain = default_service_domain_name +result_output(:domain, domain) -convox_env = begin - convox_env_output.split("\n").map { |s| s.split('=', 2) }.to_h -rescue StandardError - {} -end - -# Add database and redis -desired_env = { +set_convox_env!( 'DATABASE_URL' => rds_details[:postgres_url], 'REDIS_URL' => elasticache_details[:redis_url], - 'AWS_ACCESS_KEY_ID' => s3_bucket_details.fetch(:access_key_id), - 'AWS_ACCESS_KEY_SECRET' => s3_bucket_details.fetch(:secret_access_key), - 'AWS_UPLOADS_S3_BUCKET' => s3_bucket_details.fetch(:name), - 'AWS_UPLOADS_S3_REGION' => config.fetch(:aws_region), - 'SECRET_KEY_BASE' => config.fetch(:secret_key_base), - 'SUBMISSION_DATA_ENCRYPTION_KEY' => config.fetch(:data_encryption_key), - 'ADMIN_NAME' => 'Admin', - 'ADMIN_EMAIL' => config.fetch(:admin_email), - 'ADMIN_PASSWORD' => config.fetch(:admin_password), - 'DOCSPRING_LICENSE' => config.fetch(:docspring_license), - 'DISABLE_EMAILS' => 'true' -} - -# Only set health check path and domain if it's not already present. -desired_env['HEALTH_CHECK_PATH'] = MINIMAL_HEALTH_CHECK_PATH if convox_env['HEALTH_CHECK_PATH'].nil? -desired_env['DOMAIN_NAME'] = default_service_domain_name if convox_env['DOMAIN_NAME'].nil? - -updated_keys = [] -desired_env.each_key do |key| - updated_keys << key if convox_env[key] != desired_env[key] + 'AWS_ACCESS_KEY_ID' => s3_bucket_details[:access_key_id], + 'AWS_SECRET_ACCESS_KEY' => s3_bucket_details[:secret_access_key], + 'AWS_S3_BUCKET' => s3_bucket_details[:name], + 'AWS_REGION' => settings.fetch(:aws_region), + 'SECRET_KEY_BASE' => settings.fetch(:secret_key_base), + 'ADMIN_EMAIL' => settings.fetch(:admin_email), + 'ADMIN_PASSWORD' => settings.fetch(:admin_password), + 'DOMAIN_NAME' => domain +) + +step 'initial_deploy', 'Deploy the app for the first time', + check: -> { convox_processes.any? { |process| process['name'] == 'web' } } do + run_convox_command! 'deploy --wait' end -if updated_keys.none? - logger.info '=> Convox env has already been configured.' - logger.info ' You can update this by running: convox env set ...' -else - logger.info "=> Setting environment variables to configure DocSpring: #{updated_keys.join(', ')}" - env_command_params = desired_env.map { |k, v| "#{k}=\"#{v}\"" }.join(' ') - run_convox_command! "env set #{env_command_params}" +step 'database_setup', 'Set up the database', check: -> { config[:database_setup_done] } do + run_convox_command! 'run web rake db:prepare' + config[:database_setup_done] = 'true' end -# If we are already using the complete health check path, then we can skip the rest. -if convox_env['HEALTH_CHECK_PATH'] == COMPLETE_HEALTH_CHECK_PATH - logger.info 'DocSpring is already set up and running.' -else - logger.info 'Checking convox processes...' - convox_processes = `convox ps --rack #{config.fetch(:stack_name)}` - if convox_processes.include?('web') && convox_processes.include?('worker') - logger.info '=> Initial deploy for DocSpring Enterprise is already done.' - else - logger.info '=> Initial deploy for DocSpring Enterprise...' - logger.info '-----> Documentation: https://docs.convox.com/deployment/deploying-changes/' - run_convox_command! 'deploy' - end - - logger.info '=> Ensuring the DocSpring application container can boot successfully...' - run_convox_command! 'run command ./bin/smoke_test' - - logger.info '=> Setting up the DocSpring database...' - run_convox_command! 'run command rake db:create db:migrate db:seed' - - logger.info '=> Checking Postgres, Redis, Rails cache, S3 uploads, Sidekiq job processing...' - run_convox_command! 'run command rake tests:health_check' - - logger.info '=> Updating the health check path to include database tests...' - run_convox_command! "env set --promote HEALTH_CHECK_PATH=#{COMPLETE_HEALTH_CHECK_PATH}" -end +return if dry_run? puts logger.info 'All done!' puts -puts "You can now visit #{default_service_domain_name} and sign in with:" -puts -puts " Email: #{config.fetch(:admin_email)}" -puts " Password: #{config.fetch(:admin_password)}" +puts "You can now visit https://#{domain} and sign in as #{settings.fetch(:admin_email)}." +puts "The admin password is saved in #{config.path} (admin_password)." puts puts 'You can configure a custom domain name, auto-scaling, and other options in convox.yml.' puts 'To deploy your changes, run: convox deploy --wait' puts -puts "IMPORTANT: You should be very careful with the 'resources' section in convox.yml." -puts 'If you remove, rename, or change these resources, then Convox will delete' -puts 'your database. This will result in downtime and a loss of data.' -puts 'To prevent this from happening, you can sign into your AWS account,' -puts 'visit the RDS and ElastiCache services, and enable "Termination Protection"' -puts 'for your database resources.' -puts -puts 'To learn more about the convox CLI, run: convox --help' -puts -puts ' * View the Convox documentation: https://docs.convox.com/' -puts ' * View the DocSpring documentation: https://docspring.com/docs/' -puts -puts -puts 'To completely uninstall Convox and DocSpring from your AWS account,' -puts 'run the following steps (in this order):' -puts -puts ' 1) Disable "Termination Protection" for any resource where it was enabled.' -puts -puts " 2) Delete all files from the #{s3_bucket_details.fetch(:name)} S3 bucket:" -puts -puts " export AWS_ACCESS_KEY_ID=#{config.fetch(:aws_access_key_id)}" -puts " export AWS_SECRET_ACCESS_KEY=#{config.fetch(:aws_secret_access_key)}" -puts " aws s3 rm s3://#{s3_bucket_details.fetch(:name)} --recursive" -puts -puts ' 3) Uninstall Convox (deletes all AWS resources via Terraform):' -puts -puts " convox rack uninstall #{config.fetch(:stack_name)}" -puts +puts 'To remove everything from your AWS account, in this order:' puts -puts '------------------------------------------------------------------------------------' -puts 'Thank you for using DocSpring! Please contact support@docspring.com if you need any help.' -puts '------------------------------------------------------------------------------------' +puts " 1) Turn off deletion protection for the database: aws rds modify-db-instance \\\n " \ + "--db-instance-identifier #{settings.fetch(:stack_name)}-rds-#{settings.fetch(:random_id)} " \ + '--no-deletion-protection --apply-immediately' +puts " 2) Empty the #{s3_bucket_details[:name]} bucket (the S3 console's Empty button removes old versions too)." +puts " 3) Delete the app: convox apps delete #{settings.fetch(:convox_app_name)}" +puts ' 4) Uninstall the rack (deletes its AWS resources with Terraform): ' \ + "convox rack uninstall #{settings.fetch(:stack_name)}" puts diff --git a/lib/convox/client.rb b/lib/convox/client.rb index c64328c..9a4c8c6 100644 --- a/lib/convox/client.rb +++ b/lib/convox/client.rb @@ -1,76 +1,140 @@ # frozen_string_literal: true -require 'logger' -require 'json' +require 'erb' require 'fileutils' +require 'json' +require 'logger' require 'rubygems' -require 'os' -require 'erb' +require 'securerandom' +require 'shellwords' +require 'tmpdir' +require 'uri' +require 'convox_installer/version' +require 'convox_installer/errors' +require 'convox_installer/masker' +require 'convox_installer/platform' +require 'convox_installer/settings' +require 'convox_installer/options' +require 'convox_installer/reporter' +require 'convox_installer/shell' +require 'convox_installer/runner' +require 'convox_installer/context' +require 'convox_installer/aws_session' module Convox + # Wraps the convox, terraform and aws commands an installation needs. Every public method + # that changes something is a named step (see ConvoxInstaller::Runner): it checks first, + # changes only what is missing, and reports what it would do in `plan` and `status`. class Client - CONVOX_CONFIG_DIR = if OS.mac? - # Convox v3 moved this to ~/Library/Preferences/convox/ on Mac - File.expand_path('~/Library/Preferences/convox').freeze - else - File.expand_path('~/.convox').freeze - end + TEMPLATE_DIR = File.expand_path('../../terraform', __dir__) + + # us-east-1c has often lacked EKS capacity ("Cannot create cluster ... because + # us-east-1c, the targeted availability zone, does not currently have sufficient + # capacity"), so it is left out unless availability_zones is set. + US_EAST_1_ZONES = 'us-east-1a,us-east-1b,us-east-1d,us-east-1e,us-east-1f' + + # Kept for scripts that read them. They are fixed when the gem loads; the client + # itself reads the directory at call time, so CONVOX_CONFIG set later still works. + CONVOX_CONFIG_DIR = ConvoxInstaller::Platform.convox_config_dir.freeze + CURRENT_FILE = File.join(CONVOX_CONFIG_DIR, 'current').freeze + + # Renders a .tf.erb template. Templates call v(:name) for raw values and s(:name) for + # values as quoted HCL strings. + class TemplateContext + def initialize(vars) + @vars = vars + end + + def v(key) = @vars.fetch(key) - CURRENT_FILE = File.join(CONVOX_CONFIG_DIR, 'current') + def s(key) = hcl_string(v(key)) + + def hcl_string(value) + JSON.generate(value.to_s).gsub('${', '$${').gsub('%{', '%%{') + end + + def render(template) + ERB.new(template, trim_mode: '-').result(binding) + end + end attr_accessor :logger, :config + attr_reader :context - def cli_version_string - return @cli_version_string if @cli_version_string + def initialize(options = {}) + @context = options[:context] || ConvoxInstaller::Context.new(log_level: options[:log_level]) + @logger = context.logger + @config = options[:config] || {} + @aws_session = options[:aws_session] + @on_config_change = options[:on_config_change] + end - cli_version_string ||= `convox --version` - return unless $CHILD_STATUS.success? + def aws_session + @aws_session ||= ConvoxInstaller::AwsSession.new(context: context, config: config) + end - @cli_version_string = cli_version_string.chomp + def convox_config_dir + ConvoxInstaller::Platform.convox_config_dir end - def cli_version - return unless cli_version_string.is_a?(String) + def current_file + File.join(convox_config_dir, 'current') + end - if cli_version_string.match?(/^\d+\.\d+\.\d+/) - @cli_version ||= Gem::Version.new(version_string) - end - @cli_version + # ---- Convox CLI version ---------------------------------------------------------- + + def cli_version_string + return @cli_version_string if defined?(@cli_version_string) + + result = shell.capture(%w[convox --version]) + @cli_version_string = result.success? ? result.stdout.strip : nil end - def convox_2_cli? - return false unless cli_version_string.is_a?(String) + def cli_version + return unless cli_version_string&.match?(/\A\d+\.\d+\.\d+/) - cli_version_string.match?(/^20\d+$/) + Gem::Version.new(cli_version_string[/\A\d+\.\d+\.\d+[0-9A-Za-z.]*/]) end def convox_3_cli? - return false if !cli_version_string.is_a?(String) || - convox_2_cli? || - !cli_version_string.match?(/^\d+\.\d+\.\d+/) + version = cli_version + return false unless version - cli_version = Gem::Version.new(cli_version_string) - cli_version >= Gem::Version.new('3.0.0') && - cli_version < Gem::Version.new('4.0.0') + version >= Gem::Version.new('3.0.0') && version < Gem::Version.new('4.0.0') end - def initialize(options = {}) - @logger = Logger.new($stdout) - logger.level = options[:log_level] || Logger::INFO - @config = options[:config] || {} - end + # ---- Rack ------------------------------------------------------------------------ - # Convox v3 creates a folder for each rack for the Terraform config + # The Convox CLI keeps each rack's Terraform configuration and state in its own + # directory: /racks/. def rack_dir - stack_name = config.fetch(:stack_name) - File.join(CONVOX_CONFIG_DIR, 'racks', stack_name) + File.join(convox_config_dir, 'racks', config.fetch(:stack_name)) end + # :missing (no rack directory), :broken (a directory without main.tf), + # :incomplete (an install started but the rack has no API endpoint yet), or :installed. + def rack_install_state + return :missing unless File.directory?(rack_dir) + return :broken unless File.exist?(File.join(rack_dir, 'main.tf')) + + api = terraform_outputs.dig('api', 'value') + api.to_s.strip.empty? ? :incomplete : :installed + end + + def rack_already_installed? + require_config(%i[aws_region stack_name]) + rack_install_state == :installed + end + + # Moves the CLI's current-rack setting aside before a new install, so the new rack + # becomes the current one. The old setting is kept as current.bak. Does nothing when the + # rack is already installed, so a re-run keeps the current rack. def backup_convox_host_and_rack - FileUtils.mkdir_p CONVOX_CONFIG_DIR + return if context.dry_run? - path = File.join(CONVOX_CONFIG_DIR, 'current') + path = current_file return unless File.exist?(path) + return if present?(config[:stack_name]) && rack_install_state == :installed bak_file = "#{path}.bak" logger.info "Moving existing #{path} to #{bak_file}..." @@ -79,165 +143,174 @@ def backup_convox_host_and_rack def install_convox require_config(%i[aws_region stack_name]) - region = config.fetch(:aws_region) stack_name = config.fetch(:stack_name) - if rack_already_installed? - logger.info "There is already a Convox rack named #{stack_name}. Using this rack." - logger.debug 'If you need to start over, you can run: ' \ - "convox rack uninstall #{stack_name} " \ - '(Make sure you export AWS_ACCESS_KEY_ID and ' \ - "AWS_SECRET_ACCESS_KEY first.)\n" \ - "If this fails, you can try deleting the rack directory: rm -rf #{rack_dir}" - return true - end - - require_config(%i[ - aws_region - aws_access_key_id - aws_secret_access_key - stack_name - instance_type - ]) - - logger.info "Installing Convox (#{stack_name})..." + runner.step('convox_rack', "Install the Convox rack #{stack_name}") do |step| + step.info(rack_dir: rack_dir) + case rack_install_state + when :installed + logger.info "There is already a Convox rack named #{stack_name}. Using this rack." + logger.debug "If you need to start over, run: convox rack uninstall #{stack_name} " \ + "(with the same AWS credentials). If that fails, delete #{rack_dir}." + step.skip!('the rack is already installed') + when :broken + raise ConvoxInstaller::PreconditionFailed.new( + "#{rack_dir} exists but has no main.tf, so the rack can't be installed or resumed.", + next_step: "Make sure nothing else uses this rack name, delete #{rack_dir}, " \ + 'then run the same command again.' + ) + when :incomplete + step.plan!(action: 'resume', state: 'incomplete', + reason: 'the rack directory exists but the rack has no API endpoint yet') + logger.info "Resuming the unfinished install of #{stack_name} (terraform apply in #{rack_dir})..." + resume_rack_install + else + require_config(%i[instance_type]) + argv = rack_install_command + step.plan!(action: 'create', command: shell.display(argv)) + logger.info "Installing Convox (#{stack_name})..." + run!(argv, env: convox_env, + next_step: 'Run the same command again to resume the install. If it keeps failing, ' \ + "`convox rack uninstall #{stack_name}` removes what was created.") + end + reset_terraform_cache! + next if rack_install_state == :installed - env = { - 'AWS_REGION' => region, - 'AWS_ACCESS_KEY_ID' => config.fetch(:aws_access_key_id), - 'AWS_SECRET_ACCESS_KEY' => config.fetch(:aws_secret_access_key) - } - # Set proxy_protocol=true by default to forward client IPs - command = %(rack install aws \ -"#{config.fetch(:stack_name)}" \ -"node_type=#{config.fetch(:instance_type)}" \ -"proxy_protocol=true" \ -"region=#{config.fetch(:aws_region)}") - # us-east constantly has problems with the us-east-1c AZ: - # "Cannot create cluster 'ds-enterprise-cx3' because us-east-1c, the targeted - # availability zone, does not currently have sufficient capacity to support the cluster. - # Retry and choose from these availability zones: - # us-east-1a, us-east-1b, us-east-1d, us-east-1e, us-east-1f - if config.fetch(:aws_region) == 'us-east-1' - command += ' "availability_zones=us-east-1a,us-east-1b,us-east-1d,us-east-1e,us-east-1f"' + raise ConvoxInstaller::StepFailed.new( + "The install of #{stack_name} finished, but the rack has no API endpoint in its Terraform outputs.", + next_step: 'Run the same command again to resume the install.' + ) end - - run_convox_command!(command, env, rack_arg: false) - end - - def rack_already_installed? - require_config(%i[aws_region stack_name]) - return true if File.exist?(rack_dir) - - false + true end - # Auth for a detached rack is not saved in the auth file anymore. - # It can be found in the terraform state: - # ~/Library/Preferences/convox/racks/ds-enterprise-cx3/terraform.tfstate - # Under outputs/api/value. The API URL contains the convox username and API token as basic auth. + # Tells the Convox CLI to use this rack when no --rack flag is given. def validate_convox_rack_and_write_current! require_config(%i[aws_region stack_name]) + stack_name = config.fetch(:stack_name) - unless rack_already_installed? - raise "Could not find rack terraform directory at: #{rack_dir}" + runner.step('convox_current_rack', "Select #{stack_name} as the current Convox rack") do |step| + unless rack_install_state == :installed + step.plan!(action: 'update', state: 'unknown', reason: 'the rack is not installed yet') + raise ConvoxInstaller::PreconditionFailed.new( + "Could not find rack terraform directory at: #{rack_dir}", + next_step: 'Run install_convox first.' + ) + end + step.skip!("#{stack_name} is already the current rack") if current_rack_name == stack_name + step.plan!(action: 'update', state: 'outdated') + run!(['convox', 'switch', stack_name], env: convox_env) end - - # Tells the Convox CLI to use our terraform stack - stack_name = config.fetch(:stack_name) - write_current(stack_name) stack_name end def write_current(rack_name) - logger.debug "Setting convox rack to #{rack_name} (in #{CURRENT_FILE})..." - current_hash = { name: rack_name, type: 'terraform' } - File.open(CURRENT_FILE, 'w') { |f| f.puts current_hash.to_json } + run!(['convox', 'switch', rack_name], env: convox_env) end def validate_convox_rack_api! - require_config(%i[ - aws_region - stack_name - instance_type - ]) - logger.debug 'Validating that convox rack has the correct attributes...' - # Convox 3 racks no longer return info about region or type. (These are blank strings.) - { - provider: 'aws', - # region: config.fetch(:aws_region), - # type: config.fetch(:instance_type), - name: config.fetch(:stack_name) - }.each do |k, v| - convox_value = convox_rack_data[k.to_s] - if convox_value != v - raise "Convox data did not match! Expected #{k} to be '#{v}', " \ - "but was: '#{convox_value}'" + require_config(%i[stack_name]) + runner.step('convox_rack_api', 'Check the rack API') do |step| + if context.dry_run? + unless rack_install_state == :installed + step.plan!(action: 'check', state: 'unknown', reason: 'the rack is not installed yet') + end + begin + convox_rack_data(wait: false) + rescue ConvoxInstaller::StepFailed => e + step.plan!(action: 'check', state: 'unknown', reason: e.message) + end + end + + logger.debug 'Validating that convox rack has the correct attributes...' + # Convox 3 racks no longer return info about region or type. (These are blank strings.) + { 'provider' => 'aws', 'name' => config.fetch(:stack_name) }.each do |key, expected| + actual = convox_rack_data[key] + next if actual == expected + + raise ConvoxInstaller::PreconditionFailed.new( + "Convox data did not match! Expected #{key} to be '#{expected}', but was: '#{actual}'", + next_step: 'Check that stack_name is the rack you meant (convox racks lists them).' + ) end + step.info(version: convox_rack_data['version']) + logger.debug '=> Convox rack has the correct attributes.' end - logger.debug '=> Convox rack has the correct attributes.' true end - def convox_rack_data + # The rack's /system API response. Waits for the API to answer after an install. + def convox_rack_data(wait: !context.dry_run?) @convox_rack_data ||= begin logger.debug 'Fetching convox rack attributes...' - command = "convox api get /system --rack #{config.fetch(:stack_name)}" - logger.debug "+ #{command}" - # It can take a while for the API to be ready. - start_time = Time.now - convox_output = nil + timeout = Integer(config[:convox_api_timeout] || 360) + started = Time.now loop do - convox_output = `#{command}` - break if $CHILD_STATUS.success? - - if Time.now - start_time > 360 - raise 'Could not connect to Convox rack API!' + result = shell.capture(convox_argv('api', 'get', '/system'), env: convox_env) + break JSON.parse(result.stdout) if result.success? + + if !wait || Time.now - started > timeout + raise ConvoxInstaller::StepFailed.new( + "Could not connect to Convox rack API! #{result.stderr.strip}", + next_step: 'Check the rack with `convox rack --rack ' \ + "#{config.fetch(:stack_name)}`, then run the same command again." + ) end - logger.debug 'Waiting for Convox rack API to be ready... (can take a few minutes)' - sleep 5 + logger.info 'Waiting for Convox rack API to be ready... (can take a few minutes)' + pause(5) end - - JSON.parse(convox_output) end end + # ---- App ------------------------------------------------------------------------- + def create_convox_app! require_config(%i[convox_app_name]) - return true if convox_app_exists? - app_name = config.fetch(:convox_app_name) - logger.info "Creating app: #{app_name}..." - logger.info '=> Documentation: ' \ - 'https://docs.convox.com/reference/cli/apps/' - - # NOTE: --wait flags were removed in Convox 3. It now waits by default. - run_convox_command! "apps create #{app_name}" - - retries = 0 - loop do - break if convox_app_exists? - - if retries > 5 - raise "Something went wrong while creating the #{app_name} app! " \ - '(Please wait a few moments and then restart the installation script.)' + runner.step('convox_app', "Create the #{app_name} app") do |step| + plan_unless_rack_installed(step, 'create') + step.skip!("#{app_name} already exists") if convox_app_exists? + step.plan!(action: 'create') + + logger.info "Creating app: #{app_name}..." + logger.info '=> Documentation: https://docs.convox.com/reference/cli/apps/' + # `convox apps create` waits until the app is running. + run!(convox_argv('apps', 'create', app_name), env: convox_env) + + retries = 0 + until convox_app_exists? + if retries > 5 + raise ConvoxInstaller::StepFailed.new( + "Something went wrong while creating the #{app_name} app!", + next_step: 'Wait a few moments, then run the same command again.' + ) + end + logger.info "Waiting for #{app_name} to be ready..." + pause(3) + retries += 1 end - logger.info "Waiting for #{app_name} to be ready..." - sleep 3 - retries += 1 + logger.info "=> #{app_name} app created!" end - - logger.info "=> #{app_name} app created!" + true end + # Writes the app name to ./.convox/app, so convox commands run in this directory + # don't need --app. def set_default_app_for_directory! - logger.info 'Setting default app in ./.convox/app...' - FileUtils.mkdir_p File.expand_path('./.convox') - File.open(File.expand_path('./.convox/app'), 'w') do |f| - f.puts config.fetch(:convox_app_name) + require_config(%i[convox_app_name]) + app_name = config.fetch(:convox_app_name) + path = File.expand_path('./.convox/app') + + runner.step('convox_app_directory', 'Set the default app in ./.convox/app') do |step| + step.skip!("./.convox/app already says #{app_name}") if File.exist?(path) && File.read(path).strip == app_name + step.plan!(action: File.exist?(path) ? 'update' : 'create') + logger.info 'Setting default app in ./.convox/app...' + FileUtils.mkdir_p(File.dirname(path)) + File.write(path, "#{app_name}\n") end + true end def convox_app_exists? @@ -245,97 +318,295 @@ def convox_app_exists? app_name = config.fetch(:convox_app_name) logger.debug "Looking for existing #{app_name} app..." - convox_output = `convox api get /apps --rack #{config.fetch(:stack_name)}` - raise 'convox command failed!' unless $CHILD_STATUS.success? - - apps = JSON.parse(convox_output) - apps.each do |app| - if app['name'] == app_name - logger.debug "=> Found #{app_name} app." - return true + found = convox_api_get('/apps').any? { |app| app['name'] == app_name } + logger.debug(found ? "=> Found #{app_name} app." : "=> Did not find #{app_name} app.") + found + end + + def add_docker_registry! + require_config(%i[docker_registry_url docker_registry_username docker_registry_password]) + registry_url = config.fetch(:docker_registry_url) + + runner.step('docker_registry', "Add the Docker registry #{registry_url}") do |step| + plan_unless_rack_installed(step, 'create') + logger.debug 'Looking up existing Docker registries...' + if convox_api_get('/registries').any? { |r| r['server'] == registry_url } + step.skip!("#{registry_url} is already added") end + step.plan!(action: 'create') + + logger.info "Adding Docker Registry: #{registry_url}..." + logger.info '=> Documentation: https://docs.convox.com/configuration/private-registries/' + run!(convox_argv('registries', 'add', registry_url, + config.fetch(:docker_registry_username), config.fetch(:docker_registry_password)), + env: convox_env) end - logger.debug "=> Did not find #{app_name} app." - false + true end - # Create the s3 bucket, and also apply a CORS configuration - # Convox v3 update - They removed support for S3 resources, so we have to do - # in terraform now (which is actually pretty nice!) - def add_s3_bucket - require_config(%i[s3_bucket_name]) + # The app's environment variables, read with `convox env`. + def convox_env_vars + require_config(%i[convox_app_name]) + result = shell.capture(convox_argv('env', '--app', config.fetch(:convox_app_name)), env: convox_env) + unless result.success? + raise ConvoxInstaller::StepFailed.new("convox env failed: #{result.stderr.strip}", + next_step: 'Check that the app exists (convox apps).') + end - unless config.key? :s3_bucket_cors_rule - logger.debug 'No CORS rule provided in config: s3_bucket_cors_rule (optional)' - return + result.stdout.lines.filter_map do |line| + key, value = line.chomp.split('=', 2) + [key, value.to_s] unless key.to_s.strip.empty? + end.to_h + end + + # Sets environment variables that differ from the app's current ones, and returns the + # names it changed. Values go to `convox env set` on stdin, not on the command line. + def set_convox_env!(values = {}, promote: false, step_name: 'convox_env', **more_values) + require_config(%i[convox_app_name]) + # Ruby 3 turns `set_convox_env!('KEY' => 'value')` into keywords; accept both forms. + values = values.merge(more_values).to_h { |k, v| [k.to_s, v.to_s] } + values.each { |key, value| context.masker.add(value) if ConvoxInstaller::Masker.secret_key?(key) } + changed = [] + + runner.step(step_name, 'Set the app environment variables') do |step| + plan_unless_rack_installed(step, 'update') + current = convox_env_vars + changed = values.keys.reject { |key| current[key] == values[key] }.sort + step.info(keys: changed) + step.skip!('the environment is already up to date') if changed.empty? + step.plan!(action: 'update', state: 'outdated') + + logger.info "Setting environment variables: #{changed.join(', ')}" + multiline, simple = changed.partition { |key| values[key].include?("\n") } + argv = convox_argv('env', 'set', '--app', config.fetch(:convox_app_name)) + argv << '--promote' if promote + argv += multiline.map { |key| "#{key}=#{values[key]}" } + run!(argv, env: convox_env, stdin_data: simple.map { |key| "#{key}=#{values[key]}\n" }.join) end + changed + end - write_terraform_template('s3_bucket') + # The app's processes, from the rack API. + def convox_processes + require_config(%i[convox_app_name]) + convox_api_get("/apps/#{config.fetch(:convox_app_name)}/processes") end - def add_rds_database - require_config(%i[database_username database_password]) - write_terraform_template('rds') + def convox_api_get(path) + result = shell.capture(convox_argv('api', 'get', path), env: convox_env) + unless result.success? + raise ConvoxInstaller::StepFailed.new( + "convox api get #{path} failed: #{result.stderr.strip}", + next_step: "Check the rack with `convox rack --rack #{config.fetch(:stack_name)}`." + ) + end + + JSON.parse(result.stdout) end - def add_elasticache_cluster - write_terraform_template('elasticache') + def default_service_domain_name + require_config(%i[convox_app_name]) + + app_name = config.fetch(:convox_app_name) + default_service = config[:default_service] || 'web' + + convox_api_url = terraform_outputs.dig('api', 'value') + not_available!('the rack API endpoint (the rack is not installed yet)') if convox_api_url.to_s.empty? + + host = begin + URI.parse(convox_api_url).host + rescue URI::InvalidURIError + nil + end + host ||= convox_api_url.split('@').last.split('/').first + convox_router_host = host.sub(/\Aapi\./, '') + + [default_service, app_name, convox_router_host].join('.').downcase + end + + def run_convox_command!(cmd, env = {}, rack_arg: true) + argv = convox_command_argv(cmd, rack_arg) + return report_would_run(argv) if context.dry_run? + + run!(argv, env: convox_env.merge(env)) + true + end + + # Runs a convox command like run_convox_command! and returns its stdout (for `convox build --id` + # and other commands whose output the script needs). Its stderr is shown only when it fails. + # In plan and status it reports the command and returns nil. + def capture_convox_command!(cmd, env = {}, rack_arg: true) + argv = convox_command_argv(cmd, rack_arg) + return report_would_run(argv) if context.dry_run? + + result = shell.capture(argv, env: convox_env.merge(env)) + return result.stdout if result.success? + + raise ConvoxInstaller::StepFailed.new( + "Error running: #{shell.display(argv)} (exit status #{result.exit_code}): " \ + "#{context.masker.mask(result.stderr.strip)}", + next_step: 'Fix the problem, then run the same command again.' + ) + end + + # ---- Terraform resources --------------------------------------------------------- + + def add_s3_bucket + require_config(%i[stack_name s3_bucket_name]) + write_terraform_template( + 's3_bucket', + step_name: 'terraform_s3_bucket', + description: 'Write the S3 bucket Terraform config', + resources: %w[aws_s3_bucket.docs_s3_bucket aws_iam_access_key.docspring_user_access_key] + ) { s3_template_vars } end - def write_terraform_template(name) - template_path = File.join(__dir__, "../../terraform/#{name}.tf.erb") - unless File.exist?(template_path) - raise "Could not find terraform template at: #{template_path}" + def add_rds_database + require_config(%i[stack_name random_id]) + generate_setting(:database_password) { SecureRandom.hex(16) } + write_terraform_template( + 'rds', + step_name: 'terraform_rds_database', + description: 'Write the RDS Postgres Terraform config', + resources: %w[aws_db_instance.rds_database] + ) { rds_template_vars } + end + + def add_elasticache_cluster + require_config(%i[stack_name random_id]) + if elasticache_legacy? + write_terraform_template( + 'elasticache_legacy', + file_name: 'elasticache', + step_name: 'terraform_elasticache', + description: 'Write the ElastiCache Terraform config (3.x cluster)', + resources: %w[aws_elasticache_cluster.elasticache_cluster] + ) { elasticache_legacy_template_vars } + else + generate_setting(:elasticache_auth_token) { SecureRandom.hex(32) } + write_terraform_template( + 'elasticache', + step_name: 'terraform_elasticache', + description: 'Write the ElastiCache Redis Terraform config', + resources: %w[aws_elasticache_replication_group.redis] + ) { elasticache_template_vars } end + end - template = ERB.new(File.read(template_path)) - template_output = template.result(binding) + # Writes .tf (and the shared convox_installer.tf) into the rack's Terraform + # directory. apply_terraform_update! applies them. + def write_terraform_template(name, file_name: name, step_name: "terraform_#{name}", + description: "Write the #{name} Terraform config", resources: [], &vars_block) + template_path = File.join(TEMPLATE_DIR, "#{name}.tf.erb") + raise "Could not find terraform template at: #{template_path}" unless File.exist?(template_path) + + runner.step(step_name, description) do |step| + plan_unless_rack_installed(step, 'create') + unless File.directory?(rack_dir) + raise ConvoxInstaller::PreconditionFailed.new( + "Could not find the rack's Terraform directory at #{rack_dir}", + next_step: 'Run install_convox first.' + ) + end - tf_file_path = File.join(rack_dir, "#{name}.tf") - logger.debug "Writing terraform config to #{tf_file_path}..." - File.open(tf_file_path, 'w') { |f| f.puts template_output } + vars = vars_block ? vars_block.call : {} + files = { + 'convox_installer.tf' => render_template('convox_installer', common_template_vars), + "#{file_name}.tf" => render_template(name, vars) + } + changed = files.reject do |file, content| + path = File.join(rack_dir, file) + File.exist?(path) && File.read(path) == content + end + states = resources.to_h { |address| [address, terraform_resource_exists?(address) ? 'present' : 'missing'] } + step.info(resources: states) if states.any? + @terraform_pending = true if changed.any? || states.value?('missing') + step.skip!('the Terraform config is up to date') if changed.empty? + + main_file = File.join(rack_dir, "#{file_name}.tf") + exists = File.exist?(main_file) + step.plan!(action: exists ? 'update' : 'create', state: exists ? 'outdated' : 'missing', + files: changed.keys) + changed.each do |file, content| + path = File.join(rack_dir, file) + logger.debug "Writing terraform config to #{path}..." + File.write(path, content, perm: 0o600) + end + end end def apply_terraform_update! - logger.info 'Applying terraform update...' - command = if ENV['DEBUG_TERRAFORM'] - 'terraform plan' - else - 'terraform apply -auto-approve' - end - logger.debug "+ #{command}" - - env = { - 'AWS_ACCESS_KEY_ID' => config.fetch(:aws_access_key_id), - 'AWS_SECRET_ACCESS_KEY' => config.fetch(:aws_secret_access_key) - } - Dir.chdir(rack_dir) do - system env, command - raise 'terraform command failed!' unless $CHILD_STATUS.success? + runner.step('terraform_apply', 'Apply the Terraform changes') do |step| + plan_unless_rack_installed(step, 'apply') + if context.dry_run? + step.plan!(action: 'apply', state: 'outdated') if @terraform_pending + step.skip!('the Terraform config and resources are in place (install also checks for drift)') + end + check_duplicate_providers! + + terraform = terraform_binary + Dir.mktmpdir('convox-installer-') do |dir| + plan_file = File.join(dir, 'convox-installer.tfplan') + logger.info 'Applying terraform update...' + result = shell.stream([terraform, 'plan', '-input=false', '-detailed-exitcode', "-out=#{plan_file}", + *color_flags], env: terraform_env, chdir: rack_dir) + case result.exit_code + when 0 then step.skip!('Terraform reports no changes') + when 2 + if ENV['DEBUG_TERRAFORM'] + step.info(note: 'DEBUG_TERRAFORM is set, so the plan was not applied') + else + run!([terraform, 'apply', '-input=false', *color_flags, plan_file], env: terraform_env, chdir: rack_dir, + next_step: terraform_next_step) + end + else + raise ConvoxInstaller::StepFailed.new('terraform plan failed', next_step: terraform_next_step) + end + end + reset_terraform_cache! end end + # The rack's Terraform state (`terraform state pull`), or {} when there is none. def terraform_state - tf_state_file = File.join(rack_dir, 'terraform.tfstate') - JSON.parse(File.read(tf_state_file)) + @terraform_state ||= if File.directory?(rack_dir) + result = shell.capture([terraform_binary, 'state', 'pull'], env: terraform_env, + chdir: rack_dir) + result.success? && !result.stdout.strip.empty? ? JSON.parse(result.stdout) : {} + else + {} + end + end + + # The rack's Terraform outputs (`terraform output -json`), or {}. + def terraform_outputs + @terraform_outputs ||= if File.directory?(rack_dir) + result = shell.capture([terraform_binary, 'output', '-json'], env: terraform_env, + chdir: rack_dir) + result.success? && !result.stdout.strip.empty? ? JSON.parse(result.stdout) : {} + else + {} + end end def terraform_resource(resource_type, resource_name) - resource = terraform_state['resources'].find do |resource| - resource['type'] == resource_type && resource['name'] == resource_name - end + resource = find_terraform_resource(resource_type, resource_name) return resource if resource - raise "Could not find #{resource_type} resource named #{resource_name} in terraform state!" + not_available!("#{resource_type}.#{resource_name} in the Terraform state") + end + + def terraform_resource_exists?(address) + type, name = address.split('.', 2) + !find_terraform_resource(type, name).nil? end def s3_bucket_details require_config(%i[s3_bucket_name]) - s3_bucket = terraform_resource('aws_s3_bucket', 'docs_s3_bucket') - bucket_attributes = s3_bucket['instances'][0]['attributes'] - access_key = terraform_resource('aws_iam_access_key', 'docspring_user_access_key') - key_attributes = access_key['instances'][0]['attributes'] + bucket_attributes = resource_attributes!('aws_s3_bucket', 'docs_s3_bucket') + key_attributes = resource_attributes!('aws_iam_access_key', 'docspring_user_access_key') + context.masker.add(key_attributes['secret']) { access_key_id: key_attributes['id'], @@ -345,95 +616,435 @@ def s3_bucket_details end def rds_details - require_config(%i[database_username database_password]) + attributes = resource_attributes!('aws_db_instance', 'rds_database') + context.masker.add(attributes['password']) - database = terraform_resource('aws_db_instance', 'rds_database') - database_attributes = database['instances'][0]['attributes'] - - username = database_attributes['username'] - password = database_attributes['password'] - endpoint = database_attributes['endpoint'] - postgres_url = "postgres://#{username}:#{password}@#{endpoint}/app" + username = attributes['username'] + password = attributes['password'] + endpoint = attributes['endpoint'] + # 3.x URLs name the "app" database (the app creates it), not the instance's db_name. { - postgres_url: postgres_url + postgres_url: "postgres://#{url_encode(username)}:#{url_encode(password)}@#{endpoint}/app", + host: attributes['address'], + port: attributes['port'], + username: username } end def elasticache_details - require_config(%i[s3_bucket_name]) + if (group = resource_attributes('aws_elasticache_replication_group', 'redis')) + token = group['auth_token'].to_s.empty? ? config[:elasticache_auth_token] : group['auth_token'] + context.masker.add(token) + scheme = group['transit_encryption_enabled'] ? 'rediss' : 'redis' + auth = token.to_s.empty? ? '' : ":#{url_encode(token)}@" + host = group['primary_endpoint_address'] + port = group['port'] + else + cluster = resource_attributes!('aws_elasticache_cluster', 'elasticache_cluster') + node = cluster['cache_nodes'][0] + scheme = 'redis' + auth = '' + host = node['address'] + port = node['port'] + end + { redis_url: "#{scheme}://#{auth}#{host}:#{port}/0", host: host, port: port } + end + + def terraform_binary + context.terraform_binary ||= begin + preferred = config[:terraform_binary] + found = preferred ? shell.which(preferred.to_s) : shell.which('terraform') || shell.which('tofu') + found || preferred || 'terraform' + end + end + + # Environment for convox commands: AWS credentials and region, and a PATH where + # `terraform` runs OpenTofu when terraform_binary is tofu (the Convox CLI always runs + # `terraform`). + def convox_env + aws_session.env.merge(terraform_shim_env) + end + + def terraform_env + aws_session.env.merge( + 'AWS_STS_REGIONAL_ENDPOINTS' => 'regional', + 'TF_IN_AUTOMATION' => '1', + 'TF_INPUT' => '0' + ) + end + + private + + def runner = context.runner + def shell = context.shell + + def pause(seconds) + sleep(seconds) + end + + def convox_argv(*args) + ['convox', *args, '--rack', config.fetch(:stack_name)] + end + + def convox_command_argv(cmd, rack_arg) + argv = cmd.is_a?(Array) ? cmd.map(&:to_s) : Shellwords.split(cmd) + argv.unshift('convox') unless argv.first == 'convox' + # Always include the rack as an argument, so that `convox switch` elsewhere can't change + # which rack a command runs on. + argv += ['--rack', config.fetch(:stack_name)] if rack_arg + argv + end + + def report_would_run(argv) + logger.info "Would run: #{shell.display(argv)}" + context.reporter.event('would_run', command: shell.display(argv)) + nil + end + + def run!(argv, env: {}, chdir: nil, stdin_data: nil, next_step: nil) + result = shell.stream(argv, env: env, chdir: chdir, stdin_data: stdin_data) + return result if result.success? + + raise ConvoxInstaller::StepFailed.new( + "Error running: #{shell.display(argv)} (exit status #{result.exit_code})", + next_step: next_step || 'See the output above, fix the problem, then run the same command again.' + ) + end + + def plan_unless_rack_installed(step, action) + return unless context.dry_run? + return if rack_install_state == :installed + + step.plan!(action: action, state: 'unknown', reason: 'the rack is not installed yet') + end + + def rack_install_command + argv = %w[convox rack install] + argv += ['--version', config[:convox_rack_version].to_s] if present?(config[:convox_rack_version]) + argv += ['aws', config.fetch(:stack_name), + "node_type=#{config.fetch(:instance_type)}", + "region=#{config.fetch(:aws_region)}"] + # proxy_protocol=true by default, so the app sees client IPs. + argv << "proxy_protocol=#{bool_setting(:convox_proxy_protocol, true)}" + zones = config[:availability_zones] + zones = US_EAST_1_ZONES if !present?(zones) && config.fetch(:aws_region) == 'us-east-1' + argv << "availability_zones=#{zones}" if present?(zones) + argv + extra_rack_params + end + + def extra_rack_params + params = config[:convox_rack_params] + case params + when nil, '' then [] + when Hash then params.map { |k, val| "#{k}=#{val}" } + when Array then params.map(&:to_s) + else Shellwords.split(params.to_s) + end + end + + def resume_rack_install + terraform = terraform_binary + unless File.directory?(File.join(rack_dir, '.terraform')) + run!([terraform, 'init', '-input=false', '-upgrade', *color_flags], env: terraform_env, chdir: rack_dir) + end + run!([terraform, 'apply', '-auto-approve', '-input=false', *color_flags], env: terraform_env, chdir: rack_dir, + next_step: terraform_next_step) + end + + def terraform_next_step + "Fix the problem shown above, then run the same command again. To look at the plan yourself: cd #{rack_dir} " \ + "&& #{File.basename(terraform_binary)} plan" + end + + def color_flags + context.json? ? ['-no-color'] : [] + end + + def current_rack_name + return unless File.exist?(current_file) + + JSON.parse(File.read(current_file))['name'] + rescue JSON::ParserError + nil + end + + def terraform_shim_env + binary = terraform_binary + return {} if File.basename(binary) == 'terraform' + + @terraform_shim_dir ||= begin + dir = Dir.mktmpdir('convox-installer-tofu-') + File.symlink(binary, File.join(dir, 'terraform')) + at_exit { FileUtils.rm_rf(dir) } + dir + end + { 'PATH' => [@terraform_shim_dir, ENV.fetch('PATH', '')].join(File::PATH_SEPARATOR) } + end + + def reset_terraform_cache! + @terraform_state = nil + @terraform_outputs = nil + @terraform_pending = false + end + + def find_terraform_resource(resource_type, resource_name) + Array(terraform_state['resources']).find do |resource| + resource['module'].nil? && resource['mode'] != 'data' && + resource['type'] == resource_type && resource['name'] == resource_name + end + end + + def resource_attributes(resource_type, resource_name) + find_terraform_resource(resource_type, resource_name)&.dig('instances', 0, 'attributes') + end + + def resource_attributes!(resource_type, resource_name) + terraform_resource(resource_type, resource_name).dig('instances', 0, 'attributes') + end + + def not_available!(what) + message = "#{what} is not available yet." + raise ConvoxInstaller::NotYetAvailable, message if context.dry_run? + + raise ConvoxInstaller::PreconditionFailed.new( + "Could not find #{what}.", + next_step: 'Call the step that creates it first (install_convox, then add_* and apply_terraform_update!).' + ) + end + + def check_duplicate_providers! + files = Dir.glob(File.join(rack_dir, '*.tf')).reject do |path| + %w[main.tf convox_installer.tf].include?(File.basename(path)) + end + legacy = files.select { |path| File.read(path).match?(/^\s*provider\s+"aws"/) } + return if legacy.empty? + + raise ConvoxInstaller::PreconditionFailed.new( + "#{legacy.map { |p| File.basename(p) }.join(', ')} in #{rack_dir} still configures the aws provider, " \ + 'which convox_installer.tf now does.', + next_step: 'Call add_s3_bucket before apply_terraform_update! so s3_bucket.tf is rewritten ' \ + '(or remove the provider block from that file).' + ) + end + + def render_template(name, vars) + TemplateContext.new(vars).render(File.read(File.join(TEMPLATE_DIR, "#{name}.tf.erb"))) + end + + def generate_setting(key) + return if present?(config[key]) - # Just ensure that the bucket exists in the state - cluster = terraform_resource('aws_elasticache_cluster', 'elasticache_cluster') - cluster_attributes = cluster['instances'][0]['attributes'] - cache_node = cluster_attributes['cache_nodes'][0] - redis_url = "redis://#{cache_node['address']}:#{cache_node['port']}/0" + config[key] = yield + context.masker.add(config[key]) + @on_config_change&.call(key, config[key]) + end + + def elasticache_legacy? + legacy = config[:elasticache_legacy_cluster] + return ConvoxInstaller::Settings.truthy?(legacy) if present?(legacy) + + !find_terraform_resource('aws_elasticache_cluster', 'elasticache_cluster').nil? + end + + def common_template_vars + { region: config.fetch(:aws_region) } + end + + def name_prefix + "#{config.fetch(:stack_name)}-" + end + def s3_template_vars + bucket_name = "#{name_prefix}#{config.fetch(:s3_bucket_name)}" + existing = resource_attributes('aws_s3_bucket', 'docs_s3_bucket') + new_bucket = existing.nil? + versioning = setting(:s3_bucket_versioning, existing_versioning_status(existing)) + versioning = versioning.to_s.capitalize + unless %w[Enabled Suspended Disabled].include?(versioning) + raise ConvoxInstaller::MissingInput.new('s3_bucket_versioning must be Enabled, Suspended or Disabled.', + invalid: { s3_bucket_versioning: 'is not valid' }) + end + + lifecycle_days = Integer(setting(:s3_bucket_noncurrent_version_expiration_days, 30)) { - redis_url: redis_url + bucket_name: bucket_name, + iam_user_name: bucket_name, + cors_rules: cors_rules_hcl(config[:s3_bucket_cors_rule]), + versioning: versioning, + # Settings that could change how an existing bucket behaves for the app (ACLs, + # lifecycle rules made outside Terraform) are only added to new buckets, or when + # set explicitly or already managed. + ownership_controls: new_bucket || managed?('aws_s3_bucket_ownership_controls', 'docs_s3_bucket'), + lifecycle: versioning == 'Enabled' && lifecycle_days.positive? && + (new_bucket || present?(config[:s3_bucket_noncurrent_version_expiration_days]) || + managed?('aws_s3_bucket_lifecycle_configuration', 'docs_s3_bucket')), + noncurrent_days: lifecycle_days } end - def add_docker_registry! - require_config(%i[docker_registry_url docker_registry_username docker_registry_password]) + def existing_versioning_status(bucket) + return 'Enabled' if bucket.nil? - registry_url = config.fetch(:docker_registry_url) + managed = resource_attributes('aws_s3_bucket_versioning', 'docs_s3_bucket') + return managed.dig('versioning_configuration', 0, 'status') if managed + + bucket.dig('versioning', 0, 'enabled') ? 'Enabled' : 'Disabled' + end - logger.debug 'Looking up existing Docker registries...' - registries_response = `convox api get /registries --rack #{config.fetch(:stack_name)}` - unless $CHILD_STATUS.success? - raise 'Something went wrong while fetching the list of registries!' + def managed?(type, name) + !find_terraform_resource(type, name).nil? + end + + def cors_rules_hcl(value) + case value + when nil then nil + when String then value.strip.empty? ? nil : indent_hcl(value) + when Hash then cors_rules_hcl([value]) + when Array then value.map { |rule| cors_rule_block(rule.transform_keys(&:to_s)) }.join("\n") + else raise ConvoxInstaller::MissingInput.new('s3_bucket_cors_rule must be a cors_rule block or a list of rules.', + invalid: { s3_bucket_cors_rule: 'is not valid' }) end + end + + # Re-indents a cors_rule block written in the script, so it sits two spaces in. + def indent_hcl(text) + lines = text.lines.map(&:rstrip).drop_while(&:empty?).reverse.drop_while(&:empty?).reverse + indent = lines.reject(&:empty?).map { |line| line[/\A */].length }.min || 0 + lines.map { |line| line.empty? ? '' : " #{line[indent..]}" }.join("\n") + end - registries = JSON.parse(registries_response) + def cors_rule_block(rule) + hcl = TemplateContext.new({}) + lines = [' cors_rule {'] + %w[allowed_headers allowed_methods allowed_origins expose_headers].each do |key| + next unless rule.key?(key) - if registries.any? { |r| r['server'] == registry_url } - logger.debug "=> Docker Registry already exists: #{registry_url}" - return true + lines << " #{key} = [#{Array(rule[key]).map { |v| hcl.hcl_string(v) }.join(', ')}]" end + lines << " max_age_seconds = #{Integer(rule['max_age_seconds'])}" if rule.key?('max_age_seconds') + lines << " id = #{hcl.hcl_string(rule['id'])}" if rule.key?('id') + lines << ' }' + lines.join("\n") + end - logger.info "Adding Docker Registry: #{registry_url}..." - logger.info '=> Documentation: ' \ - 'https://docs.convox.com/configuration/private-registries/' + def rds_template_vars + identifier = "#{name_prefix}rds-#{config.fetch(:random_id)}" + existing = resource_attributes('aws_db_instance', 'rds_database') + storage_encrypted = bool_setting(:database_storage_encrypted, existing ? existing['storage_encrypted'] : true) + if existing && storage_encrypted != existing['storage_encrypted'] + raise ConvoxInstaller::PreconditionFailed.new( + "database_storage_encrypted=#{storage_encrypted} would replace the existing database #{identifier}.", + next_step: 'Remove database_storage_encrypted from the settings. To encrypt an existing database, ' \ + 'restore an encrypted copy of a snapshot by hand.' + ) + end - `convox registries add "#{registry_url}" \ - "#{config.fetch(:docker_registry_username)}" \ - "#{config.fetch(:docker_registry_password)}" \ - --rack #{config.fetch(:stack_name)}` - return if $CHILD_STATUS.success? + { + identifier: identifier, + db_name: "#{config.fetch(:stack_name).tr('-', '_')}_database", + engine: setting(:database_engine, existing&.fetch('engine', nil) || 'postgres'), + engine_version: setting(:database_engine_version) do + existing ? existing_engine_version(identifier, existing) : '17' + end, + instance_class: setting(:database_instance_class, existing&.fetch('instance_class', nil) || 'db.t3.small'), + allocated_storage: Integer(setting(:database_allocated_storage, + existing&.fetch('allocated_storage', nil) || 30)), + storage_type: setting(:database_storage_type, existing ? existing['storage_type'] || 'gp2' : 'gp3'), + storage_encrypted: storage_encrypted, + multi_az: bool_setting(:database_multi_az, existing ? existing.fetch('multi_az', true) : true), + backup_retention_period: Integer(setting(:database_backup_retention_period, + existing&.fetch('backup_retention_period', nil) || 7)), + deletion_protection: bool_setting(:database_deletion_protection, true), + allow_major_version_upgrade: bool_setting(:database_allow_major_version_upgrade, false), + username: setting(:database_username, existing&.fetch('username', nil) || 'app'), + password: config.fetch(:database_password), + final_snapshot_identifier: "#{identifier}-final-snapshot", + subnet_group_name: "#{name_prefix}rds-subnetgroup-#{config.fetch(:random_id)}", + security_group_name: "#{name_prefix}rds-database-securitygroup-#{config.fetch(:random_id)}" + } + end - raise "Something went wrong while adding the #{registry_url} registry!" + # AWS upgrades minor versions automatically, and the AWS provider then records the + # running version, so the config must name it or Terraform plans a downgrade. + def existing_engine_version(identifier, existing) + result = shell.capture(['aws', 'rds', 'describe-db-instances', '--db-instance-identifier', identifier, + '--query', 'DBInstances[0].EngineVersion', '--output', 'text'], env: aws_session.env) + live = result.stdout.strip + return live if result.success? && live.match?(/\A\d+(\.\d+)*\z/) + + existing['engine_version_actual'].to_s.empty? ? existing['engine_version'] : existing['engine_version_actual'] end - def default_service_domain_name - require_config(%i[convox_app_name]) + def elasticache_template_vars + random_id = config.fetch(:random_id) + existing = resource_attributes('aws_elasticache_replication_group', 'redis') + engine = setting(:elasticache_engine, existing&.fetch('engine', nil) || 'redis') + nodes = Integer(setting(:elasticache_num_cache_nodes, existing&.fetch('num_cache_clusters', nil) || 1)) + # Replication group IDs are at most 40 characters. + stack = config.fetch(:stack_name)[0, 40 - "-redis-#{random_id}".length].sub(/-+\z/, '') + { + replication_group_id: "#{stack}-redis-#{random_id}", + description: "Redis for the #{config.fetch(:stack_name)} Convox rack (managed by convox_installer)", + engine: engine, + engine_version: setting(:elasticache_engine_version, + existing&.fetch('engine_version', nil) || (engine == 'valkey' ? '8.0' : '7.1')), + node_type: setting(:elasticache_node_type, existing&.fetch('node_type', nil) || 'cache.t3.medium'), + num_cache_clusters: nodes, + failover: nodes > 1, + port: Integer(setting(:elasticache_port, 6379)), + auth_token: config.fetch(:elasticache_auth_token), + subnet_group_name: "#{name_prefix}elasticache-cluster-subnetgroup-#{random_id}", + security_group_name: "#{name_prefix}elasticache-securitygroup-#{random_id}" + } + end - app_name = config.fetch(:convox_app_name) - default_service = config[:default_service] || 'web' + def elasticache_legacy_template_vars + random_id = config.fetch(:random_id) + existing = resource_attributes('aws_elasticache_cluster', 'elasticache_cluster') + { + cluster_id: "#{name_prefix}elasticache-#{random_id}", + engine: setting(:elasticache_engine, existing&.fetch('engine', nil) || 'redis'), + engine_version: setting(:elasticache_engine_version, existing&.fetch('engine_version', nil) || '7.1'), + node_type: setting(:elasticache_node_type, existing&.fetch('node_type', nil) || 'cache.t3.medium'), + num_cache_nodes: Integer(setting(:elasticache_num_cache_nodes, existing&.fetch('num_cache_nodes', nil) || 1)), + port: Integer(setting(:elasticache_port, existing&.fetch('port', nil) || 6379)), + subnet_group_name: "#{name_prefix}elasticache-cluster-subnetgroup-#{random_id}", + security_group_name: "#{name_prefix}elasticache-securitygroup-#{random_id}" + } + end - convox_api_url = terraform_state['outputs']['api']['value'] - convox_router_host = convox_api_url.split('@').last.sub(/^api\./, '') + def setting(key, default = nil) + value = config[key] + return value if present?(value) - [default_service, app_name, convox_router_host].join('.').downcase + block_given? ? yield : default end - def run_convox_command!(cmd, env = {}, rack_arg: true) - # Always include the rack as an argument, to - # make sure that 'convox switch' doesn't affect any commands - command = "convox #{cmd}" - if rack_arg - command = "#{command} --rack #{config.fetch(:stack_name)}" - end - logger.debug "+ #{command}" - system env, command - raise "Error running: #{command}" unless $CHILD_STATUS.success? + def bool_setting(key, default) + value = config[key] + return ConvoxInstaller::Settings.truthy?(value) if present?(value) + + default ? true : false end - private + def url_encode(value) + value.to_s.gsub(/[^A-Za-z0-9\-._~]/) { |c| c.bytes.map { |b| format('%%%02X', b) }.join } + end + + def present?(value) + !value.nil? && !value.to_s.strip.empty? + end def require_config(required_keys) - required_keys.each do |k| - raise "#{k} is missing from the config!" unless config[k] - end + missing = required_keys.reject { |k| present?(config[k]) } + return if missing.empty? + + raise ConvoxInstaller::MissingInput.new( + "#{missing.join(', ')} #{missing.one? ? 'is' : 'are'} missing from the config!", + missing: missing, + next_step: "Add #{missing.map { |k| ConvoxInstaller::Settings.flag_name(k) }.join(', ')} " \ + '(or the environment variables or config file entries), or add prompts for them.' + ) end end end diff --git a/lib/convox_installer.rb b/lib/convox_installer.rb index b23af2a..5d19b14 100644 --- a/lib/convox_installer.rb +++ b/lib/convox_installer.rb @@ -1,32 +1,175 @@ # frozen_string_literal: true -require 'active_support' -require 'active_support/core_ext' +require 'English' +require 'json' +require 'logger' +require 'convox_installer/version' +require 'convox_installer/errors' +require 'convox_installer/masker' +require 'convox_installer/platform' +require 'convox_installer/settings' +require 'convox_installer/options' +require 'convox_installer/reporter' +require 'convox_installer/shell' +require 'convox_installer/runner' +require 'convox_installer/context' require 'convox_installer/config' +require 'convox_installer/aws_session' require 'convox_installer/requirements' require 'convox' +# The DSL for install scripts: +# +# require 'convox_installer' +# include ConvoxInstaller +# +# @prompts = ConvoxInstaller::Config::DEFAULT_PROMPTS + [...] +# ensure_requirements! +# config = prompt_for_config +# install_convox +# ... +# +# The script's command line is parsed the first time a DSL method runs (see +# ConvoxInstaller::Options). When the script ends, the installer prints the final result +# (a JSON event with --json) and exits with a code that says how it went. module ConvoxInstaller + class << self + # Set when a script's run has started, so the result is printed once at exit. + attr_accessor :exit_handler_installed + + # Called once per process. In --json mode, stdout carries only events: anything else + # the script or a subprocess prints to stdout goes to stderr. + def start_run(context) + return if exit_handler_installed + + self.exit_handler_installed = true + at_exit do + code = context.runner.finish($ERROR_INFO) + $stdout.flush + $stderr.flush + # Known errors were already explained, so skip Ruby's backtrace (exit! skips it). + # Unexpected errors keep their backtrace. + exit!(code) if $ERROR_INFO.is_a?(Error) || $ERROR_INFO.is_a?(Interrupt) + exit(code) + end + end + + def json_streams + event_io = $stdout.dup + event_io.sync = true + $stdout.reopen($stderr) + event_io + end + end + + def installer_context + @installer_context ||= begin + argv = @argv || ARGV + prompts = @prompts || Config::DEFAULT_PROMPTS + titles = prompts.select { |p| p[:key] }.to_h { |p| [p[:key].to_sym, p[:title] || p[:key].to_s] } + options = Options.parse(argv, settings: titles) + if options.help? || options.version? + puts(options.version? ? VERSION : options.help_text) + $stdout.flush + exit!(0) + end + event_io = options.json? ? ConvoxInstaller.json_streams : $stdout + context = Context.new(options: options, log_level: @log_level, event_io: event_io) + context.reporter.event('start', version: VERSION, command: options.command.to_s, dry_run: options.dry_run?) + ConvoxInstaller.start_run(context) + context + rescue UsageError => e + if argv.include?('--json') + error = { type: e.type, message: e.message, next_step: e.next_step } + puts JSON.generate(event: 'result', status: 'failed', exit_code: e.exit_code, error: error) + end + warn "#{e.message}\n#{e.next_step}" + $stdout.flush + exit!(e.exit_code) + end + end + def client - @client ||= Convox::Client.new(log_level: @log_level, config: config.config) + @client ||= Convox::Client.new( + context: installer_context, + config: config.config, + aws_session: aws_session, + on_config_change: lambda { |key, value| + config.set(key, value, :generated) + config.save_config_to_file + } + ) end def config - options = { log_level: @log_level } - options[:prompts] = @prompts if @prompts - @config ||= Config.new(options) + @config ||= Config.new(context: installer_context, prompts: @prompts || Config::DEFAULT_PROMPTS) end def requirements - @requirements ||= Requirements.new(log_level: @log_level) + @requirements ||= Requirements.new(context: installer_context, terraform_binary: config[:terraform_binary]) + end + + def aws_session + @aws_session ||= AwsSession.new(context: installer_context, config: config.config) end def ensure_requirements! - requirements.ensure_requirements! + installer_context.runner.step('requirements', 'Check for convox, aws and terraform') do + requirements.ensure_requirements! + end + true end + # Loads the settings, prompts for missing ones (or fails with the list in non-interactive + # runs), checks the AWS credentials, shows a summary and asks to start. Returns the + # settings hash. def prompt_for_config - config.prompt_for_config + installer_context.runner.step('config', 'Load the settings') do |step| + config.prompt_for_config(confirm: !installer_context.dry_run?, summary: method(:aws_summary_lines)) + step.info(file: config.path) + end + # Remember the account, so a later run can't install into a different one by mistake. + config[:aws_account_id] = aws_session.identity[:account] unless config[:aws_account_id] + config.config + end + + # A custom step for your own script. In install the block runs unless `check` returns + # true. In plan and status the block doesn't run: the step is reported as done when + # `check` returns true and as pending otherwise. + # + # With plan_aware: true the block also runs in plan and status, and must call + # `s.plan!(action: '...')` before it changes anything (it can call `s.skip!` when there is + # nothing to do). The block gets that handle as its argument. + def step(name, description = nil, check: nil, plan_aware: false, &) + installer_context.runner.step(name, description, check: check, run_in_dry_run: plan_aware, &) + end + + # Adds a value to the final result (secrets are masked). + def result_output(key, value) + installer_context.runner.add_output(key, value) + end + + # :install, :plan or :status. + def installer_command + installer_context.command + end + + # True in plan and status, where nothing may change. + def dry_run? + installer_context.dry_run? + end + + # Environment for your own aws commands: the same credentials and region the installer uses. + def aws_env + aws_session.env + end + + def aws_identity + aws_session.identity + end + + def logger + installer_context.logger end %w[ @@ -42,17 +185,31 @@ def prompt_for_config add_elasticache_cluster apply_terraform_update! terraform_state + terraform_outputs s3_bucket_details elasticache_details rds_details add_docker_registry! default_service_domain_name run_convox_command! - logger + capture_convox_command! rack_already_installed? + rack_dir + convox_env_vars + set_convox_env! + convox_processes + convox_api_get ].each do |method| - define_method(method) do |*args| - client.send(method, *args) + define_method(method) do |*args, **kwargs| + client.send(method, *args, **kwargs) end end + + private + + def aws_summary_lines(_config) + aws_session.reset! + aws_session.verify_account!(config[:aws_account_id]) + aws_session.summary_lines + end end diff --git a/lib/convox_installer/aws_session.rb b/lib/convox_installer/aws_session.rb new file mode 100644 index 0000000..ec6344e --- /dev/null +++ b/lib/convox_installer/aws_session.rb @@ -0,0 +1,150 @@ +# frozen_string_literal: true + +require 'json' +require 'time' + +module ConvoxInstaller + # AWS credentials and identity. + # + # By default the installer uses the AWS CLI's credential chain: AWS_PROFILE (SSO, assumed + # roles, credential_process), environment variables, then instance or container roles. + # The Convox CLI insists on AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in its environment, + # so the installer resolves the chain with `aws configure export-credentials` and passes + # the resulting (usually temporary) credentials to every convox, terraform and aws command + # it runs. Explicit keys in the settings (the 3.x way) are still used when present. + class AwsSession + # Refresh exported credentials this long before they expire. + REFRESH_MARGIN = 10 * 60 + + attr_reader :context, :config + + def initialize(context:, config:) + @context = context + @config = config + end + + def region + config[:aws_region] + end + + def explicit_keys? + present?(config[:aws_access_key_id]) && present?(config[:aws_secret_access_key]) + end + + def credential_source + return 'access keys from the settings (aws_access_key_id)' if explicit_keys? + + profile = present?(config[:aws_profile]) ? "profile #{config[:aws_profile]}" : 'default chain' + "AWS CLI credential chain (#{profile})" + end + + # Forget the identity and exported credentials (after the settings change). + def reset! + @identity = nil + @exported = nil + @expires_at = nil + end + + # Environment for convox, terraform and aws commands. + def env + base_env.merge(credentials_env) + end + + def identity + @identity ||= begin + result = context.shell.capture(%w[aws sts get-caller-identity --output json], env: env) + unless result.success? + raise PreconditionFailed.new( + "AWS rejected the credentials (aws sts get-caller-identity failed): #{result.stderr.strip}", + next_step: credentials_next_step + ) + end + data = JSON.parse(result.stdout) + { account: data.fetch('Account'), arn: data.fetch('Arn'), user_id: data['UserId'] } + end + end + + def verify_account!(expected) + return if expected.nil? || expected.to_s.strip.empty? + return if identity[:account] == expected.to_s + + raise PreconditionFailed.new( + "These AWS credentials belong to account #{identity[:account]} (#{identity[:arn]}), " \ + "but this installation uses account #{expected} (aws_account_id).", + next_step: 'Switch to credentials for the right account (for example set AWS_PROFILE), ' \ + 'or change aws_account_id if you really mean to use another account.' + ) + end + + # Rows for the configuration summary. + def summary_lines + [ + ['AWS Account', identity[:account]], + ['AWS Principal', identity[:arn]], + ['AWS Credentials', credential_source] + ] + end + + private + + def base_env + env = {} + if present?(region) + env['AWS_REGION'] = region + env['AWS_DEFAULT_REGION'] = region + end + env['AWS_PROFILE'] = config[:aws_profile] if present?(config[:aws_profile]) + env + end + + def credentials_env + return explicit_env if explicit_keys? + + exported_env + end + + def explicit_env + { + 'AWS_ACCESS_KEY_ID' => config[:aws_access_key_id], + 'AWS_SECRET_ACCESS_KEY' => config[:aws_secret_access_key], + # nil unsets a session token left in the shell from other credentials. + 'AWS_SESSION_TOKEN' => present?(config[:aws_session_token]) ? config[:aws_session_token] : nil + } + end + + def exported_env + return @exported if @exported && !expiring? + + result = context.shell.capture(%w[aws configure export-credentials --format process], env: base_env) + unless result.success? + raise PreconditionFailed.new( + "No usable AWS credentials found: #{result.stderr.strip}", + next_step: credentials_next_step + ) + end + + data = JSON.parse(result.stdout) + @expires_at = data['Expiration'] ? Time.parse(data['Expiration']) : nil + context.masker.add(data['SecretAccessKey']).add(data['SessionToken']) + @exported = { + 'AWS_ACCESS_KEY_ID' => data.fetch('AccessKeyId'), + 'AWS_SECRET_ACCESS_KEY' => data.fetch('SecretAccessKey'), + 'AWS_SESSION_TOKEN' => data['SessionToken'] + } + end + + def expiring? + @expires_at && @expires_at - Time.now < REFRESH_MARGIN + end + + def credentials_next_step + profile = present?(config[:aws_profile]) ? " --profile #{config[:aws_profile]}" : '' + "Sign in with the AWS CLI (for example `aws sso login#{profile}` or `aws configure`), " \ + "check it with `aws sts get-caller-identity#{profile}`, then run the same command again." + end + + def present?(value) + !value.nil? && !value.to_s.strip.empty? + end + end +end diff --git a/lib/convox_installer/config.rb b/lib/convox_installer/config.rb index f38ec83..dd23308 100644 --- a/lib/convox_installer/config.rb +++ b/lib/convox_installer/config.rb @@ -6,10 +6,21 @@ require 'securerandom' module ConvoxInstaller + # The installer's settings. + # + # Values come from, highest precedence first: command-line flags (--set key=value or + # -- value), environment variables (CONVOX_INSTALLER_ or ), the config file + # (./.installer_config.json), then the prompts' `value:` and `default:`. Interactive runs + # prompt for anything still missing; non-interactive runs (--yes) fail with the list. + # + # Every value is saved to the config file (mode 0600) as soon as it is known, so a + # re-run reuses generated names and passwords and resumes where it stopped. class Config CONFIG_FILE = File.expand_path('./.installer_config.json').freeze - attr_accessor :logger, :config, :prompts, :highline + RACK_NAME = /\A[a-z][a-z0-9-]*\z/ + AWS_REGION = /\A[a-z]{2}(-[a-z]+)+-\d+\z/ + AWS_ACCOUNT_ID = /\A\d{12}\z/ DEFAULT_PROMPTS = [ { @@ -28,17 +39,6 @@ class Config title: 'EC2 Instance Type', default: 't3.medium' }, - { - section: 'Admin AWS Credentials' - }, - { - key: :aws_access_key_id, - title: 'AWS Access Key ID' - }, - { - key: :aws_secret_access_key, - title: 'AWS Secret Access Key' - }, # Short random ID used to ensure that resources are always unique { key: :random_id, @@ -47,152 +47,359 @@ class Config } ].freeze - def initialize(options = {}) - @logger = Logger.new($stdout) - logger.level = options[:log_level] || Logger::INFO + attr_accessor :logger, :config, :prompts, :highline + attr_reader :sources, :path, :context + def initialize(options = {}) + @context = options[:context] || Context.new(log_level: options[:log_level]) + @logger = context.logger self.prompts = options[:prompts] || DEFAULT_PROMPTS + @path = File.expand_path(options[:path] || context.options.config_path || CONFIG_FILE) + context.config_file = @path + @env = options[:env] || ENV + @assume_yes = options.fetch(:assume_yes, context.assume_yes?) + @interactive = options.fetch(:interactive) { !@assume_yes && $stdin.tty? } + self.highline = options[:highline] || HighLine.new + self.config = {} + @sources = {} load_config_from_file load_config_from_env - self.config = config.merge((options[:config] || {}).symbolize_keys) + merge_values(options[:config] || {}, :option) + merge_values(context.options.settings, :flag) + end - self.highline = options[:highline] || HighLine.new + def interactive? = @interactive + + def [](key) = config[key.to_sym] + + def fetch(...) = config.fetch(...) + + def []=(key, value) + set(key, value, :script) + save_config_to_file end def config_keys - prompts.map { |prompt| prompt[:key] }.compact.map(&:to_sym) + (prompts.filter_map { |prompt| prompt[:key]&.to_sym } + Settings::KNOWN.keys).uniq end - def prompt_for_config - loop do - prompts.each do |prompt| - if prompt[:section] - highline.say "\n#{prompt[:section]}" - highline.say "============================================\n\n" - end - next unless prompt[:key] + def prompt_for(key) + prompts.find { |p| p[:key]&.to_sym == key.to_sym } + end - ask_prompt(prompt) - end + def secret?(key) + prompt = prompt_for(key) + return prompt[:secret] if prompt&.key?(:secret) - show_config_summary + known = Settings::KNOWN[key.to_sym] + return known[:secret] if known&.key?(:secret) + Masker.secret_key?(key) + end + + # Fills in every setting, shows the summary and (when confirm is true) asks the person + # to confirm. `summary` returns extra summary lines, such as the AWS account in use. + def prompt_for_config(confirm: true, summary: nil) + loop do + collect_values + extra = summary ? Array(summary.call(config)) : [] + show_config_summary(extra) + report_config_event @completed_prompt = true + break unless confirm highline.say 'Please double check all of these configuration details.' + break if @assume_yes + + unless interactive? + raise MissingInput.new( + 'The installer needs your confirmation before it starts, but this run is not interactive.', + missing: ['confirmation'], + next_step: 'Check the settings above, then run the same command with --yes.' + ) + end - break if ENV['AUTOSTART_CONVOX_INSTALLATION'] - - agree = highline.agree( - 'Would you like to start the Convox installation?' \ - " (press 'n' to correct any settings)" + break if highline.agree( + 'Would you like to start the Convox installation? ' \ + "(press 'n' to correct any settings)" ) - break if agree highline.say "\n" end config + rescue EOFError + raise Cancelled.new( + 'The input ended before the installer got an answer.', + next_step: 'Run the script again in a terminal, or pass --yes with every setting for a non-interactive run.' + ) end - def show_config_summary + def show_config_summary(extra_lines = []) highline.say "\n============================================" highline.say ' SUMMARY' highline.say "============================================\n\n" - config_titles = prompts.map do |prompt| - prompt[:title] || prompt[:key] - end.compact - max = config_titles.map(&:length).max - + rows = extra_lines.dup prompts.each do |prompt| next if !prompt[:key] || prompt[:hidden] - value = config[prompt[:key]] - title = prompt[:title] || prompt[:key] - padded_key = "#{title}:".ljust(max + 3) - highline.say " #{padded_key} #{value}" + key = prompt[:key].to_sym + rows << [prompt[:title] || key.to_s, display_value(key)] end - highline.say "\nWe've saved your configuration to: #{CONFIG_FILE}" + max = rows.map { |title, _| title.length }.max || 0 + + rows.each do |title, value| + highline.say " #{"#{title}:".ljust(max + 3)} #{value}" + end + highline.say "\nWe've saved your configuration to: #{path}" highline.say 'If anything goes wrong during the installation, ' \ "you can restart the script to reload the config and continue.\n\n" end - def self.config_file_exists? - File.exist?(CONFIG_FILE) + # Settings a non-interactive run would still need. + def missing_keys + prompts.filter_map do |prompt| + key = prompt[:key]&.to_sym + next unless key + next if present?(config[key]) || prompt.key?(:value) || prompt.key?(:default) + + key + end + end + + # Sets a value (from the gem or the script) and saves the file. + def set(key, value, source = :script) + key = key.to_sym + config[key] = value + sources[key] = source + context.masker.add(value) if secret?(key) + value end - def self.read_config_file - File.read(CONFIG_FILE) + def save_config_to_file + FileUtils.mkdir_p(File.dirname(path)) + tmp = "#{path}.tmp-#{Process.pid}" + File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, 0o600) do |f| + f.puts(JSON.pretty_generate(convox_installer_version: VERSION, config: persisted_config)) + end + File.chmod(0o600, tmp) + File.rename(tmp, path) + end + + def self.config_file_exists?(path = CONFIG_FILE) + File.exist?(path) + end + + def self.read_config_file(path = CONFIG_FILE) + File.read(path) + end + + def validation_error(key, value) + key = key.to_sym + prompt = prompt_for(key) + validator = prompt && prompt[:validate] + case validator + when Regexp then return "must match #{validator.inspect}" unless value.to_s.match?(validator) + when Proc + result = validator.call(value) + return result if result.is_a?(String) + return 'is not valid' unless result + end + builtin_validation_error(key, value) end private + def builtin_validation_error(key, value) + case key + when :stack_name + return 'must be 26 characters or fewer' if value.to_s.length > 26 + + unless value.to_s.match?(RACK_NAME) + 'must start with a lowercase letter and contain only lowercase letters, numbers and hyphens' + end + when :aws_region + "doesn't look like an AWS region (e.g. us-east-1)" unless value.to_s.match?(AWS_REGION) + when :aws_account_id + 'must be a 12-digit AWS account ID' unless value.to_s.match?(AWS_ACCOUNT_ID) + end + end + + def collect_values + missing = [] + invalid = {} + prompts.each do |prompt| + if prompt[:section] && interactive? + highline.say "\n#{prompt[:section]}" + highline.say "============================================\n\n" + highline.say "#{prompt[:info]}\n\n" if prompt[:info] + end + next unless prompt[:key] + + if interactive? + ask_prompt(prompt) + else + fill_prompt(prompt, missing) + end + key = prompt[:key].to_sym + error = present?(config[key]) ? validation_error(key, config[key]) : nil + invalid[key] = error if error + end + raise_input_errors(missing, invalid) + end + + def raise_input_errors(missing, invalid) + return if missing.empty? && invalid.empty? + + parts = [] + parts << "Missing settings: #{missing.join(', ')}." if missing.any? + invalid.each { |key, error| parts << "#{key} #{error}." } + examples = (missing + invalid.keys).first(3).map do |key| + "#{Settings.flag_name(key)} VALUE (or #{env_names(key).first(2).last}=VALUE)" + end + raise MissingInput.new( + parts.join(' '), + missing: missing, + invalid: invalid, + next_step: "Set them with flags, environment variables or the config file (#{path}), " \ + "for example: #{examples.join(', ')}." + ) + end + + # Non-interactive: generated values and defaults are used; anything else must be given. + def fill_prompt(prompt, missing) + key = prompt[:key].to_sym + return if present?(config[key]) + + if prompt.key?(:value) + set(key, resolve(prompt[:value]), :generated) + elsif prompt.key?(:default) + set(key, resolve(prompt[:default]), :default) + else + missing << key + return + end + save_config_to_file + end + def ask_prompt(prompt) - key = prompt[:key] + key = prompt[:key].to_sym title = prompt[:title] || key - # If looping through the config again, ask for all - # the config with defaults. - if config[key] && !@completed_prompt + # The first time through, keep values we already have. After the person says "no" at + # the confirmation, ask again for everything, with the current values as defaults. + if present?(config[key]) && !@completed_prompt && !validation_error(key, config[key]) logger.debug "Found existing config for #{key} => #{config[key]}" return end # Used when we want to force a default value and not prompt the user. # (e.g. securely generated passwords) - if prompt[:value] - return if config[key] - - default = prompt[:value] - config[key] = if default.is_a?(Proc) - default.arity.zero? ? default.call : default.call(config) - else - default - end + if prompt.key?(:value) + return if present?(config[key]) + + set(key, resolve(prompt[:value]), :generated) save_config_to_file return end prompt_string = prompt[:prompt] || "Please enter your #{title}: " - - config[key] = highline.ask(prompt_string) do |q| - if @completed_prompt + answer = highline.ask(prompt_string) do |q| + if @completed_prompt && present?(config[key]) q.default = config[key] - elsif prompt[:default] - q.default = prompt[:default] + elsif prompt.key?(:default) + q.default = resolve(prompt[:default]) end - q.validate = /.+/ + q.echo = '*' if secret?(key) && terminal_input? + q.validate = ->(input) { present?(input) && !validation_error(key, input) } + q.responses[:not_valid] = "#{title} #{validation_error(key, '') || 'is required'}." end - + set(key, answer.to_s, :prompt) save_config_to_file end - def load_config_from_file - return unless Config.config_file_exists? + # Masked typing needs a real terminal. + def terminal_input? + io = highline.respond_to?(:input) ? highline.input : nil + io.respond_to?(:tty?) && io.tty? + end + + def resolve(value) + return value unless value.is_a?(Proc) + + value.arity.zero? ? value.call : value.call(config) + end - logger.debug "Loading saved config from #{CONFIG_FILE}..." + def display_value(key) + value = config[key] + return '' unless present?(value) + return Masker.display(value) if secret?(key) + + value.is_a?(String) ? value : JSON.generate(value) + end + + def report_config_event + visible = prompts.reject { |p| p[:hidden] || !p[:key] }.map { |p| p[:key].to_sym } + visible += Settings::KNOWN.keys.select { |k| present?(config[k]) && !prompt_for(k)&.dig(:hidden) } + settings = visible.uniq.to_h do |key| + value = config[key] + [key, secret?(key) && present?(value) ? Masker::MASK : value] + end + context.reporter.event('config', file: path, settings: settings, + sources: sources.slice(*visible).transform_values(&:to_s)) + end - loaded_config = JSON.parse(Config.read_config_file)['config'].symbolize_keys - self.config = config.merge(loaded_config) + def load_config_from_file + return unless Config.config_file_exists?(path) + + logger.debug "Loading saved config from #{path}..." + data = JSON.parse(Config.read_config_file(path)) + merge_values(data.fetch('config', {}), :file) + rescue JSON::ParserError => e + raise PreconditionFailed.new( + "The config file #{path} is not valid JSON: #{e.message}", + next_step: 'Fix or delete the file, then run the same command again.' + ) end def load_config_from_env config_keys.each do |key| - env_key = key.to_s.upcase - value = ENV[env_key] - next unless value.present? + name = env_names(key).find { |n| present?(@env[n]) } + next unless name - logger.debug "Found value for #{key} in env var: #{env_key} => #{value}" - config[key] = value + logger.debug "Found value for #{key} in env var: #{name}" + merge_values({ key => @env[name] }, :"env:#{name}") end end - def save_config_to_file - # FileUtils.mkdir_p File.expand_path("~/.convox") - File.open(CONFIG_FILE, 'w') do |f| - f.puts(JSON.pretty_generate(config: config)) + def merge_values(values, source) + values.each do |key, value| + next if value.nil? + + set(key, value, source) + end + end + + # AWS credentials passed in the environment or on the command line stay out of the + # file: they belong to the credential chain. + def persisted_config + config.reject do |key, _| + !Settings.persist?(key) && sources[key].to_s.start_with?('env:', 'flag') + end + end + + def env_names(key) + Settings.env_names(key, plain: !prompt_for(key).nil?) + end + + def present?(value) + case value + when nil then false + when String then !value.strip.empty? + when Hash, Array then !value.empty? + else true end end end diff --git a/lib/convox_installer/context.rb b/lib/convox_installer/context.rb new file mode 100644 index 0000000..9cd052a --- /dev/null +++ b/lib/convox_installer/context.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require 'logger' + +module ConvoxInstaller + # What one run of an install script shares: the parsed command line, logging and events, + # secret masking, the command runner and the step runner. + class Context + attr_reader :options, :reporter, :masker, :shell, :runner + attr_accessor :config_file, :terraform_binary + + def initialize(options: nil, log_level: nil, event_io: $stdout, human_io: nil, executor: nil) + @options = options || Options.new + @masker = Masker.new + @reporter = Reporter.new( + masker: @masker, + json: @options.json?, + event_io: event_io, + human_io: human_io, + log_level: @options.log_level || log_level || Logger::INFO + ) + @shell = Shell.new(reporter: @reporter, masker: @masker, executor: executor) + @runner = Runner.new(self) + end + + def logger = reporter.logger + def command = options.command + def dry_run? = options.dry_run? + def json? = options.json? + def assume_yes? = options.assume_yes? + end +end diff --git a/lib/convox_installer/errors.rb b/lib/convox_installer/errors.rb new file mode 100644 index 0000000..1acb843 --- /dev/null +++ b/lib/convox_installer/errors.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +module ConvoxInstaller + # Process exit codes. Agents and CI can branch on these. + module ExitCodes + SUCCESS = 0 + # An unexpected error (a bug in the gem or the install script). + ERROR = 1 + # A setting is missing or invalid, or the command line could not be parsed. + MISSING_INPUT = 2 + # Something outside the installer is not ready: a missing tool, an old version, + # no AWS credentials, the wrong AWS account. + PRECONDITION_FAILED = 3 + # A step started and failed (a convox or terraform command returned an error). + STEP_FAILED = 4 + # The input ended at a prompt (Ctrl-D, or stdin closed) before the person answered. + CANCELLED = 5 + # Interrupted with Ctrl-C (SIGINT). + INTERRUPTED = 130 + end + + class Error < StandardError + attr_reader :next_step + attr_accessor :step + + def initialize(message = nil, next_step: nil, step: nil) + super(message) + @next_step = next_step + @step = step + end + + def exit_code = ExitCodes::ERROR + def type = 'error' + def details = {} + end + + class MissingInput < Error + attr_reader :missing, :invalid + + def initialize(message = nil, missing: [], invalid: {}, next_step: nil, step: nil) + super(message, next_step: next_step, step: step) + @missing = missing.map(&:to_s) + @invalid = invalid.transform_keys(&:to_s) + end + + def exit_code = ExitCodes::MISSING_INPUT + def type = 'missing_input' + + def details + result = {} + result[:missing] = missing if missing.any? + result[:invalid] = invalid if invalid.any? + result + end + end + + class UsageError < MissingInput + def type = 'usage' + end + + class PreconditionFailed < Error + def exit_code = ExitCodes::PRECONDITION_FAILED + def type = 'precondition_failed' + end + + class StepFailed < Error + def exit_code = ExitCodes::STEP_FAILED + def type = 'step_failed' + end + + class Cancelled < Error + def exit_code = ExitCodes::CANCELLED + def type = 'cancelled' + end + + # Raised in `plan` and `status` when a later step needs something that doesn't exist yet + # (for example the database URL before the database is created). The run stops there and + # exits 0: everything after it is pending. + class NotYetAvailable < Error + def exit_code = ExitCodes::SUCCESS + def type = 'not_yet_available' + end +end diff --git a/lib/convox_installer/masker.rb b/lib/convox_installer/masker.rb new file mode 100644 index 0000000..cfb0968 --- /dev/null +++ b/lib/convox_installer/masker.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +module ConvoxInstaller + # Keeps secrets out of logs, summaries and JSON events. + class Masker + MASK = '[hidden]' + + # Settings whose names match this are treated as secrets unless their prompt says + # `secret: false`. + SECRET_KEY_PATTERN = /password|secret|token|license|private_key|key_base|encryption_key|credential|api_key/i + + # Credentials embedded in URLs: postgres://user:pass@host, https://convox:token@api... + URL_CREDENTIALS = %r{([a-z][a-z0-9+.-]*://[^:/@\s]*:)[^@/\s]+@}i + + # KEY=value arguments where KEY looks secret. + SECRET_ASSIGNMENT = / + \b([A-Za-z0-9_]*(?:PASSWORD|SECRET|TOKEN|LICENSE|KEY_BASE|ENCRYPTION_KEY|PRIVATE_KEY|API_KEY)[A-Za-z0-9_]*) + =("[^"]*"|'[^']*'|\S+) + /ix + + def self.secret_key?(key) + key.to_s.match?(SECRET_KEY_PATTERN) + end + + # How a secret appears in the configuration summary: masked, with the last four + # characters of long values so a person can tell which key or licence they entered. + def self.display(value) + str = value.to_s + return '' if str.empty? + return '********' if str.length < 16 + + "********#{str[-4..]}" + end + + def initialize + @secrets = Set.new + end + + def add(value) + str = value.to_s + # Very short values would mask unrelated text ("1", "us"). + @secrets << str if str.length >= 6 + self + end + + def mask(text) + return text unless text.is_a?(String) + + result = text.dup + @secrets.sort_by { |s| -s.length }.each { |secret| result = result.gsub(secret, MASK) } + result = result.gsub(URL_CREDENTIALS) { "#{Regexp.last_match(1)}#{MASK}@" } + result.gsub(SECRET_ASSIGNMENT) { "#{Regexp.last_match(1)}=#{MASK}" } + end + + def mask_data(data) + case data + when Hash then data.to_h { |k, v| [k, mask_data(v)] } + when Array then data.map { |v| mask_data(v) } + when String then mask(data) + else data + end + end + end +end diff --git a/lib/convox_installer/options.rb b/lib/convox_installer/options.rb new file mode 100644 index 0000000..6db6a56 --- /dev/null +++ b/lib/convox_installer/options.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +require 'logger' +require 'optparse' + +module ConvoxInstaller + # Parses the install script's command line. + # + # ruby install.rb [install|apply|plan|status] [--yes] [--json] [--config FILE] + # [--set key=value]... [-- value]... + class Options + COMMANDS = { + 'install' => :install, + 'apply' => :install, + 'plan' => :plan, + 'status' => :status + }.freeze + + LOG_LEVELS = { + 'debug' => Logger::DEBUG, + 'info' => Logger::INFO, + 'warn' => Logger::WARN, + 'error' => Logger::ERROR + }.freeze + + attr_reader :command, :settings, :config_path, :log_level + + # settings: setting key => title (the script's prompts); the gem's own settings are added. + def self.parse(argv, settings: {}, env: ENV, program_name: $PROGRAM_NAME) + new(env: env).tap { |o| o.parse!(argv, settings: settings, program_name: program_name) } + end + + def initialize(command: :install, json: false, assume_yes: false, settings: {}, config_path: nil, + log_level: nil, env: ENV) + @command = command + @json = json + @assume_yes = assume_yes + @settings = settings.transform_keys(&:to_sym) + @config_path = config_path + @log_level = log_level + @help = false + @version = false + @setting_titles = default_setting_titles + apply_env(env) + end + + def json? = @json + def assume_yes? = @assume_yes + def help? = @help + def version? = @version + def dry_run? = command != :install + + def parse!(argv, settings: {}, program_name: $PROGRAM_NAME) + @setting_titles = settings.to_h { |k, v| [k.to_sym, v || k.to_s] }.merge(default_setting_titles) do |_k, a, _b| + a + end + @parser = nil + @program_name = File.basename(program_name.to_s) + positional = parser.parse(argv.dup) + parse_command(positional) + self + rescue OptionParser::ParseError => e + raise UsageError.new(e.message, next_step: "Run `#{usage_command} --help` to see the options.") + end + + def help_text + [ + parser.help, + '', + 'Every setting can also come from an environment variable, CONVOX_INSTALLER_ (for example', + 'CONVOX_INSTALLER_STACK_NAME), or from the config file. The script\'s prompts also read ', + '(STACK_NAME), and a few settings read their usual names (AWS_REGION, AWS_PROFILE).', + 'Precedence: flags, then environment, then the config file, then defaults.', + '', + 'Exit codes: 0 success, 1 unexpected error, 2 missing or invalid input, 3 precondition failed,', + '4 step failed, 5 input ended at a prompt, 130 interrupted.' + ].join("\n") + end + + private + + def usage_command + "ruby #{@program_name || 'install.rb'}" + end + + def parser + @parser ||= OptionParser.new do |opts| + opts.banner = "Usage: #{usage_command} [install|apply|plan|status] [options]\n\n" \ + "Commands:\n " \ + "install (default) Set everything up. Re-run it to resume; finished steps are skipped.\n " \ + "apply Same as install.\n " \ + "plan Show which steps would make changes. Makes no changes.\n " \ + "status Show what exists now. Makes no changes.\n\n" \ + 'Options:' + opts.on('-y', '--yes', 'Never prompt; start without confirmation. Missing settings are an error.') do + @assume_yes = true + end + opts.on('--non-interactive', 'Same as --yes.') { @assume_yes = true } + opts.on('--json', 'Print one JSON event per line on stdout; human logs go to stderr.') { @json = true } + opts.on('--config FILE', 'Config file (default: ./.installer_config.json).') { |f| @config_path = f } + opts.on('--set KEY=VALUE', 'Set any setting. Repeatable.') { |pair| add_pair(pair) } + opts.on('--log-level LEVEL', LOG_LEVELS.keys, "Log level: #{LOG_LEVELS.keys.join(', ')}.") do |level| + @log_level = LOG_LEVELS.fetch(level) + end + opts.on('--debug', 'Same as --log-level debug.') { @log_level = Logger::DEBUG } + opts.on('-h', '--help', 'Show this help.') { @help = true } + opts.on('--version', 'Show the convox_installer version.') { @version = true } + opts.separator '' + opts.separator 'Settings:' + @setting_titles.each do |key, title| + opts.on("#{Settings.flag_name(key)} VALUE", title.to_s) { |value| @settings[key] = value } + end + end + end + + def default_setting_titles + Settings::KNOWN.to_h { |key, info| [key, info[:title]] } + end + + def add_pair(pair) + key, value = pair.split('=', 2) + if key.to_s.strip.empty? || value.nil? + raise OptionParser::InvalidArgument, "--set expects KEY=VALUE, got: #{pair}" + end + + @settings[key.strip.tr('-', '_').to_sym] = value + end + + def parse_command(positional) + return if positional.empty? + + if positional.length > 1 + raise UsageError.new("Unexpected arguments: #{positional.join(' ')}", + next_step: "Run `#{usage_command} --help` to see the commands.") + end + + name = positional.first + @command = COMMANDS.fetch(name) do + raise UsageError.new("Unknown command: #{name}. Commands: #{COMMANDS.keys.join(', ')}", + next_step: "Run `#{usage_command} --help` to see the commands.") + end + end + + def apply_env(env) + @assume_yes = true if Settings.truthy?(env['CONVOX_INSTALLER_NON_INTERACTIVE']) + # 3.x name for skipping the confirmation prompt. + @assume_yes = true if Platform.present?(env['AUTOSTART_CONVOX_INSTALLATION']) + @json = true if Settings.truthy?(env['CONVOX_INSTALLER_JSON']) + @config_path ||= env['CONVOX_INSTALLER_CONFIG'] if Platform.present?(env['CONVOX_INSTALLER_CONFIG']) + end + end +end diff --git a/lib/convox_installer/platform.rb b/lib/convox_installer/platform.rb new file mode 100644 index 0000000..4ab7eb3 --- /dev/null +++ b/lib/convox_installer/platform.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require 'rbconfig' + +module ConvoxInstaller + # Operating system details: where the Convox CLI keeps its settings and how to install + # the tools the installer needs. + module Platform + module_function + + def os(host_os = RbConfig::CONFIG['host_os']) + case host_os + when /darwin|mac os/i then :macos + when /linux/i then :linux + when /mswin|mingw|cygwin/i then :windows + else :other + end + end + + def arm64?(host_cpu = RbConfig::CONFIG['host_cpu']) + host_cpu.to_s.match?(/arm64|aarch64/i) + end + + # The Convox CLI (v3) keeps its settings, including each rack's Terraform directory, + # in its config directory: $CONVOX_CONFIG if set, otherwise convox/ under the XDG + # config home. On macOS that is ~/Library/Preferences/convox, on Linux ~/.config/convox + # (both honour $XDG_CONFIG_HOME). + def convox_config_dir(env: ENV, os: self.os) + return File.expand_path(env['CONVOX_CONFIG']) if present?(env['CONVOX_CONFIG']) + return File.join(File.expand_path(env['XDG_CONFIG_HOME']), 'convox') if present?(env['XDG_CONFIG_HOME']) + + if os == :macos + File.expand_path('~/Library/Preferences/convox') + else + File.expand_path('~/.config/convox') + end + end + + INSTALL_HINTS = { + 'convox' => { + macos: 'curl -L https://github.com/convox/convox/releases/latest/download/convox-macos%s ' \ + '-o /tmp/convox && sudo install -m 755 /tmp/convox /usr/local/bin/convox', + linux: 'curl -L https://github.com/convox/convox/releases/latest/download/convox-linux%s ' \ + '-o /tmp/convox && sudo install -m 755 /tmp/convox /usr/local/bin/convox', + docs: 'https://docs.convox.com/installation/cli' + }, + 'aws' => { + macos: 'brew install awscli', + linux: 'see https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html', + docs: 'https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html' + }, + 'terraform' => { + macos: 'brew install hashicorp/tap/terraform (or OpenTofu: brew install opentofu)', + linux: 'see https://developer.hashicorp.com/terraform/install ' \ + '(or OpenTofu: https://opentofu.org/docs/intro/install/)', + docs: 'https://developer.hashicorp.com/terraform/install' + } + }.freeze + + def install_hint(tool, os: self.os, arm64: arm64?) + hints = INSTALL_HINTS.fetch(tool) + hint = hints[os] || hints[:docs] + format(hint, arm: arm64 ? '-arm64' : '') + end + + def present?(value) + !value.nil? && !value.to_s.strip.empty? + end + end +end diff --git a/lib/convox_installer/reporter.rb b/lib/convox_installer/reporter.rb new file mode 100644 index 0000000..802c990 --- /dev/null +++ b/lib/convox_installer/reporter.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +require 'json' +require 'logger' +require 'time' + +module ConvoxInstaller + # Human logs and machine-readable events. + # + # Without --json, logs go to stdout as they did in 3.x and no events are printed. + # With --json, every event is one JSON object on its own line on stdout, and logs go + # to stderr. Everything passes through the Masker first. + class Reporter + attr_reader :logger, :human_io, :masker + + def initialize(masker:, json: false, event_io: $stdout, human_io: nil, log_level: Logger::INFO) + @masker = masker + @json = json + @event_io = event_io + @human_io = human_io || (json ? $stderr : $stdout) + @logger = Logger.new(@human_io) + @logger.level = log_level + @logger.formatter = method(:format_log) + end + + def json? = @json + + def event(type, **data) + return unless json? + + payload = { event: type.to_s, time: Time.now.utc.iso8601 }.merge(data).compact + @event_io.puts(JSON.generate(masker.mask_data(payload))) + @event_io.flush + end + + # Text for people (the config summary, step headings). Not an event. + def say(text = '') + @human_io.puts(masker.mask(text.to_s)) + @human_io.flush + end + + private + + def format_log(severity, _time, _progname, message) + text = masker.mask(message.is_a?(String) ? message : message.inspect) + prefix = %w[INFO ANY].include?(severity) ? '' : "#{severity}: " + "#{prefix}#{text}\n" + end + end +end diff --git a/lib/convox_installer/requirements.rb b/lib/convox_installer/requirements.rb index 984bacb..aa80b5e 100644 --- a/lib/convox_installer/requirements.rb +++ b/lib/convox_installer/requirements.rb @@ -1,77 +1,51 @@ # frozen_string_literal: true -require 'highline' -require 'os' -require 'logger' +require 'json' +require 'rubygems' module ConvoxInstaller + # Checks that convox (v3), the AWS CLI (v2) and terraform or OpenTofu (1.6+) are installed. class Requirements - attr_accessor :ecr_label, :logger + MINIMUM_TERRAFORM = Gem::Version.new('1.6.0') + # `aws configure export-credentials` arrived in AWS CLI 2.9. + MINIMUM_AWS_CLI = Gem::Version.new('2.9.0') + + attr_accessor :logger + attr_reader :context def initialize(options = {}) - @ecr_label = options[:ecr_label] - @logger = Logger.new($stdout) - logger.level = options[:log_level] || Logger::INFO + @context = options[:context] || Context.new(log_level: options[:log_level]) + @logger = context.logger + @terraform_preference = options[:terraform_binary] end def ensure_requirements! logger.debug 'Checking for required commands...' - @missing_packages = [] - unless command_present? 'convox' - @missing_packages << { - name: 'convox', - brew: 'convox', - docs: 'https://docs.convox.com/introduction/installation' - } - end - - unless command_present? 'aws' - @missing_packages << { - name: 'aws', - brew: 'awscli', - docs: 'https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html' - } - end - - unless command_present? 'terraform' - @missing_packages << { - name: 'terraform', - brew: 'terraform', - docs: 'https://learn.hashicorp.com/tutorials/terraform/install-cli' - } - end + missing = [] + missing << 'convox' unless command_present?('convox') + missing << 'aws' unless command_present?('aws') + terraform = terraform_binary + missing << (@terraform_preference || 'terraform') unless terraform + raise_missing!(missing) if missing.any? - if @missing_packages.any? - logger.error 'This script requires the convox and AWS CLI tools.' - if OS.mac? - logger.error 'Please run: brew install ' \ - "#{@missing_packages.map { |p| p[:brew] }.join(' ')}" - else - logger.error 'Installation Instructions:' - @missing_packages.each do |package| - logger.error "* #{package[:name]}: #{package[:docs]}" - end - end - quit! - end + check_convox_version! + check_aws_cli_version! + check_terraform_version!(terraform) + context.terraform_binary = terraform + true + end - client = Convox::Client.new - if client.convox_3_cli? - logger.debug "=> Convox CLI is version 3.x.x (#{client.cli_version_string})" - return - end + # terraform_binary setting (terraform, tofu or a path), otherwise terraform, otherwise tofu. + def terraform_binary + return find_command(@terraform_preference) if @terraform_preference - logger.error 'This script requires Convox CLI version 3.x.x. ' \ - "Your Convox CLI version is: #{client.cli_version_string}" - logger.error "Please run 'brew update convox' or follow the instructions " \ - 'at https://docs.convox.com/getting-started/introduction' - quit! + find_command('terraform') || find_command('tofu') end def command_present?(command) - path = find_command command - if path.present? + path = find_command(command) + if path logger.debug "=> Found #{command}: #{path}" return true end @@ -81,11 +55,79 @@ def command_present?(command) # Stubbed in tests def find_command(command) - `which #{command} 2>/dev/null`.chomp + context.shell.which(command) + end + + private + + def raise_missing!(missing) + os = Platform.os + hints = missing.map do |tool| + hint_key = %w[tofu terraform].include?(File.basename(tool)) ? 'terraform' : tool + hint_key = 'terraform' unless Platform::INSTALL_HINTS.key?(hint_key) + "#{tool}: #{Platform.install_hint(hint_key, os: os)}" + end + raise PreconditionFailed.new( + "This installer needs the convox, aws and terraform (or tofu) commands. Missing: #{missing.join(', ')}.", + next_step: "Install them, then run the same command again. #{hints.join(' | ')}" + ) + end + + def check_convox_version! + client = Convox::Client.new(context: context) + version = client.cli_version_string + if version == 'dev' + logger.warn 'The Convox CLI was built from source (version "dev"); assuming it is v3.' + return + end + if client.convox_3_cli? + logger.debug "=> Convox CLI is version 3.x.x (#{version})" + return + end + + raise PreconditionFailed.new( + "This installer needs Convox CLI version 3.x.x. Your Convox CLI version is: #{version.inspect}", + next_step: "Install the v3 CLI: #{Platform.install_hint('convox')} " \ + '(https://docs.convox.com/installation/cli). ' \ + 'Convox v2 racks need convox_installer 1.0.9.' + ) + end + + def check_aws_cli_version! + result = context.shell.capture(%w[aws --version]) + text = "#{result.stdout} #{result.stderr}" + version = text[%r{aws-cli/(\d+\.\d+\.\d+)}, 1] + return if version && Gem::Version.new(version) >= MINIMUM_AWS_CLI + + raise PreconditionFailed.new( + "This installer needs AWS CLI version #{MINIMUM_AWS_CLI} or later. Found: #{version || text.strip.inspect}", + next_step: "Install AWS CLI v2: #{Platform.install_hint('aws')}" + ) + end + + def check_terraform_version!(binary) + result = context.shell.capture([binary, 'version', '-json']) + version = parse_terraform_version(result) + if version && Gem::Version.new(version) >= MINIMUM_TERRAFORM + logger.debug "=> #{File.basename(binary)} version #{version}" + return + end + + raise PreconditionFailed.new( + "This installer needs Terraform or OpenTofu #{MINIMUM_TERRAFORM} or later. " \ + "#{binary} reported: #{version || 'no version'}", + next_step: "Upgrade: #{Platform.install_hint('terraform')}" + ) end - def quit! - exit 1 + def parse_terraform_version(result) + begin + version = JSON.parse(result.stdout)['terraform_version'] + return version if version + rescue JSON::ParserError + # Older releases have no -json flag; fall back to the text output. + end + "#{result.stdout} #{result.stderr}"[/v?(\d+\.\d+\.\d+)/, 1] end end end diff --git a/lib/convox_installer/runner.rb b/lib/convox_installer/runner.rb new file mode 100644 index 0000000..6fc77fe --- /dev/null +++ b/lib/convox_installer/runner.rb @@ -0,0 +1,210 @@ +# frozen_string_literal: true + +module ConvoxInstaller + # Runs named steps and reports them. + # + # Every step checks the current state before it changes anything, so an install can be + # re-run after a failure and skips what is already done. In `plan` and `status` a step + # runs its read-only checks and stops before the first change, reporting what install + # would do. + class Runner + STEP_END = :convox_installer_step_end + + # Passed to each step's block. + class StepHandle + attr_reader :name + + def initialize(runner, name) + @runner = runner + @name = name + @info = {} + end + + # Nothing to do: the step is already in the state it would create. + def skip!(reason = nil, **info) + throw STEP_END, { status: 'skipped', state: 'present', reason: reason }.merge(info).compact + end + + # Call this right before the first change. In plan and status it ends the step and + # reports the change; in install it does nothing and the step goes on. + def plan!(action:, state: 'missing', reason: nil, **info) + @info.merge!(info.compact) + return unless @runner.dry_run? + + throw STEP_END, { status: 'pending', state: state, action: action, reason: reason }.merge(@info).compact + end + + # Extra fields for the step's final event. + def info(**data) + @info.merge!(data.compact) + end + + def collected_info = @info + end + + attr_reader :context, :steps, :outputs + + def initialize(context) + @context = context + @steps = [] + @outputs = {} + @finished = false + end + + def dry_run? = context.dry_run? + def command = context.command + + # check: a lambda that returns true when the step is already done. + # run_in_dry_run: false means the block makes changes without calling plan! first, so in + # plan and status it doesn't run (the step is pending unless check says it's done). + def step(name, description = nil, check: nil, run_in_dry_run: true) + name = name.to_s + handle = StepHandle.new(self, name) + reporter.say("==> #{name}#{": #{description}" if description}") unless dry_run? + reporter.event('step', step: name, status: 'started', description: description) unless dry_run? + + value = nil + outcome = catch(STEP_END) do + handle.skip!('already done') if check&.call + handle.plan!(action: 'run') if check || !run_in_dry_run + value = yield(handle) if block_given? + nil + end + outcome ||= { status: 'done' }.merge(handle.collected_info) + record(name, description, outcome) + value + rescue NotYetAvailable => e + e.step ||= name + record(name, description, { status: 'pending', state: 'unknown', reason: e.message }) + raise + rescue Error => e + e.step ||= name + record(name, description, failure(e)) + raise + rescue StandardError => e + error = StepFailed.new( + "Step #{name} failed: #{e.message}", + step: name, + next_step: 'Fix the problem above, then run the same command again. Finished steps are skipped.' + ) + error.set_backtrace(e.backtrace) + record(name, description, failure(error)) + raise error + end + + def add_output(key, value) + outputs[key.to_s] = value + end + + # Emits the final result event and returns the exit code. + def finish(exception = nil) + return @exit_code if @finished + + @finished = true + code, error = classify(exception) + result = { + command: command.to_s, + status: result_status(code, exception), + exit_code: code, + steps: steps.map { |s| s.slice(:step, :status, :action, :state) }, + outputs: outputs.empty? ? nil : outputs, + config_file: context.config_file, + error: error + } + if dry_run? + pending = steps.select { |s| s[:status] == 'pending' }.map { |s| s[:step] } + result[:pending] = pending + result[:changes_pending] = pending.any? + if exception.is_a?(NotYetAvailable) + result[:stopped_early] = + { step: exception.step, reason: exception.message }.compact + end + end + reporter.event('result', **result.compact) + report_to_human(code, exception, error) + @exit_code = code + end + + private + + def reporter = context.reporter + + def record(name, description, outcome) + entry = { step: name, description: description }.merge(outcome).compact + steps << entry + reporter.event('step', **entry) + log_outcome(entry) + end + + def log_outcome(entry) + text = case entry[:status] + when 'skipped' then " already done#{" (#{entry[:reason]})" if entry[:reason]}" + when 'pending' then " would #{entry[:action] || 'run'}#{": #{entry[:reason]}" if entry[:reason]}" + when 'failed' then " failed: #{entry.dig(:error, :message)}" + end + if dry_run? + reporter.say("#{entry[:step].ljust(28)} #{entry[:status]}#{" -#{text.sub(/\A\s+/, ' ')}" if text}") + elsif text + reporter.say(text) + end + end + + def failure(error) + { status: 'failed', error: error_hash(error) } + end + + def error_hash(error) + { + type: error.respond_to?(:type) ? error.type : 'error', + message: error.message, + step: error.respond_to?(:step) ? error.step : nil, + next_step: error.respond_to?(:next_step) ? error.next_step : nil + }.merge(error.respond_to?(:details) ? error.details : {}).compact + end + + def classify(exception) + case exception + when nil then [ExitCodes::SUCCESS, nil] + when SystemExit + code = exception.status + error = code.zero? ? nil : { type: 'exit', message: "The script exited with status #{code}." } + [code, error] + when NotYetAvailable + return [ExitCodes::SUCCESS, nil] if dry_run? + + [ExitCodes::PRECONDITION_FAILED, error_hash(exception).merge(type: 'precondition_failed')] + when Interrupt then [ExitCodes::INTERRUPTED, { type: 'interrupted', message: 'Interrupted.' }] + when Error then [exception.exit_code, error_hash(exception)] + else [ExitCodes::ERROR, error_hash(exception).merge(type: 'unexpected_error')] + end + end + + def result_status(code, exception) + return 'succeeded' if code.zero? + return 'cancelled' if exception.is_a?(Cancelled) || exception.is_a?(Interrupt) + + 'failed' + end + + def report_to_human(code, exception, error) + if code.zero? + if dry_run? + pending = steps.count { |s| s[:status] == 'pending' } + reporter.say + reporter.say(if pending.zero? + 'Nothing to change.' + else + "#{pending} step(s) would make changes. Run install to apply them." + end) + reporter.say("Stopped early: #{exception.message}") if exception.is_a?(NotYetAvailable) + end + return + end + return if error.nil? || exception.is_a?(SystemExit) + + reporter.say + reporter.logger.error(error[:message]) + reporter.say("Next: #{error[:next_step]}") if error[:next_step] + end + end +end diff --git a/lib/convox_installer/settings.rb b/lib/convox_installer/settings.rb new file mode 100644 index 0000000..25eb4a9 --- /dev/null +++ b/lib/convox_installer/settings.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true + +module ConvoxInstaller + # Settings the gem itself reads, besides the prompts in a script. Every setting (these and + # every prompt key) can come from a command-line flag, an environment variable or the + # config file. This table drives `--help`, the per-setting flags and the README. + module Settings + # persist: false keeps a value out of the config file when it came from the + # environment or a flag (AWS credentials belong to the credential chain, not the file). + KNOWN = { + aws_region: { + title: 'AWS Region', + env: %w[AWS_REGION AWS_DEFAULT_REGION], + description: 'AWS region for the rack and its resources.' + }, + aws_profile: { + title: 'AWS Profile', + env: %w[AWS_PROFILE], + description: 'AWS CLI profile to use (SSO, assumed role or keys). ' \ + 'Leave unset to use the default credential chain.' + }, + aws_account_id: { + title: 'AWS Account ID', + env: %w[AWS_ACCOUNT_ID], + description: 'The AWS account to install into. Saved after the first confirmation; ' \ + 'the installer stops if the credentials belong to a different account.' + }, + aws_access_key_id: { + title: 'AWS Access Key ID', + env: %w[AWS_ACCESS_KEY_ID], + secret: false, + persist: false, + description: 'Explicit access key (still accepted for older scripts). Prefer a profile or SSO.' + }, + aws_secret_access_key: { + title: 'AWS Secret Access Key', + env: %w[AWS_SECRET_ACCESS_KEY], + secret: true, + persist: false, + description: 'Explicit secret key, used with aws_access_key_id.' + }, + aws_session_token: { + title: 'AWS Session Token', + env: %w[AWS_SESSION_TOKEN], + secret: true, + persist: false, + description: 'Session token for temporary explicit credentials.' + }, + terraform_binary: { + title: 'Terraform binary', + description: 'terraform, tofu, or a path to either. Default: terraform if installed, otherwise tofu.' + }, + convox_rack_version: { + title: 'Convox rack version', + description: 'Rack version for `convox rack install --version`. Default: the latest release.' + }, + convox_rack_params: { + title: 'Extra rack parameters', + description: 'More `convox rack install` parameters, as key=value pairs separated by spaces ' \ + '(or a Hash in the config file). Example: high_availability=false build_node_enabled=true' + }, + convox_proxy_protocol: { + title: 'Proxy protocol', + description: 'Rack parameter proxy_protocol, which passes client IPs to the app. Default: true.' + }, + availability_zones: { + title: 'Availability zones', + description: 'Comma-separated availability zones for the rack (at least 3). ' \ + 'Default: chosen by AWS, except us-east-1 where us-east-1c is left out.' + }, + convox_api_timeout: { + title: 'Rack API timeout', + description: 'Seconds to wait for the rack API to answer after an install. Default: 360.' + }, + convox_app_name: { title: 'Convox App Name', description: 'Name of the Convox app.' }, + default_service: { + title: 'Default service', + description: 'Service whose *.convox.cloud domain default_service_domain_name returns. Default: web.' + }, + docker_registry_url: { title: 'Docker Registry URL', description: 'Private registry server to add.' }, + docker_registry_username: { title: 'Docker Registry Username', description: 'Registry username.' }, + docker_registry_password: { title: 'Docker Registry Password', secret: true, description: 'Registry password.' }, + s3_bucket_name: { + title: 'S3 bucket name', + description: 'Bucket name suffix; the bucket is named -.' + }, + s3_bucket_cors_rule: { + title: 'S3 CORS rule', + description: 'CORS rules: a Terraform `cors_rule { ... }` block, or a list of rule hashes in the config file.' + }, + s3_bucket_versioning: { + title: 'S3 versioning', + description: 'Enabled, Suspended or Disabled. Default: Enabled for new buckets; existing buckets keep theirs.' + }, + s3_bucket_noncurrent_version_expiration_days: { + title: 'S3 old version expiry', + description: 'Days to keep old object versions when versioning is on. Default: 30.' + }, + database_username: { title: 'Database username', description: 'RDS master username. Default: app.' }, + database_password: { + title: 'Database password', + secret: true, + description: 'RDS master password. Generated and saved to the config file if not set.' + }, + database_engine_version: { + title: 'Postgres version', + description: 'RDS Postgres engine version. Default: 17 for new databases; existing databases keep theirs.' + }, + database_instance_class: { title: 'RDS instance class', description: 'Default: db.t3.small.' }, + database_allocated_storage: { title: 'RDS storage (GiB)', description: 'Default: 30.' }, + database_storage_type: { title: 'RDS storage type', description: 'Default: gp3 for new databases.' }, + database_storage_encrypted: { + title: 'RDS storage encryption', + description: 'Default: true for new databases. Changing it on an existing database would replace it, ' \ + 'so the installer refuses.' + }, + database_multi_az: { title: 'RDS Multi-AZ', description: 'Default: true.' }, + database_backup_retention_period: { + title: 'RDS backup retention (days)', + description: 'Default: 7 for new databases.' + }, + database_deletion_protection: { title: 'RDS deletion protection', description: 'Default: true.' }, + database_allow_major_version_upgrade: { + title: 'Allow Postgres major upgrade', + description: 'Set to true when you change database_engine_version to a new major version. Default: false.' + }, + elasticache_engine: { title: 'ElastiCache engine', description: 'redis or valkey. Default: redis.' }, + elasticache_engine_version: { title: 'ElastiCache version', description: 'Default: 7.1.' }, + elasticache_node_type: { title: 'ElastiCache node type', description: 'Default: cache.t3.medium.' }, + elasticache_num_cache_nodes: { + title: 'ElastiCache nodes', + description: 'Default: 1. With 2 or more, automatic failover and Multi-AZ are turned on.' + }, + elasticache_port: { title: 'ElastiCache port', description: 'Default: 6379.' }, + elasticache_auth_token: { + title: 'ElastiCache auth token', + secret: true, + description: 'Redis AUTH token. Generated and saved to the config file if not set.' + }, + elasticache_legacy_cluster: { + title: 'ElastiCache legacy cluster', + description: 'true keeps the 3.x single-node cluster without TLS or AUTH. Default: true when that ' \ + 'cluster already exists in the Terraform state, otherwise false.' + } + }.freeze + + module_function + + # Environment variables for a setting, in order of precedence. plain: true adds the bare + # upper-case name (STACK_NAME), which 3.x read for every prompt. The gem's own settings + # without a prompt don't use bare names, so a DATABASE_PASSWORD in your shell for some + # other project isn't picked up. + def env_names(key, plain: true) + key = key.to_sym + names = ["CONVOX_INSTALLER_#{key.to_s.upcase}"] + names << key.to_s.upcase if plain + names += KNOWN.dig(key, :env) || [] + names.uniq + end + + def flag_name(key) + "--#{key.to_s.tr('_', '-')}" + end + + def persist?(key) + KNOWN.dig(key.to_sym, :persist) != false + end + + def truthy?(value) + case value + when true then true + when false, nil then false + else %w[1 true yes y on enabled].include?(value.to_s.strip.downcase) + end + end + + def boolean?(value) + [true, false].include?(value) || + %w[1 0 true false yes no y n on off enabled disabled].include?(value.to_s.strip.downcase) + end + end +end diff --git a/lib/convox_installer/shell.rb b/lib/convox_installer/shell.rb new file mode 100644 index 0000000..4f2a1e0 --- /dev/null +++ b/lib/convox_installer/shell.rb @@ -0,0 +1,110 @@ +# frozen_string_literal: true + +require 'open3' +require 'shellwords' + +module ConvoxInstaller + # Runs external commands (convox, terraform, aws). Commands are argument arrays, never + # shell strings, so values with spaces or quotes can't break them, and the logged form of + # every command is masked. Specs replace the executor, so no real command runs in tests. + class Shell + Result = Struct.new(:stdout, :stderr, :exit_code, keyword_init: true) do + def success? = exit_code.zero? + end + + # The real executor. Specs set Shell.executor to a double. + class SystemExecutor + def capture(env, argv, stdin_data:, chdir:) + options = { stdin_data: stdin_data } + options[:chdir] = chdir if chdir + stdout, stderr, status = Open3.capture3(env, *argv, **options) + [stdout, stderr, status.exitstatus || 1] + end + + # Streams combined stdout and stderr line by line to the block. + def stream(env, argv, stdin_data:, chdir:, &block) + options = {} + options[:chdir] = chdir if chdir + Open3.popen2e(env, *argv, **options) do |stdin, output, wait| + stdin.write(stdin_data) if stdin_data + stdin.close + output.each_line(&block) + wait.value.exitstatus || 1 + end + end + end + + class << self + attr_writer :executor + + def executor + @executor ||= SystemExecutor.new + end + end + + attr_reader :reporter, :masker + + def initialize(reporter:, masker:, executor: nil) + @reporter = reporter + @masker = masker + @executor = executor + end + + def executor + @executor || self.class.executor + end + + # Runs a command and returns its output. stdin is closed (or receives stdin_data), so a + # command never waits for input. + def capture(argv, env: {}, stdin_data: '', chdir: nil) + argv = normalize(argv) + reporter.logger.debug("+ #{display(argv)}#{" (in #{chdir})" if chdir}") + stdout, stderr, code = executor.capture(stringify_env(env), argv, stdin_data: stdin_data, chdir: chdir) + Result.new(stdout: stdout.to_s, stderr: stderr.to_s, exit_code: code) + end + + # Runs a command and shows its output as it runs (on stderr in --json mode). + def stream(argv, env: {}, stdin_data: nil, chdir: nil) + argv = normalize(argv) + reporter.logger.info("+ #{display(argv)}") + io = reporter.human_io + code = executor.stream(stringify_env(env), argv, stdin_data: stdin_data, chdir: chdir) do |line| + io.write(masker.mask(line)) + io.flush + end + Result.new(stdout: '', stderr: '', exit_code: code) + end + + # The command as text for logs: secret KEY=value arguments and known secrets masked. + def display(argv) + words = normalize(argv).map do |arg| + key, value = arg.split('=', 2) + arg = "#{key}=#{Masker::MASK}" if value && key.match?(/\A[A-Za-z_][A-Za-z0-9_]*\z/) && Masker.secret_key?(key) + arg.match?(%r{\A[A-Za-z0-9_@%+=:,./\[\]-]+\z}) ? arg : Shellwords.escape(arg) + end + masker.mask(words.join(' ')) + end + + # Finds an executable on PATH without running a subprocess. + def which(command) + return command if command.include?(File::SEPARATOR) && File.executable?(command) + + ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).each do |dir| + path = File.join(dir, command) + return path if File.file?(path) && File.executable?(path) + end + nil + end + + private + + def normalize(argv) + argv = Shellwords.split(argv) if argv.is_a?(String) + argv.map(&:to_s) + end + + def stringify_env(env) + env.to_h { |k, v| [k.to_s, v&.to_s] } + end + end +end diff --git a/lib/convox_installer/version.rb b/lib/convox_installer/version.rb index 9b0ee6e..64f5fae 100644 --- a/lib/convox_installer/version.rb +++ b/lib/convox_installer/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module ConvoxInstaller - VERSION = '3.2.1' + VERSION = '4.0.0' end diff --git a/spec/fixtures/fake_tools.rb b/spec/fixtures/fake_tools.rb new file mode 100644 index 0000000..1025d7f --- /dev/null +++ b/spec/fixtures/fake_tools.rb @@ -0,0 +1,193 @@ +# frozen_string_literal: true + +# Fake convox, aws and terraform commands for the end-to-end spec. Each fake executable is a +# small sh wrapper that runs this file with the tool name. State lives in FAKE_STATE_DIR. +# Nothing here talks to AWS or Convox. + +require 'json' +require 'fileutils' +require 'digest' + +module FakeTools + module_function + + def state_dir = ENV.fetch('FAKE_STATE_DIR') + def state_file = File.join(state_dir, 'state.json') + + def state + @state ||= File.exist?(state_file) ? JSON.parse(File.read(state_file)) : {} + end + + def save + File.write(state_file, JSON.generate(state)) + end + + def log_call(tool, argv) + entry = { tool: tool, argv: argv, aws_key: ENV.fetch('AWS_ACCESS_KEY_ID', nil), cwd: Dir.pwd } + File.open(File.join(state_dir, 'calls.log'), 'a') { |f| f.puts(JSON.generate(entry)) } + end + + def rack_arg(argv) + index = argv.index('--rack') + index ? argv[index + 1] : nil + end + + def rack_dir(name) + File.join(ENV.fetch('CONVOX_CONFIG'), 'racks', name) + end + + def run(tool, argv) + log_call(tool, argv) + case tool + when 'aws' then aws(argv) + when 'convox' then convox(argv) + when 'terraform' then terraform(argv) + end + ensure + save + end + + def aws(argv) + case argv.first(2) + when ['--version'] then puts 'aws-cli/2.31.0 Python/3.13.0 Linux/6.8 exe/x86_64' + when %w[configure export-credentials] + puts JSON.generate(Version: 1, AccessKeyId: 'ASIAFAKE', SecretAccessKey: 'fake-exported-secret', + SessionToken: 'fake-session-token', Expiration: (Time.now + 3600).utc.strftime('%FT%TZ')) + when %w[rds describe-db-instances] + db = (state['resources'] || []).find { |r| r['type'] == 'aws_db_instance' } + puts db.dig('instances', 0, 'attributes', 'engine_version') + when %w[sts get-caller-identity] + puts JSON.generate(Account: '123456789012', Arn: 'arn:aws:sts::123456789012:assumed-role/Admin/agent') + else + warn "fake aws: unsupported #{argv.join(' ')}" + exit 254 + end + end + + def convox(argv) + if argv == ['--version'] + puts '3.26.0' + return + end + + rack = rack_arg(argv) + case argv.first(2) + when %w[rack install] + name = argv[argv.index('aws') + 1] + FileUtils.mkdir_p(File.join(rack_dir(name), '.terraform')) + File.write(File.join(rack_dir(name), 'main.tf'), "module \"system\" {}\n") + state['installed'] = name + puts "Installing #{name}... OK" + when %w[api get] + path = argv[2] + data = case path + when '/system' then { name: rack, provider: 'aws', version: '3.26.0' } + when '/apps' then (state['apps'] || []).map { |a| { name: a } } + when '/registries' then (state['registries'] || []).map { |r| { server: r } } + else state['deployed'] ? [{ name: 'web' }] : [] + end + puts JSON.generate(data) + when %w[apps create] then (state['apps'] ||= []) << argv[2] + when %w[registries add] then (state['registries'] ||= []) << argv[2] + when %w[env --app] then (state['env'] || {}).each { |k, v| puts "#{k}=#{v}" } + when %w[env set] + env = (state['env'] ||= {}) + $stdin.read.each_line do |line| + k, v = line.chomp.split('=', 2) + env[k] = v + end + puts 'Setting... OK' + else + case argv.first + when 'switch' then File.write(File.join(ENV.fetch('CONVOX_CONFIG'), 'current'), + JSON.generate(name: argv[1], type: 'terraform')) + when 'deploy' then state['deployed'] = true + when 'build' then puts 'RFAKE12345' + when 'releases' + unless argv[1] == 'promote' + warn "fake convox: unsupported #{argv.join(' ')}" + exit 1 + end + state['promoted'] = argv[2] + state['deployed'] = true + when 'run' then state['ran'] = (state['ran'] || []) << argv[1..].join(' ') + else + warn "fake convox: unsupported #{argv.join(' ')}" + exit 1 + end + end + end + + def tf_files_digest + Digest::SHA256.hexdigest(Dir.glob('*.tf').map { |f| File.read(f) }.join) + end + + def terraform(argv) + case argv.first + when 'version' then puts JSON.generate(terraform_version: '1.13.4') + when 'output' + outputs = state['installed'] ? { api: { value: 'https://convox:fake-api-pw@api.fake123.convox.cloud' } } : {} + puts JSON.generate(outputs) + when 'state' then puts JSON.generate(version: 4, resources: state['resources'] || []) + when 'plan' then exit(state['applied_digest'] == tf_files_digest ? 0 : 2) + when 'apply' + state['applied_digest'] = tf_files_digest + state['resources'] = applied_resources + puts 'Apply complete!' + else + warn "fake terraform: unsupported #{argv.join(' ')}" + exit 1 + end + end + + def resource(type, name, attributes) + { mode: 'managed', type: type, name: name, instances: [{ attributes: attributes }] } + end + + # The attributes of one resource block in a .tf file in the current directory, as + # Terraform would record them in its state (only the simple `key = value` lines). + def block_attributes(file, type, name) + return nil unless File.exist?(file) + + block = File.read(file)[/^resource "#{type}" "#{name}" \{\n(.*?)^\}/m, 1] + return nil unless block + + block.lines.each_with_object({}) do |line, attributes| + key, value = line.strip.split(/\s*=\s*/, 2) + next unless value && key.match?(/\A[a-z_]+\z/) + + attributes[key] = case value + when 'true', 'false' then value == 'true' + when /\A\d+\z/ then Integer(value) + when /\A"/ then JSON.parse(value) + end + end.compact + end + + def applied_resources + resources = [] + if (bucket = block_attributes('s3_bucket.tf', 'aws_s3_bucket', 'docs_s3_bucket')) + resources << resource('aws_s3_bucket', 'docs_s3_bucket', bucket) + status = File.read('s3_bucket.tf')[/status = "(\w+)"/, 1] + resources << resource('aws_s3_bucket_versioning', 'docs_s3_bucket', + versioning_configuration: [{ status: status }]) + resources << resource('aws_s3_bucket_ownership_controls', 'docs_s3_bucket', {}) + if File.read('s3_bucket.tf').include?('aws_s3_bucket_lifecycle_configuration') + resources << resource('aws_s3_bucket_lifecycle_configuration', 'docs_s3_bucket', {}) + end + resources << resource('aws_iam_access_key', 'docspring_user_access_key', id: 'AKIAFAKEAPP', + secret: 'fake-app-secret') + end + if (db = block_attributes('rds.tf', 'aws_db_instance', 'rds_database')) + resources << resource('aws_db_instance', 'rds_database', + db.merge('endpoint' => 'db.fake:5432', 'address' => 'db.fake', 'port' => 5432)) + end + if (redis = block_attributes('elasticache.tf', 'aws_elasticache_replication_group', 'redis')) + resources << resource('aws_elasticache_replication_group', 'redis', + redis.merge('primary_endpoint_address' => 'redis.fake')) + end + resources + end +end + +FakeTools.run(ARGV.shift, ARGV) if $PROGRAM_NAME == __FILE__ diff --git a/spec/lib/convox/client_spec.rb b/spec/lib/convox/client_spec.rb index e393613..9485988 100644 --- a/spec/lib/convox/client_spec.rb +++ b/spec/lib/convox/client_spec.rb @@ -1,102 +1,656 @@ # frozen_string_literal: true -require 'convox/client' +require 'spec_helper' RSpec.describe Convox::Client do - let(:home_dir) { File.expand_path('~') } + include FakeRack + + let(:executor) { FakeExecutor.new } + let(:command) { :install } + let(:context) do + build_context(command: command, executor: executor).tap { |c| c.terraform_binary = '/usr/bin/terraform' } + end + let(:settings) do + { + stack_name: 'test-rack', + aws_region: 'us-west-2', + instance_type: 't3.large', + random_id: 'ab12cd34', + convox_app_name: 'myapp' + } + end + let(:config) { settings.dup } + let(:client) { described_class.new(context: context, config: config) } + + around do |example| + with_convox_config_dir { example.run } + end + + before do + stub_aws(executor) + stub_terraform_reads(executor) + end + + def step_events + events(context).select { |e| e['event'] == 'step' && e['status'] != 'started' } + end describe 'Convox CLI version' do - let(:client) { described_class.new } + { + '3.26.0' => true, + '3.0.0' => true, + '3.25.14rc2' => true, + '20210208170413' => false, + '4.0.0' => false + }.each do |version, expected| + it "#{expected ? 'accepts' : 'rejects'} #{version}" do + executor.on('convox', '--version') { "#{version}\n" } + expect(client.convox_3_cli?).to be expected + end + end - it 'returns the convox CLI version output for 20210208170413' do - expect(client).to receive(:cli_version_string).at_least(:once).and_return('20210208170413') - expect(client.convox_2_cli?).to be true - expect(client.convox_3_cli?).to be false + it 'parses the version' do + executor.on('convox', '--version') { "3.26.0\n" } + expect(client.cli_version).to eq Gem::Version.new('3.26.0') end + end - it 'returns the convox CLI version output for 20200101130413' do - expect(client).to receive(:cli_version_string).at_least(:once).and_return('20200101130413') - expect(client.convox_2_cli?).to be true - expect(client.convox_3_cli?).to be false + describe '#rack_dir' do + it 'is under CONVOX_CONFIG' do + expect(client.rack_dir).to eq File.join(ENV.fetch('CONVOX_CONFIG'), 'racks', 'test-rack') end + end - it 'returns the convox CLI version output for 3.0.0' do - expect(client).to receive(:cli_version_string).at_least(:once).and_return('3.0.0') - expect(client.convox_2_cli?).to be false - expect(client.convox_3_cli?).to be true + describe '#backup_convox_host_and_rack' do + it 'moves the current rack setting aside' do + current = File.join(ENV.fetch('CONVOX_CONFIG'), 'current') + File.write(current, '{"name":"other","type":"terraform"}') + client.backup_convox_host_and_rack + expect(File.exist?(current)).to be false + expect(File.read("#{current}.bak")).to include 'other' end - it 'returns the convox CLI version output for 3.1.3' do - expect(client).to receive(:cli_version_string).at_least(:once).and_return('3.1.3') - expect(client.convox_2_cli?).to be false - expect(client.convox_3_cli?).to be true + it 'keeps the current rack setting when the rack is already installed' do + current = File.join(ENV.fetch('CONVOX_CONFIG'), 'current') + File.write(current, '{"name":"test-rack","type":"terraform"}') + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + client.backup_convox_host_and_rack + expect(File.exist?(current)).to be true end - it 'returns the convox CLI version output for 4.0.0' do - expect(client).to receive(:cli_version_string).at_least(:once).and_return('4.0.0') - expect(client.convox_2_cli?).to be false - expect(client.convox_3_cli?).to be false + context 'when planning' do + let(:command) { :plan } + + it 'changes nothing' do + current = File.join(ENV.fetch('CONVOX_CONFIG'), 'current') + File.write(current, '{}') + client.backup_convox_host_and_rack + expect(File.exist?(current)).to be true + end end end - it 'backups existing Convox host and rack files' do - expect(File).to receive(:exist?).with( - "#{home_dir}/.convox/host" - ).and_return(true) - expect(File).to receive(:exist?).with( - "#{home_dir}/.convox/rack" - ).and_return(true) - expect(FileUtils).to receive(:mv).with( - "#{home_dir}/.convox/host", "#{home_dir}/.convox/host.bak" - ) - expect(FileUtils).to receive(:mv).with( - "#{home_dir}/.convox/rack", "#{home_dir}/.convox/rack.bak" - ) + describe '#install_convox' do + it 'requires the region and stack name' do + expect { described_class.new(context: context, config: {}).install_convox } + .to raise_error(ConvoxInstaller::MissingInput, 'aws_region, stack_name are missing from the config!') + end - client = described_class.new - expect(client.logger).to receive(:info).twice + it 'runs convox rack install with the AWS credentials from the credential chain' do + executor.on('convox', 'rack', 'install') do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + "Installing...\n" + end - client.backup_convox_host_and_rack - end + expect(client.install_convox).to be true + + install = executor.calls_matching('convox', 'rack', 'install').first + expect(install.argv).to eq %w[ + convox rack install aws test-rack node_type=t3.large region=us-west-2 proxy_protocol=true + ] + expect(install.env).to include( + 'AWS_ACCESS_KEY_ID' => 'ASIAEXAMPLE', + 'AWS_SECRET_ACCESS_KEY' => 'exported-secret-key-value', + 'AWS_SESSION_TOKEN' => 'exported-session-token-value', + 'AWS_REGION' => 'us-west-2' + ) + expect(step_events.last).to include('step' => 'convox_rack', 'status' => 'done') + expect(human_output(context)).not_to include('exported-secret-key-value') + end + + it 'leaves out us-east-1c in us-east-1, passes extra parameters and the rack version' do + config.merge!(aws_region: 'us-east-1', convox_rack_version: '3.26.0', convox_proxy_protocol: 'false', + convox_rack_params: 'high_availability=false tags=team=ops,env=prod') + executor.on('convox', 'rack', 'install') do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + '' + end + + client.install_convox + + expect(executor.calls_matching('convox', 'rack', 'install').first.argv).to eq %w[ + convox rack install --version 3.26.0 aws test-rack node_type=t3.large region=us-east-1 + proxy_protocol=false availability_zones=us-east-1a,us-east-1b,us-east-1d,us-east-1e,us-east-1f + high_availability=false tags=team=ops,env=prod + ] + end - describe '#install' do - it 'requires the correct config vars' do - client = described_class.new - expect { client.install_convox }.to raise_error('aws_region is missing from the config!') + it 'uses explicit access keys from the settings when they are set' do + config.merge!(aws_access_key_id: 'AKIALEGACY', aws_secret_access_key: 'legacy-secret-value') + executor.on('convox', 'rack', 'install') do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + '' + end + + client.install_convox - client = described_class.new(config: { aws_region: 'us-east-1' }) - expect { client.install_convox }.to raise_error('stack_name is missing from the config!') + env = executor.calls_matching('convox', 'rack', 'install').first.env + expect(env).to include('AWS_ACCESS_KEY_ID' => 'AKIALEGACY', 'AWS_SECRET_ACCESS_KEY' => 'legacy-secret-value', + 'AWS_SESSION_TOKEN' => nil) + expect(executor.calls_matching('aws', 'configure')).to be_empty end - it 'runs the correct convox CLI command' do - client = described_class.new( - config: { - aws_region: 'us-east-1', - aws_access_key_id: 'asdf', - aws_secret_access_key: '1234', - stack_name: 'asdf', - instance_type: 't3.medium' - } - ) + it 'skips an installed rack' do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + + client.install_convox + + expect(executor.calls_matching('convox', 'rack', 'install')).to be_empty + expect(step_events.last).to include('step' => 'convox_rack', 'status' => 'skipped', 'state' => 'present') + end + + it 'resumes an unfinished install with terraform apply in the rack directory' do + dir = create_rack_dir('test-rack') + @tf_outputs = {} + executor.on('/usr/bin/terraform', 'apply') do + @tf_outputs = installed_outputs + '' + end - expect(client.logger).to receive(:info) - expect(client).to receive(:run_convox_command!).with( - 'rack install aws --name "asdf" "InstanceType=t3.medium" ' \ - '"BuildInstance="', - 'AWS_ACCESS_KEY_ID' => 'asdf', - 'AWS_REGION' => 'us-east-1', - 'AWS_SECRET_ACCESS_KEY' => '1234' - ) client.install_convox + + apply = executor.calls_matching('/usr/bin/terraform', 'apply').first + expect(apply.argv).to eq ['/usr/bin/terraform', 'apply', '-auto-approve', '-input=false', '-no-color'] + expect(apply.chdir).to eq dir + expect(apply.env).to include('AWS_STS_REGIONAL_ENDPOINTS' => 'regional') + expect(executor.calls_matching('convox', 'rack', 'install')).to be_empty + end + + it 'fails with exit code 4 and a next step when convox rack install fails' do + executor.on('convox', 'rack', 'install') { ['', "terraform failed\n", 1] } + + expect { client.install_convox }.to raise_error(ConvoxInstaller::StepFailed) do |error| + expect(error.exit_code).to eq 4 + expect(error.step).to eq 'convox_rack' + expect(error.next_step).to include 'Run the same command again' + end + end + + it 'refuses a rack directory without main.tf' do + create_rack_dir('test-rack', main_tf: false) + expect { client.install_convox }.to raise_error(ConvoxInstaller::PreconditionFailed, /has no main.tf/) + end + + context 'when planning' do + let(:command) { :plan } + + it 'reports the install command without running it' do + client.install_convox + + expect(executor.calls_matching('convox', 'rack', 'install')).to be_empty + event = step_events.last + expect(event).to include('step' => 'convox_rack', 'status' => 'pending', 'action' => 'create') + expect(event['command']).to include 'convox rack install aws test-rack' + end + end + + context 'when using OpenTofu' do + it 'runs convox with a PATH where terraform is tofu' do + context.terraform_binary = '/opt/tofu/bin/tofu' + outputs = {} + executor.on('/opt/tofu/bin/tofu', 'output', '-json') { JSON.generate(outputs) } + executor.on('convox', 'rack', 'install') do |call| + shim = call.env.fetch('PATH').split(File::PATH_SEPARATOR).first + expect(File.readlink(File.join(shim, 'terraform'))).to eq '/opt/tofu/bin/tofu' + create_rack_dir('test-rack') + outputs = installed_outputs + '' + end + + client.install_convox + end end end describe '#validate_convox_rack_and_write_current!' do - it 'requires the correct config vars' do - client = described_class.new - expect do - client.validate_convox_rack_and_write_current! - end.to raise_error('aws_region is missing from the config!') + it 'switches to the rack' do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + executor.on('convox', 'switch', 'test-rack') { "Switched to test-rack\n" } + + expect(client.validate_convox_rack_and_write_current!).to eq 'test-rack' + expect(executor.commands).to include 'convox switch test-rack' + end + + it 'skips when the rack is already current' do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + File.write(File.join(ENV.fetch('CONVOX_CONFIG'), 'current'), '{"name":"test-rack","type":"terraform"}') + + client.validate_convox_rack_and_write_current! + expect(executor.calls_matching('convox', 'switch')).to be_empty + end + + it 'fails when the rack is not installed' do + expect { client.validate_convox_rack_and_write_current! } + .to raise_error(ConvoxInstaller::PreconditionFailed, /Could not find rack terraform directory/) + end + end + + describe '#validate_convox_rack_api!' do + before do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + end + + it 'checks the provider and name' do + executor.on('convox', 'api', 'get', '/system') do + JSON.generate(provider: 'aws', name: 'test-rack', version: '3.26.0') + end + expect(client.validate_convox_rack_api!).to be true + end + + it 'fails when the rack is a different one' do + executor.on('convox', 'api', 'get', '/system') { JSON.generate(provider: 'aws', name: 'other') } + expect { client.validate_convox_rack_api! } + .to raise_error(ConvoxInstaller::PreconditionFailed, /Expected name to be 'test-rack', but was: 'other'/) + end + + it 'waits for the API to answer' do + attempts = 0 + executor.on('convox', 'api', 'get', '/system') do + attempts += 1 + attempts < 3 ? ['', 'connection refused', 1] : JSON.generate(provider: 'aws', name: 'test-rack') + end + allow(client).to receive(:pause) + + client.validate_convox_rack_api! + expect(client).to have_received(:pause).with(5).twice + end + end + + describe '#create_convox_app!' do + before do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + end + + it 'creates the app when it does not exist' do + apps = [] + executor.on('convox', 'api', 'get', '/apps') { JSON.generate(apps) } + executor.on('convox', 'apps', 'create', 'myapp') do + apps << { name: 'myapp' } + '' + end + + client.create_convox_app! + expect(executor.commands).to include 'convox apps create myapp --rack test-rack' + end + + it 'skips an existing app' do + executor.on('convox', 'api', 'get', '/apps') { JSON.generate([{ name: 'myapp' }]) } + client.create_convox_app! + expect(executor.calls_matching('convox', 'apps', 'create')).to be_empty + end + end + + describe '#set_default_app_for_directory!' do + it 'writes ./.convox/app' do + Dir.mktmpdir do |dir| + Dir.chdir(dir) do + client.set_default_app_for_directory! + expect(File.read('.convox/app')).to eq "myapp\n" + client.set_default_app_for_directory! + expect(step_events.last).to include('status' => 'skipped') + end + end + end + end + + describe '#add_docker_registry!' do + before do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + config.merge!(docker_registry_url: 'registry.example.com', docker_registry_username: 'user', + docker_registry_password: 'registry-password-value') + end + + it 'adds the registry and masks the password in logs' do + context.masker.add('registry-password-value') + executor.on('convox', 'api', 'get', '/registries') { '[]' } + executor.on('convox', 'registries', 'add') { '' } + + client.add_docker_registry! + + expect(executor.commands).to include( + 'convox registries add registry.example.com user registry-password-value --rack test-rack' + ) + expect(human_output(context)).not_to include 'registry-password-value' + end + + it 'skips a registry that is already added' do + executor.on('convox', 'api', 'get', '/registries') { JSON.generate([{ server: 'registry.example.com' }]) } + client.add_docker_registry! + expect(executor.calls_matching('convox', 'registries', 'add')).to be_empty + end + end + + describe '#set_convox_env!' do + before do + create_rack_dir('test-rack') + @tf_outputs = installed_outputs + executor.on('convox', 'env', '--app') { "KEEP=same\nCHANGE=old\n" } + end + + it 'sends only the changed values, on stdin, and returns their names' do + executor.on('convox', 'env', 'set') { '' } + + changed = client.set_convox_env!({ 'KEEP' => 'same', 'CHANGE' => 'new', 'ADMIN_PASSWORD' => 'super-secret-pw' }, + promote: true) + + expect(changed).to eq %w[ADMIN_PASSWORD CHANGE] + set = executor.calls_matching('convox', 'env', 'set').first + expect(set.argv).to eq %w[convox env set --app myapp --rack test-rack --promote] + expect(set.stdin_data).to eq "ADMIN_PASSWORD=super-secret-pw\nCHANGE=new\n" + expect(events(context).to_s).not_to include 'super-secret-pw' + end + + it 'skips when nothing changed' do + expect(client.set_convox_env!('KEEP' => 'same')).to eq [] + expect(executor.calls_matching('convox', 'env', 'set')).to be_empty + end + end + + describe '#capture_convox_command!' do + it 'returns the command output, run with --rack' do + executor.on('convox', 'build') { "RABCDEFGHIJ\n" } + expect(client.capture_convox_command!('build --id')).to eq "RABCDEFGHIJ\n" + expect(executor.calls_matching('convox', 'build').first.argv).to eq %w[convox build --id --rack test-rack] + end + + it 'raises StepFailed with the command error output' do + executor.on('convox', 'build') { ['', 'ERROR: no such app', 1] } + expect { client.capture_convox_command!('build --id') } + .to raise_error(ConvoxInstaller::StepFailed, /convox build --id --rack test-rack.*no such app/) + end + + context 'when planning' do + let(:command) { :plan } + + it 'reports the command and runs nothing' do + expect(client.capture_convox_command!('build --id')).to be_nil + expect(executor.calls_matching('convox')).to be_empty + expect(events(context).find { |e| e['event'] == 'would_run' }['command']) + .to eq 'convox build --id --rack test-rack' + end + end + end + + describe '#run_convox_command!' do + it 'runs the command with --rack, without a shell' do + executor.on('convox', 'env', 'set') { '' } + client.run_convox_command!('env set FOO="bar baz"') + expect(executor.calls_matching('convox', 'env', 'set').first.argv) + .to eq ['convox', 'env', 'set', 'FOO=bar baz', '--rack', 'test-rack'] + end + + it 'raises StepFailed when the command fails' do + executor.on('convox', 'deploy') { 1 } + expect { client.run_convox_command!('deploy') }.to raise_error(ConvoxInstaller::StepFailed, /convox deploy/) + end + + context 'when planning' do + let(:command) { :plan } + + it 'reports the command and runs nothing' do + expect(client.run_convox_command!('env set SECRET_KEY_BASE=abcdef123456')).to be_nil + expect(executor.calls_matching('convox')).to be_empty + event = events(context).find { |e| e['event'] == 'would_run' } + expect(event['command']).to eq 'convox env set SECRET_KEY_BASE=[hidden] --rack test-rack' + end + end + end + + describe 'Terraform resources' do + let(:rack_dir) { create_rack_dir('test-rack') } + + before do + rack_dir + @tf_outputs = installed_outputs + config.merge!(s3_bucket_name: 'docs-1234', database_username: 'app', database_password: 'db-password-value') + end + + def tf_file(name) + File.read(File.join(rack_dir, name)) + end + + it 'writes current S3 resources for a new bucket, with CORS from a cors_rule block' do + config[:s3_bucket_cors_rule] = + " cors_rule {\n allowed_methods = [\"GET\"]\n allowed_origins = [\"*\"]\n }" + + client.add_s3_bucket + + s3 = tf_file('s3_bucket.tf') + expect(s3).to include 'bucket = "test-rack-docs-1234"' + %w[aws_s3_bucket_public_access_block aws_s3_bucket_ownership_controls + aws_s3_bucket_server_side_encryption_configuration aws_s3_bucket_versioning + aws_s3_bucket_lifecycle_configuration aws_s3_bucket_cors_configuration].each do |resource| + expect(s3).to include "resource \"#{resource}\" \"docs_s3_bucket\"" + end + expect(s3).to include 'status = "Enabled"' + expect(s3).to include 'allowed_methods = ["GET"]' + expect(s3).not_to include 'acl =' + expect(tf_file('convox_installer.tf')).to include 'region = "us-west-2"' + expect(File.stat(File.join(rack_dir, 's3_bucket.tf')).mode & 0o777).to eq 0o600 + end + + it 'renders CORS rules given as a list of hashes' do + config[:s3_bucket_cors_rule] = [{ 'allowed_methods' => %w[PUT POST], 'allowed_origins' => ['https://x.test'], + 'max_age_seconds' => 3000 }] + client.add_s3_bucket + expect(tf_file('s3_bucket.tf')).to include 'allowed_methods = ["PUT", "POST"]' + expect(tf_file('s3_bucket.tf')).to include 'max_age_seconds = 3000' + end + + it 'keeps an existing unversioned bucket as it is' do + @tf_resources = [terraform_resource('aws_s3_bucket', 'docs_s3_bucket', + 'bucket' => 'test-rack-docs-1234', 'versioning' => [{ 'enabled' => false }])] + client.add_s3_bucket + s3 = tf_file('s3_bucket.tf') + expect(s3).to include 'status = "Disabled"' + expect(s3).not_to include 'aws_s3_bucket_ownership_controls' + expect(s3).not_to include 'aws_s3_bucket_lifecycle_configuration' + expect(s3).not_to include 'aws_s3_bucket_cors_configuration' + end + + it 'writes an encrypted Postgres 17 database for a new install' do + client.add_rds_database + rds = tf_file('rds.tf') + expect(rds).to include 'identifier = "test-rack-rds-ab12cd34"' + expect(rds).to include 'engine_version = "17"' + expect(rds).to include 'storage_encrypted = true' + expect(rds).to include 'storage_type = "gp3"' + expect(rds).to include 'deletion_protection = true' + expect(rds).to include 'password = "db-password-value"' + expect(rds).to include 'cidr_blocks = [data.aws_vpc.convox_installer_rack.cidr_block]' + end + + it 'generates and saves a database password when none is set' do + config.delete(:database_password) + saved = {} + client = described_class.new(context: context, config: config, on_config_change: ->(k, v) { saved[k] = v }) + client.add_rds_database + expect(config[:database_password]).to match(/\A\h{32}\z/) + expect(saved).to eq(database_password: config[:database_password]) + end + + it 'keeps the running engine version and settings of an existing database' do + @tf_resources = [terraform_resource('aws_db_instance', 'rds_database', + 'engine' => 'postgres', 'engine_version' => '15.7', + 'instance_class' => 'db.t3.medium', 'allocated_storage' => 50, + 'storage_type' => 'gp2', 'storage_encrypted' => false, + 'multi_az' => true, 'backup_retention_period' => 1, 'username' => 'app')] + executor.on('aws', 'rds', 'describe-db-instances') { "15.12\n" } + + client.add_rds_database + + rds = tf_file('rds.tf') + expect(rds).to include 'engine_version = "15.12"' + expect(rds).to include 'instance_class = "db.t3.medium"' + expect(rds).to include 'allocated_storage = 50' + expect(rds).to include 'storage_type = "gp2"' + expect(rds).to include 'storage_encrypted = false' + expect(rds).to include 'backup_retention_period = 1' + end + + it 'refuses a setting that would replace an existing database' do + @tf_resources = [terraform_resource('aws_db_instance', 'rds_database', 'storage_encrypted' => false)] + config[:database_storage_encrypted] = 'true' + expect { client.add_rds_database }.to raise_error(ConvoxInstaller::PreconditionFailed, /would replace/) + end + + it 'writes a Redis replication group with TLS and AUTH for a new install' do + client.add_elasticache_cluster + redis = tf_file('elasticache.tf') + expect(redis).to include 'resource "aws_elasticache_replication_group" "redis"' + expect(redis).to include 'replication_group_id = "test-rack-redis-ab12cd34"' + expect(redis).to include 'transit_encryption_enabled = true' + expect(redis).to include "auth_token = \"#{config[:elasticache_auth_token]}\"" + expect(config[:elasticache_auth_token]).to match(/\A\h{64}\z/) + end + + it 'keeps the 3.x cluster when it exists' do + @tf_resources = [terraform_resource('aws_elasticache_cluster', 'elasticache_cluster', + 'engine' => 'redis', 'engine_version' => '7.1', + 'node_type' => 'cache.t3.small', 'num_cache_nodes' => 1, 'port' => 6379)] + client.add_elasticache_cluster + redis = tf_file('elasticache.tf') + expect(redis).to include 'resource "aws_elasticache_cluster" "elasticache_cluster"' + expect(redis).to include 'cluster_id = "test-rack-elasticache-ab12cd34"' + expect(redis).to include 'node_type = "cache.t3.small"' + expect(config).not_to have_key(:elasticache_auth_token) + end + + it 'skips writing files that are unchanged' do + client.add_rds_database + client.add_rds_database + expect(step_events.last).to include('step' => 'terraform_rds_database', 'status' => 'skipped') + end + + context 'when planning' do + let(:command) { :plan } + + it 'reports the files and resources without writing them' do + client.add_rds_database + expect(File.exist?(File.join(rack_dir, 'rds.tf'))).to be false + expect(step_events.last).to include( + 'step' => 'terraform_rds_database', 'status' => 'pending', 'action' => 'create', + 'files' => ['convox_installer.tf', 'rds.tf'], 'resources' => { 'aws_db_instance.rds_database' => 'missing' } + ) + end + end + + describe '#apply_terraform_update!' do + it 'plans, then applies the saved plan' do + executor.on('/usr/bin/terraform', 'plan') { 2 } + executor.on('/usr/bin/terraform', 'apply') { '' } + + client.apply_terraform_update! + + plan = executor.calls_matching('/usr/bin/terraform', 'plan').first + plan_file = plan.argv.find { |a| a.start_with?('-out=') }.delete_prefix('-out=') + expect(plan.argv).to include('-detailed-exitcode', '-input=false') + expect(plan.chdir).to eq rack_dir + expect(executor.calls_matching('/usr/bin/terraform', 'apply').first.argv.last).to eq plan_file + expect(step_events.last).to include('step' => 'terraform_apply', 'status' => 'done') + end + + it 'skips the apply when there are no changes' do + executor.on('/usr/bin/terraform', 'plan') { 0 } + client.apply_terraform_update! + expect(executor.calls_matching('/usr/bin/terraform', 'apply')).to be_empty + expect(step_events.last).to include('status' => 'skipped') + end + + it 'fails when the plan fails' do + executor.on('/usr/bin/terraform', 'plan') { 1 } + expect { client.apply_terraform_update! }.to raise_error(ConvoxInstaller::StepFailed, 'terraform plan failed') + end + + it 'stops when a 3.x s3_bucket.tf still configures the provider' do + File.write(File.join(rack_dir, 's3_bucket.tf'), "provider \"aws\" {\n region = \"us-west-2\"\n}\n") + expect { client.apply_terraform_update! }.to raise_error(ConvoxInstaller::PreconditionFailed, /s3_bucket.tf/) + end + end + + describe 'resource details' do + before do + @tf_resources = [ + terraform_resource('aws_s3_bucket', 'docs_s3_bucket', 'bucket' => 'test-rack-docs-1234'), + terraform_resource('aws_iam_access_key', 'docspring_user_access_key', + 'id' => 'AKIAAPP', 'secret' => 'app-secret-key-value'), + terraform_resource('aws_db_instance', 'rds_database', + 'username' => 'app', 'password' => 'p@ss/word', 'endpoint' => 'db.example:5432', + 'address' => 'db.example', 'port' => 5432), + terraform_resource('aws_elasticache_replication_group', 'redis', + 'primary_endpoint_address' => 'redis.example', 'port' => 6379, + 'transit_encryption_enabled' => true, 'auth_token' => 'redis-token-value') + ] + end + + it 'returns the S3 bucket and its access key' do + expect(client.s3_bucket_details).to eq(access_key_id: 'AKIAAPP', secret_access_key: 'app-secret-key-value', + name: 'test-rack-docs-1234') + end + + it 'returns a Postgres URL with the credentials encoded' do + expect(client.rds_details[:postgres_url]).to eq 'postgres://app:p%40ss%2Fword@db.example:5432/app' + end + + it 'returns a TLS Redis URL with the auth token' do + expect(client.elasticache_details[:redis_url]).to eq 'rediss://:redis-token-value@redis.example:6379/0' + end + + it 'returns a plain Redis URL for the 3.x cluster' do + @tf_resources = [terraform_resource('aws_elasticache_cluster', 'elasticache_cluster', + 'cache_nodes' => [{ 'address' => 'old.example', 'port' => 6379 }])] + expect(client.elasticache_details[:redis_url]).to eq 'redis://old.example:6379/0' + end + + it 'explains what to do when a resource does not exist yet' do + @tf_resources = [] + expect do + client.rds_details + end.to raise_error(ConvoxInstaller::PreconditionFailed, /aws_db_instance.rds_database/) + end + + context 'when planning' do + let(:command) { :plan } + + it 'raises NotYetAvailable for a missing resource' do + @tf_resources = [] + expect { client.rds_details }.to raise_error(ConvoxInstaller::NotYetAvailable) + end + end + end + + it 'finds the default service domain from the rack API URL' do + expect(client.default_service_domain_name).to eq 'web.myapp.abc123def456.convox.cloud' end end end diff --git a/spec/lib/convox_installer/aws_session_spec.rb b/spec/lib/convox_installer/aws_session_spec.rb new file mode 100644 index 0000000..14f3f1b --- /dev/null +++ b/spec/lib/convox_installer/aws_session_spec.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::AwsSession do + let(:executor) { FakeExecutor.new } + let(:context) { build_context(executor: executor) } + let(:config) { { aws_region: 'eu-west-1' } } + let(:session) { described_class.new(context: context, config: config) } + + before { stub_aws(executor) } + + it 'resolves the credential chain into environment variables' do + expect(session.env).to eq( + 'AWS_REGION' => 'eu-west-1', + 'AWS_DEFAULT_REGION' => 'eu-west-1', + 'AWS_ACCESS_KEY_ID' => 'ASIAEXAMPLE', + 'AWS_SECRET_ACCESS_KEY' => 'exported-secret-key-value', + 'AWS_SESSION_TOKEN' => 'exported-session-token-value' + ) + session.env + expect(executor.calls_matching('aws', 'configure', 'export-credentials').length).to eq 1 + end + + it 'passes the profile to the AWS CLI' do + config[:aws_profile] = 'customer-sso' + session.env + expect(executor.calls_matching('aws', 'configure').first.env).to include('AWS_PROFILE' => 'customer-sso') + expect(session.credential_source).to eq 'AWS CLI credential chain (profile customer-sso)' + end + + it 'masks the exported secrets' do + session.env + expect(context.masker.mask('key exported-secret-key-value')).to eq 'key [hidden]' + end + + it 'refreshes credentials that are about to expire' do + executor.on('aws', 'configure', 'export-credentials') do + JSON.generate(AccessKeyId: 'ASIA1', SecretAccessKey: 'secret-one-value', SessionToken: 'token-one-value', + Expiration: (Time.now + 60).utc.iso8601) + end + session.env + session.env + expect(executor.calls_matching('aws', 'configure').length).to eq 2 + end + + it 'reports the account and principal' do + expect(session.identity).to eq(account: '123456789012', arn: 'arn:aws:sts::123456789012:assumed-role/Admin/me', + user_id: 'AROAEXAMPLE:me') + expect(session.summary_lines.map(&:first)).to eq ['AWS Account', 'AWS Principal', 'AWS Credentials'] + end + + it 'explains how to sign in when there are no credentials' do + executor.on('aws', 'configure', 'export-credentials') do + ['', 'Error when retrieving token from sso: Token has expired and refresh failed', 255] + end + config[:aws_profile] = 'prod' + expect { session.env }.to raise_error(ConvoxInstaller::PreconditionFailed) do |error| + expect(error.message).to include 'Token has expired' + expect(error.next_step).to include 'aws sso login --profile prod' + end + end + + it 'stops when the credentials are for a different account' do + expect { session.verify_account!('999999999999') } + .to raise_error(ConvoxInstaller::PreconditionFailed, /belong to account 123456789012.*uses account 999999999999/) + expect { session.verify_account!('123456789012') }.not_to raise_error + end +end diff --git a/spec/lib/convox_installer/config_spec.rb b/spec/lib/convox_installer/config_spec.rb index 00c61fc..8f5e4fa 100644 --- a/spec/lib/convox_installer/config_spec.rb +++ b/spec/lib/convox_installer/config_spec.rb @@ -1,237 +1,230 @@ # frozen_string_literal: true -require 'convox_installer' +require 'spec_helper' require 'securerandom' RSpec.describe ConvoxInstaller::Config do - before do - stub_const('ConvoxInstaller::Config::CONFIG_FILE', '/path/to/.installer_config.json') - end - - after do - ENV.delete 'AWS_REGION' - ENV.delete 'AWS_ACCESS_KEY_ID' - end - - it 'loads the saved config from ./.installer_config.json' do - expect(described_class).to receive(:config_file_exists?).and_return(true) - expect(described_class).to receive(:read_config_file).and_return( - '{ "config": { "aws_region": "us-west-2", "aws_access_key_id": "1234" } }' - ) - config = described_class.new - - expect(config.config).to eq( - aws_region: 'us-west-2', - aws_access_key_id: '1234' - ) - end - - it 'loads config from ENV vars' do - expect(described_class).to receive(:config_file_exists?).and_return(false) - ENV['AWS_REGION'] = 'us-east-1' - ENV['AWS_ACCESS_KEY_ID'] = '2345' - - config = described_class.new - expect(config.config).to eq( - aws_region: 'us-east-1', - aws_access_key_id: '2345' - ) - end - - it 'prompts the user for their AWS details, and re-prompts to correct mistakes' do - expect(described_class).to receive(:config_file_exists?).and_return(false) - input = StringIO.new - output = StringIO.new - highline = HighLine.new(input, output) - - input_details = [ - [:stack_name, ''], - [:aws_region, ''], - [:instance_type, 'c5.xlarge'], - [:aws_access_key_id, 'asdf'], - [:aws_secret_access_key, 'xkcd'], - [:confirm?, 'n'], - [:stack_name, 'convox-test'], - [:aws_region, 'us-north-12'], - [:instance_type, 't3.medium'], - [:aws_access_key_id, 'sdfg'], - [:aws_secret_access_key, ''], - [:confirm?, 'y'] - ] - input << input_details.map(&:last).join("\n") << "\n" + let(:dir) { Dir.mktmpdir('installer-config-') } + let(:path) { File.join(dir, '.installer_config.json') } + let(:settings) { {} } + let(:assume_yes) { false } + let(:context) { build_context(settings: settings, assume_yes: assume_yes, config_path: path) } + let(:input) { StringIO.new } + let(:output) { StringIO.new } + let(:highline) { HighLine.new(input, output) } + + after { FileUtils.rm_rf(dir) } + + def build(env: {}, interactive: true, prompts: nil, **options) + described_class.new(context: context, env: env, interactive: interactive, highline: highline, + prompts: prompts || described_class::DEFAULT_PROMPTS, **options) + end + + def answer(*lines) + input << lines.join("\n") << "\n" input.rewind + end - config = described_class.new(highline: highline) - expect(config).to receive(:save_config_to_file).exactly(10).times + def saved + JSON.parse(File.read(path)) + end - expect(config.config).to eq({}) - config.prompt_for_config - expect(config.config).to eq( - stack_name: 'convox-test', - aws_region: 'us-north-12', - aws_access_key_id: 'sdfg', - aws_secret_access_key: 'xkcd', - instance_type: 't3.medium' - ) - output.rewind - stripped_output = output.read.lines.map(&:rstrip).join("\n") - expected_output = <<~CONVOX_INSTALLER_OUTPUT - Please enter a name for your Convox installation |convox| - Please enter your AWS Region: |us-east-1| Please enter your EC2 Instance Type: |t3.medium| - Admin AWS Credentials - ============================================ + it 'loads the saved config from the config file' do + File.write(path, '{ "config": { "aws_region": "us-west-2", "stack_name": "saved" } }') + config = build + expect(config.config).to eq(aws_region: 'us-west-2', stack_name: 'saved') + expect(config.sources[:aws_region]).to eq :file + end - Please enter your AWS Access Key ID: Please enter your AWS Secret Access Key: - ============================================ - SUMMARY - ============================================ + it 'reads environment variables, the CONVOX_INSTALLER_ prefix first' do + File.write(path, '{ "config": { "aws_region": "us-west-2" } }') + env = { 'AWS_REGION' => 'eu-west-1', 'CONVOX_INSTALLER_STACK_NAME' => 'prefixed', 'STACK_NAME' => 'plain', + 'AWS_DEFAULT_REGION' => 'ap-south-1' } + config = build(env: env) + expect(config[:aws_region]).to eq 'eu-west-1' + expect(config[:stack_name]).to eq 'prefixed' + expect(config.sources[:stack_name]).to eq :'env:CONVOX_INSTALLER_STACK_NAME' + end - Convox Stack Name: convox - AWS Region: us-east-1 - EC2 Instance Type: c5.xlarge - AWS Access Key ID: asdf - AWS Secret Access Key: xkcd + context 'with flags' do + let(:settings) { { stack_name: 'from-flag' } } - We've saved your configuration to: /path/to/.installer_config.json - If anything goes wrong during the installation, you can restart the script to reload the config and continue. + it 'gives them precedence over the environment and the file' do + File.write(path, '{ "config": { "stack_name": "from-file" } }') + config = build(env: { 'STACK_NAME' => 'from-env' }) + expect(config[:stack_name]).to eq 'from-flag' + expect(config.sources[:stack_name]).to eq :flag + end + end - Please double check all of these configuration details. - Would you like to start the Convox installation? (press 'n' to correct any settings) + it 'reads prefixed environment variables for the gem settings that have no prompt' do + config = build(env: { 'CONVOX_INSTALLER_DATABASE_INSTANCE_CLASS' => 'db.t4g.small', 'AWS_PROFILE' => 'prod' }) + expect(config[:database_instance_class]).to eq 'db.t4g.small' + expect(config[:aws_profile]).to eq 'prod' + end - Please enter a name for your Convox installation |convox| - Please enter your AWS Region: |us-east-1| Please enter your EC2 Instance Type: |c5.xlarge| - Admin AWS Credentials - ============================================ + it 'ignores bare names for the gem settings, which other tools use' do + config = build(env: { 'DATABASE_PASSWORD' => 'another-projects-password', 'DATABASE_USERNAME' => 'someone' }) + expect(config[:database_password]).to be_nil + expect(config[:database_username]).to be_nil + end - Please enter your AWS Access Key ID: |asdf| Please enter your AWS Secret Access Key: |xkcd| - ============================================ - SUMMARY - ============================================ + it 'reads bare names for settings the script prompts for' do + config = build(env: { 'DATABASE_USERNAME' => 'from-env' }, prompts: [{ key: :database_username }]) + expect(config[:database_username]).to eq 'from-env' + end - Convox Stack Name: convox-test - AWS Region: us-north-12 - EC2 Instance Type: t3.medium - AWS Access Key ID: sdfg - AWS Secret Access Key: xkcd - - We've saved your configuration to: /path/to/.installer_config.json - If anything goes wrong during the installation, you can restart the script to reload the config and continue. - - Please double check all of these configuration details. - Would you like to start the Convox installation? (press 'n' to correct any settings) - CONVOX_INSTALLER_OUTPUT - - # puts stripped_output - # puts "---------------" - # puts expected_output - expect(stripped_output).to eq expected_output.strip - end - - it 'prompts for custom configuration' do - expect(described_class).to receive(:config_file_exists?).and_return(false) - input = StringIO.new - output = StringIO.new - highline = HighLine.new(input, output) - - custom_prompts = ConvoxInstaller::Config::DEFAULT_PROMPTS + [ - { - section: 'ECR Authentication', - info: "You should have received authentication details for the Docker Registry\n" \ - 'via email. If not, please contact support@example.com' - }, - { - key: :docker_registry_username, - title: 'Docker Registry Access Key ID' - }, - { - key: :docker_registry_password, - title: 'Docker Registry Secret Access Key' - }, - { - key: :admin_email, - title: 'Admin Email', - prompt: 'Please enter the email address you would like to use ' \ - 'for the default admin user', - default: 'admin@example.com' - }, - { - key: :admin_password, - title: 'Admin Password', - value: ->(_c) { SecureRandom.hex(8) } - } - ] + it 'explains an invalid config file' do + File.write(path, '{ not json') + expect { build }.to raise_error(ConvoxInstaller::PreconditionFailed, /not valid JSON/) + end - input_details = [ - [:stack_name, ''], - [:aws_region, ''], - [:instance_type, 'c5.xlarge'], - [:aws_access_key_id, 'asdf'], - [:aws_secret_access_key, 'xkcd'], - [:docker_registry_username, 'bob'], - [:docker_registry_password, 'password1'], - [:admin_email, 'admin@test.com'], - [:confirm?, 'y'] - ] - input << input_details.map(&:last).join("\n") << "\n" - input.rewind + describe 'non-interactive runs' do + let(:assume_yes) { true } + let(:secret_env) do + { 'DOCKER_REGISTRY_PASSWORD' => 'registry-pw-value', 'DOCSPRING_LICENSE' => 'license-value-1234' } + end + let(:prompts) do + described_class::DEFAULT_PROMPTS + [ + { key: :docker_registry_password, title: 'Docker Registry Password' }, + { key: :docspring_license, title: 'License' }, + { key: :admin_password, value: -> { 'generated-admin-pw' } } + ] + end + + it 'uses defaults and generated values, and lists the missing settings' do + config = build(interactive: false, prompts: prompts) + expect { config.prompt_for_config }.to raise_error(ConvoxInstaller::MissingInput) do |error| + expect(error.missing).to eq %w[docker_registry_password docspring_license] + expect(error.exit_code).to eq 2 + expect(error.message).to eq 'Missing settings: docker_registry_password, docspring_license.' + expect(error.next_step).to include '--docker-registry-password VALUE (or DOCKER_REGISTRY_PASSWORD=VALUE)' + end + expect(config.config).to include(stack_name: 'convox', aws_region: 'us-east-1', instance_type: 't3.medium', + admin_password: 'generated-admin-pw') + expect(config.sources[:stack_name]).to eq :default + end + + it 'starts without asking when everything is set' do + config = build(interactive: false, prompts: prompts, + env: secret_env) + expect(config.prompt_for_config).to include(docker_registry_password: 'registry-pw-value') + end + + it 'reports invalid values' do + config = build(interactive: false, env: { 'STACK_NAME' => 'Bad_Name', 'AWS_REGION' => 'nowhere' }) + expect { config.prompt_for_config }.to raise_error(ConvoxInstaller::MissingInput) do |error| + expect(error.invalid.keys).to eq %w[stack_name aws_region] + expect(error.message).to include 'stack_name must start with a lowercase letter' + end + end + + it 'emits the settings with secrets masked' do + config = build(interactive: false, prompts: prompts, + env: secret_env) + config.prompt_for_config + event = events(context).find { |e| e['event'] == 'config' } + expect(event['settings']).to include('stack_name' => 'convox', 'docker_registry_password' => '[hidden]', + 'docspring_license' => '[hidden]') + expect(event['sources']).to include('docker_registry_password' => 'env:DOCKER_REGISTRY_PASSWORD') + expect(events(context).to_s).not_to include('registry-pw-value') + end + end + + context 'when not interactive and not told to start' do + it 'asks for --yes instead of prompting' do + config = build(interactive: false) + expect { config.prompt_for_config }.to raise_error(ConvoxInstaller::MissingInput) do |error| + expect(error.missing).to eq ['confirmation'] + expect(error.next_step).to include '--yes' + end + end + + it 'needs no confirmation for plan and status' do + config = build(interactive: false) + expect(config.prompt_for_config(confirm: false)).to include(stack_name: 'convox') + end + end - config = described_class.new(highline: highline, prompts: custom_prompts) - expect(config).to receive(:save_config_to_file).exactly(9).times - expect(SecureRandom).to receive(:hex).with(8).and_return('99a6f67de0c7a117') + it 'prompts for the settings, and re-prompts to correct mistakes' do + answer('', '', 'c5.xlarge', 'n', 'convox-test', 'us-north-1', 't3.medium', 'y') + allow(SecureRandom).to receive(:hex).with(4).and_return('a1b2c3d4') + config = build expect(config.config).to eq({}) + config.prompt_for_config(summary: ->(_c) { [['AWS Account', '123456789012']] }) + + expect(config.config).to eq(stack_name: 'convox-test', aws_region: 'us-north-1', instance_type: 't3.medium', + random_id: 'a1b2c3d4') + stripped_output = output.string.lines.map(&:rstrip).join("\n") + expect(stripped_output).to include <<~TEXT.strip + SUMMARY + ============================================ + + AWS Account: 123456789012 + Convox Stack Name: convox + AWS Region: us-east-1 + EC2 Instance Type: c5.xlarge + TEXT + expect(stripped_output).to include 'Convox Stack Name: convox-test' + expect(stripped_output).to include "We've saved your configuration to: #{path}" + expect(stripped_output.scan('Would you like to start the Convox installation?').length).to eq 2 + expect(saved).to eq('convox_installer_version' => ConvoxInstaller::VERSION, + 'config' => config.config.transform_keys(&:to_s)) + expect(File.stat(path).mode & 0o777).to eq 0o600 + end + it 'prompts for custom settings and masks secrets in the summary' do + custom_prompts = described_class::DEFAULT_PROMPTS + [ + { section: 'ECR Authentication', info: 'You should have received these by email.' }, + { key: :docker_registry_username, title: 'Docker Registry Access Key ID' }, + { key: :docker_registry_password, title: 'Docker Registry Secret Access Key' }, + { key: :admin_email, title: 'Admin Email', prompt: 'Admin email address', default: 'admin@example.com' }, + { key: :admin_password, title: 'Admin Password', value: ->(_c) { SecureRandom.hex(8) } } + ] + answer('', '', '', 'bob', 'registry-secret-1234567890', '', 'y') + allow(SecureRandom).to receive(:hex).and_call_original + allow(SecureRandom).to receive(:hex).with(8).and_return('99a6f67de0c7a117') + + config = build(prompts: custom_prompts) config.prompt_for_config - expect(config.config).to eq( - stack_name: 'convox', - aws_region: 'us-east-1', - aws_access_key_id: 'asdf', - aws_secret_access_key: 'xkcd', - instance_type: 'c5.xlarge', - docker_registry_username: 'bob', - docker_registry_password: 'password1', - admin_email: 'admin@test.com', - admin_password: '99a6f67de0c7a117' - ) - output.rewind - stripped_output = output.read.lines.map(&:rstrip).join("\n") - expected_output = <<~CONVOX_INSTALLER_OUTPUT - Please enter a name for your Convox installation |convox| - Please enter your AWS Region: |us-east-1| Please enter your EC2 Instance Type: |t3.medium| - Admin AWS Credentials - ============================================ + expect(config.config).to include(docker_registry_username: 'bob', + docker_registry_password: 'registry-secret-1234567890', + admin_email: 'admin@example.com', admin_password: '99a6f67de0c7a117') + expect(output.string).to include 'ECR Authentication' + expect(output.string).to include 'You should have received these by email.' + expect(output.string).to include 'Docker Registry Secret Access Key: ********7890' + expect(output.string).to include 'Admin Password: ********a117' + expect(output.string).not_to include 'registry-secret-1234567890' + end - Please enter your AWS Access Key ID: Please enter your AWS Secret Access Key: - ECR Authentication - ============================================ + it 'stops with exit code 5 when the input ends at a prompt' do + answer('') + input.truncate(0) + config = build + expect { config.prompt_for_config }.to raise_error(ConvoxInstaller::Cancelled) { |e| expect(e.exit_code).to eq 5 } + end - Please enter your Docker Registry Access Key ID: Please enter your Docker Registry Secret Access Key: Please enter the email address you would like to use for the default admin user |admin@example.com| + it 'keeps AWS credentials from the environment out of the file' do + config = build(env: { 'AWS_ACCESS_KEY_ID' => 'AKIAENV', 'AWS_SECRET_ACCESS_KEY' => 'env-secret-value' }) + config[:stack_name] = 'saved' + expect(saved['config']).to eq('stack_name' => 'saved') + expect(config[:aws_secret_access_key]).to eq 'env-secret-value' + end - ============================================ - SUMMARY - ============================================ + it 'keeps AWS credentials that were already in the file (3.x installs)' do + File.write(path, '{ "config": { "aws_access_key_id": "AKIAOLD", "aws_secret_access_key": "old-secret" } }') + config = build + config[:stack_name] = 'saved' + expect(saved['config']).to include('aws_access_key_id' => 'AKIAOLD', 'aws_secret_access_key' => 'old-secret') + end - Convox Stack Name: convox - AWS Region: us-east-1 - EC2 Instance Type: c5.xlarge - AWS Access Key ID: asdf - AWS Secret Access Key: xkcd - Docker Registry Access Key ID: bob - Docker Registry Secret Access Key: password1 - Admin Email: admin@test.com - Admin Password: 99a6f67de0c7a117 - - We've saved your configuration to: /path/to/.installer_config.json - If anything goes wrong during the installation, you can restart the script to reload the config and continue. - - Please double check all of these configuration details. - Would you like to start the Convox installation? (press 'n' to correct any settings) - CONVOX_INSTALLER_OUTPUT - - # puts stripped_output - # puts "---------------" - # puts expected_output - expect(stripped_output).to eq expected_output.strip + it 'treats keys that look like secrets as secrets, unless a prompt says otherwise' do + config = build(prompts: [{ key: :public_token, secret: false }, { key: :plain }]) + expect(config.secret?(:public_token)).to be false + expect(config.secret?(:admin_password)).to be true + expect(config.secret?(:docspring_license)).to be true + expect(config.secret?(:plain)).to be false end end diff --git a/spec/lib/convox_installer/masker_spec.rb b/spec/lib/convox_installer/masker_spec.rb new file mode 100644 index 0000000..037c11e --- /dev/null +++ b/spec/lib/convox_installer/masker_spec.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::Masker do + let(:masker) { described_class.new } + + it 'masks registered secrets' do + masker.add('hunter2-password') + expect(masker.mask('the password is hunter2-password')).to eq 'the password is [hidden]' + end + + it 'ignores very short values' do + masker.add('ab') + expect(masker.mask('tab')).to eq 'tab' + end + + it 'masks credentials in URLs' do + expect(masker.mask('DATABASE_URL is postgres://app:s3cr3t@db.example:5432/app')) + .to eq 'DATABASE_URL is postgres://app:[hidden]@db.example:5432/app' + expect(masker.mask('https://convox:token123@api.x.convox.cloud')).to eq 'https://convox:[hidden]@api.x.convox.cloud' + end + + it 'masks secret-looking assignments' do + expect(masker.mask('env set ADMIN_PASSWORD=abc SECRET_KEY_BASE="x y" NAME=ok')) + .to eq 'env set ADMIN_PASSWORD=[hidden] SECRET_KEY_BASE=[hidden] NAME=ok' + end + + it 'masks nested data' do + masker.add('top-secret-value') + expect(masker.mask_data({ a: ['top-secret-value', 1], b: { c: 'x top-secret-value' } })) + .to eq({ a: ['[hidden]', 1], b: { c: 'x [hidden]' } }) + end + + it 'shows the last four characters of long secrets in summaries' do + expect(described_class.display('0123456789abcdef1234')).to eq '********1234' + expect(described_class.display('short')).to eq '********' + expect(described_class.display('')).to eq '' + end +end diff --git a/spec/lib/convox_installer/options_spec.rb b/spec/lib/convox_installer/options_spec.rb new file mode 100644 index 0000000..1ebf078 --- /dev/null +++ b/spec/lib/convox_installer/options_spec.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::Options do + def parse(*argv, env: {}) + described_class.parse(argv, settings: { stack_name: 'Convox Stack Name', docspring_license: 'License' }, env: env, + program_name: 'install.rb') + end + + it 'defaults to install, interactive, human output' do + options = parse + expect(options.command).to eq :install + expect(options.json?).to be false + expect(options.assume_yes?).to be false + expect(options.dry_run?).to be false + end + + it 'parses the commands' do + expect(parse('apply').command).to eq :install + expect(parse('plan').command).to eq :plan + expect(parse('status').command).to eq :status + expect(parse('status').dry_run?).to be true + end + + it 'parses flags and settings' do + options = parse('plan', '--json', '--yes', '--config', '/tmp/x.json', '--stack-name', 'prod', + '--docspring-license', 'abc', '--set', 'database-instance-class=db.t4g.small', '--debug') + expect(options.json?).to be true + expect(options.assume_yes?).to be true + expect(options.config_path).to eq '/tmp/x.json' + expect(options.log_level).to eq Logger::DEBUG + expect(options.settings).to eq(stack_name: 'prod', docspring_license: 'abc', + database_instance_class: 'db.t4g.small') + end + + it 'has flags for the gem settings' do + expect(parse('--aws-profile', 'sso', '--terraform-binary', 'tofu').settings) + .to eq(aws_profile: 'sso', terraform_binary: 'tofu') + end + + it 'reads options from the environment' do + options = parse(env: { 'CONVOX_INSTALLER_NON_INTERACTIVE' => '1', 'CONVOX_INSTALLER_JSON' => 'true', + 'CONVOX_INSTALLER_CONFIG' => '/srv/config.json' }) + expect(options.assume_yes?).to be true + expect(options.json?).to be true + expect(options.config_path).to eq '/srv/config.json' + end + + it 'treats the 3.x AUTOSTART_CONVOX_INSTALLATION variable as --yes' do + expect(parse(env: { 'AUTOSTART_CONVOX_INSTALLATION' => '1' }).assume_yes?).to be true + end + + it 'rejects unknown options and commands with exit code 2' do + expect { parse('--nope') }.to raise_error(ConvoxInstaller::UsageError, /invalid option: --nope/) do |error| + expect(error.exit_code).to eq 2 + expect(error.next_step).to include 'ruby install.rb --help' + end + expect { parse('destroy') }.to raise_error(ConvoxInstaller::UsageError, /Unknown command: destroy/) + expect { parse('--set', 'novalue') }.to raise_error(ConvoxInstaller::UsageError, /KEY=VALUE/) + end + + it 'documents the settings, environment variables and exit codes in --help' do + help = parse.help_text + expect(help).to include '--stack-name VALUE', 'Convox Stack Name', '--aws-profile VALUE', 'CONVOX_INSTALLER_' + expect(help).to include '2 missing or invalid input, 3 precondition failed' + end +end diff --git a/spec/lib/convox_installer/platform_spec.rb b/spec/lib/convox_installer/platform_spec.rb new file mode 100644 index 0000000..09c3486 --- /dev/null +++ b/spec/lib/convox_installer/platform_spec.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::Platform do + it 'detects the operating system' do + expect(described_class.os('darwin24')).to eq :macos + expect(described_class.os('linux-gnu')).to eq :linux + expect(described_class.os('mingw32')).to eq :windows + end + + describe '.convox_config_dir' do + it 'uses CONVOX_CONFIG first' do + expect(described_class.convox_config_dir(env: { 'CONVOX_CONFIG' => '/srv/convox', 'XDG_CONFIG_HOME' => '/x' })) + .to eq '/srv/convox' + end + + it 'uses XDG_CONFIG_HOME on any OS' do + expect(described_class.convox_config_dir(env: { 'XDG_CONFIG_HOME' => '/home/me/.cfg' }, os: :macos)) + .to eq '/home/me/.cfg/convox' + end + + it 'uses ~/Library/Preferences/convox on macOS and ~/.config/convox on Linux' do + expect(described_class.convox_config_dir(env: {}, os: :macos)) + .to eq File.expand_path('~/Library/Preferences/convox') + expect(described_class.convox_config_dir(env: {}, os: :linux)).to eq File.expand_path('~/.config/convox') + end + end + + it 'gives install hints for each OS and CPU' do + expect(described_class.install_hint('convox', os: :linux, arm64: true)).to include 'convox-linux-arm64' + expect(described_class.install_hint('convox', os: :macos, arm64: false)).to include 'convox-macos -o' + expect(described_class.install_hint('aws', os: :macos)).to eq 'brew install awscli' + end +end diff --git a/spec/lib/convox_installer/requirements_spec.rb b/spec/lib/convox_installer/requirements_spec.rb index 281bd2e..710a2d1 100644 --- a/spec/lib/convox_installer/requirements_spec.rb +++ b/spec/lib/convox_installer/requirements_spec.rb @@ -1,115 +1,103 @@ # frozen_string_literal: true -require 'convox_installer' +require 'spec_helper' RSpec.describe ConvoxInstaller::Requirements do - let(:convox_cli_version) { '3.3.4' } + let(:executor) { FakeExecutor.new } + let(:context) { build_context(executor: executor) } + let(:convox_version) { '3.26.0' } + let(:terraform_version) { '1.13.4' } + let(:found) { { 'convox' => '/usr/local/bin/convox', 'aws' => '/usr/bin/aws', 'terraform' => '/usr/bin/terraform' } } + let(:requirements) { described_class.new(context: context) } before do - allow_any_instance_of( - Convox::Client - ).to receive(:cli_version_string).and_return(convox_cli_version) + executor.on('convox', '--version') { "#{convox_version}\n" } + executor.on('aws', '--version') { 'aws-cli/2.31.0 Python/3.13.0 Darwin/25.0.0 exe/arm64' } + executor.on('/usr/bin/terraform', 'version', '-json') { JSON.generate(terraform_version: terraform_version) } + executor.on('/usr/bin/tofu', 'version', '-json') { JSON.generate(terraform_version: '1.10.6') } + allow(requirements).to receive(:find_command) { |command| found[command] } end - context 'with no missing packages and correct CLI version' do - it 'does nothing' do - req = described_class.new - expect(req).to receive(:find_command).with('convox').and_return(true) - expect(req).to receive(:find_command).with('aws').and_return(true) - expect(req).not_to receive(:quit!) + it 'passes with convox 3, AWS CLI 2 and terraform 1.6 or later' do + expect(requirements.ensure_requirements!).to be true + expect(context.terraform_binary).to eq '/usr/bin/terraform' + end - expect(req.logger).not_to receive(:error) + it 'falls back to OpenTofu' do + found.delete('terraform') + found['tofu'] = '/usr/bin/tofu' + requirements.ensure_requirements! + expect(context.terraform_binary).to eq '/usr/bin/tofu' + end + it 'uses the terraform_binary setting' do + found['tofu'] = '/usr/bin/tofu' + described_class.new(context: context, terraform_binary: 'tofu').tap do |req| + allow(req).to receive(:find_command) { |command| found[command] } req.ensure_requirements! end + expect(context.terraform_binary).to eq '/usr/bin/tofu' end - context 'with Mac' do - context 'with two missing packages' do - it 'shows the correct error message and quit' do - expect(OS).to receive(:mac?).and_return(true) - - req = described_class.new - expect(req).to receive(:find_command).with('convox').and_return(false) - expect(req).to receive(:find_command).with('aws').and_return(false) - expect(req).to receive(:quit!) - - expect(req.logger).to receive(:error).with( - 'This script requires the convox and AWS CLI tools.' - ) - expect(req.logger).to receive(:error).with( - 'Please run: brew install convox awscli' - ) - - req.ensure_requirements! + context 'with missing tools on macOS' do + it 'lists them with Homebrew and download hints' do + allow(ConvoxInstaller::Platform).to receive(:os).and_return(:macos) + found.delete('convox') + found.delete('terraform') + + expect { requirements.ensure_requirements! }.to raise_error(ConvoxInstaller::PreconditionFailed) do |error| + expect(error.exit_code).to eq 3 + expect(error.message).to include 'Missing: convox, terraform.' + expect(error.next_step).to include 'releases/latest/download/convox-macos' + expect(error.next_step).to include 'brew install hashicorp/tap/terraform' + expect(error.next_step).to include 'brew install opentofu' end end + end - context 'with Convox CLI version 20210208170413' do - let(:convox_cli_version) { '20210208170413' } - - it 'shows the correct error message and quit' do - req = described_class.new - expect(req).to receive(:find_command).with('convox').and_return(true) - expect(req).to receive(:find_command).with('aws').and_return(true) - expect(req).to receive(:quit!) - - expect(req.logger).to receive(:error).with( - 'This script requires Convox CLI version 3.x.x. Your Convox CLI version is: 20210208170413' - ) - expect(req.logger).to receive(:error).with( - "Please run 'brew update convox' or follow the instructions at https://docs.convox.com/getting-started/introduction" - ) + context 'with missing tools on Linux' do + it 'gives Linux instructions' do + allow(ConvoxInstaller::Platform).to receive(:os).and_return(:linux) + found.delete('aws') - req.ensure_requirements! + expect { requirements.ensure_requirements! }.to raise_error(ConvoxInstaller::PreconditionFailed) do |error| + expect(error.next_step).to include 'aws: see https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html' end end + end - context 'with one missing packages' do - it 'shows the correct error message and quit' do - expect(OS).to receive(:mac?).and_return(true) + context 'with a Convox v2 CLI' do + let(:convox_version) { '20210208170413' } - req = described_class.new - expect(req).to receive(:find_command).with('convox').and_return(false) - expect(req).to receive(:find_command).with('aws').and_return(true) - expect(req).to receive(:quit!) + it 'explains that v3 is needed' do + expect { requirements.ensure_requirements! }.to raise_error( + ConvoxInstaller::PreconditionFailed, + 'This installer needs Convox CLI version 3.x.x. Your Convox CLI version is: "20210208170413"' + ) + end + end - expect(req.logger).to receive(:error).with( - 'This script requires the convox and AWS CLI tools.' - ) - expect(req.logger).to receive(:error).with( - 'Please run: brew install convox' - ) + context 'with a Convox CLI built from source' do + let(:convox_version) { 'dev' } - req.ensure_requirements! - end + it 'warns and carries on' do + expect(requirements.ensure_requirements!).to be true + expect(human_output(context)).to include 'built from source' end end - context 'with Linux' do - context 'with two missing packages' do - it 'shows the correct error message and quit' do - expect(OS).to receive(:mac?).and_return(false) - - req = described_class.new - expect(req).to receive(:find_command).with('convox').and_return(false) - expect(req).to receive(:find_command).with('aws').and_return(false) - expect(req).to receive(:quit!) - - expect(req.logger).to receive(:error).with( - 'This script requires the convox and AWS CLI tools.' - ) - expect(req.logger).to receive(:error).with('Installation Instructions:') - expect(req.logger).to receive(:error).with( - '* convox: https://docs.convox.com/introduction/installation' - ) - expect(req.logger).to receive(:error).with( - '* aws: https://docs.aws.amazon.com/cli/latest/' \ - 'userguide/cli-chap-install.html' - ) - - req.ensure_requirements! - end + context 'with terraform older than 1.6' do + let(:terraform_version) { '1.5.7' } + + it 'asks for an upgrade' do + expect { requirements.ensure_requirements! }.to raise_error(ConvoxInstaller::PreconditionFailed, /1.6.0 or later/) end end + + it 'rejects AWS CLI v1' do + executor.on('aws', '--version') { ['', 'aws-cli/1.29.0 Python/3.11 Linux/6.1 botocore/1.31.0', 0] } + expect do + requirements.ensure_requirements! + end.to raise_error(ConvoxInstaller::PreconditionFailed, /AWS CLI version 2.9.0/) + end end diff --git a/spec/lib/convox_installer/runner_spec.rb b/spec/lib/convox_installer/runner_spec.rb new file mode 100644 index 0000000..d41f2b9 --- /dev/null +++ b/spec/lib/convox_installer/runner_spec.rb @@ -0,0 +1,137 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::Runner do + let(:command) { :install } + let(:context) { build_context(command: command) } + let(:runner) { context.runner } + + def result_event + events(context).find { |e| e['event'] == 'result' } + end + + it 'runs a step and reports it' do + value = runner.step('make_thing', 'Make the thing') do |s| + s.info(id: 7) + 42 + end + expect(value).to eq 42 + expect(events(context).map { |e| e.slice('event', 'step', 'status') }).to eq [ + { 'event' => 'step', 'step' => 'make_thing', 'status' => 'started' }, + { 'event' => 'step', 'step' => 'make_thing', 'status' => 'done' } + ] + expect(events(context).last).to include('description' => 'Make the thing', 'id' => 7) + end + + it 'skips a step that is already done' do + ran = false + runner.step('thing', check: -> { true }) { ran = true } + expect(ran).to be false + expect(events(context).last).to include('status' => 'skipped', 'state' => 'present') + end + + it 'turns other errors into StepFailed with the step name and a next step' do + expect { runner.step('thing') { raise 'disk full' } }.to raise_error(ConvoxInstaller::StepFailed) do |error| + expect(error.message).to eq 'Step thing failed: disk full' + expect(error.step).to eq 'thing' + end + expect(events(context).last).to include('status' => 'failed') + end + + it 'keeps the type of installer errors' do + expect { runner.step('thing') { raise ConvoxInstaller::PreconditionFailed, 'no' } } + .to raise_error(ConvoxInstaller::PreconditionFailed) + end + + describe '#finish' do + it 'reports success' do + runner.step('one') { nil } + runner.add_output(:domain, 'web.app.example.convox.cloud') + expect(runner.finish).to eq 0 + expect(result_event).to include('command' => 'install', 'status' => 'succeeded', 'exit_code' => 0, + 'outputs' => { 'domain' => 'web.app.example.convox.cloud' }, + 'steps' => [{ 'step' => 'one', 'status' => 'done' }]) + end + + { + ConvoxInstaller::MissingInput.new('Missing settings: x.', missing: ['x']) => [2, 'missing_input'], + ConvoxInstaller::PreconditionFailed.new('no aws') => [3, 'precondition_failed'], + ConvoxInstaller::StepFailed.new('boom') => [4, 'step_failed'], + ConvoxInstaller::Cancelled.new('no') => [5, 'cancelled'], + Interrupt.new => [130, 'interrupted'], + RuntimeError.new('bug') => [1, 'unexpected_error'] + }.each do |error, (code, type)| + it "exits #{code} for #{error.class.name.split('::').last}" do + expect(runner.finish(error)).to eq code + expect(result_event['error']).to include('type' => type) + expect(result_event['exit_code']).to eq code + end + end + + it 'includes the missing settings and the next step' do + error = ConvoxInstaller::MissingInput.new('Missing settings: x.', missing: ['x'], next_step: 'Pass --x VALUE.') + runner.finish(error) + expect(result_event['error']).to include('missing' => ['x'], 'next_step' => 'Pass --x VALUE.') + expect(human_output(context)).to include 'Next: Pass --x VALUE.' + end + + it 'masks secrets in the result' do + context.masker.add('very-secret-value') + runner.add_output(:password, 'very-secret-value') + runner.finish + expect(result_event['outputs']).to eq('password' => '[hidden]') + end + + it 'only reports once' do + runner.finish + runner.finish + expect(events(context).count { |e| e['event'] == 'result' }).to eq 1 + end + end + + context 'when planning' do + let(:command) { :plan } + + it 'stops a step at its first change and reports it as pending' do + changed = false + runner.step('thing') do |s| + s.plan!(action: 'create', reason: 'it does not exist') + changed = true + end + expect(changed).to be false + expect(events(context).last).to include('status' => 'pending', 'action' => 'create', 'state' => 'missing') + end + + it 'runs read-only steps' do + ran = false + runner.step('check_thing') { ran = true } + expect(ran).to be true + expect(events(context).last).to include('status' => 'done') + end + + it 'does not run steps that change things without calling plan!' do + runner.step('custom', run_in_dry_run: false) { raise 'must not run' } + expect(events(context).last).to include('status' => 'pending', 'action' => 'run') + runner.step('custom_with_check', check: -> { false }) { raise 'must not run' } + expect(events(context).last).to include('status' => 'pending', 'action' => 'run') + runner.step('custom_done', check: -> { true }, run_in_dry_run: false) { raise 'must not run' } + expect(events(context).last).to include('status' => 'skipped') + end + + it 'lists the pending steps in the result' do + runner.step('done_thing', check: -> { true }) + runner.step('todo', check: -> { false }) + runner.finish + expect(result_event).to include('status' => 'succeeded', 'pending' => ['todo'], 'changes_pending' => true) + end + + it 'exits 0 when a later step needs something that does not exist yet' do + error = ConvoxInstaller::NotYetAvailable.new('aws_db_instance.rds_database is not available yet.') + expect { runner.step('database_url') { raise error } }.to raise_error(ConvoxInstaller::NotYetAvailable) + expect(runner.finish(error)).to eq 0 + expect(result_event['stopped_early']).to eq('step' => 'database_url', + 'reason' => 'aws_db_instance.rds_database is not available yet.') + end + end +end diff --git a/spec/lib/convox_installer/shell_spec.rb b/spec/lib/convox_installer/shell_spec.rb new file mode 100644 index 0000000..17990c6 --- /dev/null +++ b/spec/lib/convox_installer/shell_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe ConvoxInstaller::Shell do + let(:executor) { FakeExecutor.new } + let(:context) { build_context(executor: executor) } + let(:shell) { context.shell } + + it 'captures output through the executor, with stdin closed' do + executor.on('convox', 'api', 'get') { ['[]', '', 0] } + result = shell.capture(%w[convox api get /apps], env: { 'A' => 1 }) + expect(result).to be_success + expect(result.stdout).to eq '[]' + expect(executor.calls.first.env).to eq('A' => '1') + expect(executor.calls.first.stdin_data).to eq '' + end + + it 'streams output to the human log, masked' do + context.masker.add('streamed-secret') + executor.on('terraform') { "line one streamed-secret\n" } + result = shell.stream(%w[terraform apply]) + expect(result.exit_code).to eq 0 + expect(human_output(context)).to include 'line one [hidden]' + end + + it 'splits legacy command strings into arguments' do + executor.on('convox') { '' } + shell.stream('convox env set FOO="a b"') + expect(executor.calls.first.argv).to eq ['convox', 'env', 'set', 'FOO=a b'] + end + + it 'displays commands with secret arguments masked' do + expect(shell.display(['convox', 'env', 'set', 'DOCSPRING_LICENSE=abc123', 'NAME=a b'])) + .to eq 'convox env set DOCSPRING_LICENSE=[hidden] NAME\\=a\\ b' + end + + it 'finds executables on PATH without running anything' do + Dir.mktmpdir do |dir| + path = File.join(dir, 'fake-tool') + File.write(path, '') + File.chmod(0o755, path) + original = ENV.fetch('PATH', nil) + ENV['PATH'] = dir + expect(shell.which('fake-tool')).to eq path + expect(shell.which('missing-tool')).to be_nil + ensure + ENV['PATH'] = original + end + end + + it 'refuses to run real commands in specs' do + expect { described_class.new(reporter: context.reporter, masker: context.masker).capture(%w[ls]) } + .to raise_error(/real command/) + end +end diff --git a/spec/lib/convox_installer_spec.rb b/spec/lib/convox_installer_spec.rb new file mode 100644 index 0000000..5e9815f --- /dev/null +++ b/spec/lib/convox_installer_spec.rb @@ -0,0 +1,154 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'open3' +require 'rbconfig' + +# Runs examples/full_installation.rb as a real script, with fake convox, aws and terraform +# commands first on PATH (spec/fixtures/fake_tools.rb). Nothing reaches AWS or Convox. +RSpec.describe ConvoxInstaller do + let(:root) { Dir.mktmpdir('installer-e2e-') } + let(:bin_dir) { File.join(root, 'bin') } + let(:work_dir) { File.join(root, 'work') } + let(:state_dir) { File.join(root, 'state') } + let(:convox_dir) { File.join(root, 'convox') } + let(:script) { File.expand_path('../../examples/full_installation.rb', __dir__) } + let(:fake_tools) { File.expand_path('../fixtures/fake_tools.rb', __dir__) } + let(:registry_env) do + { 'DOCKER_REGISTRY_USERNAME' => 'registry-user', 'DOCKER_REGISTRY_PASSWORD' => 'registry-password-value' } + end + + before do + [bin_dir, work_dir, state_dir, convox_dir].each { |dir| FileUtils.mkdir_p(dir) } + %w[convox aws terraform].each do |tool| + path = File.join(bin_dir, tool) + File.write(path, <<~SH) + #!/bin/sh + RUBYOPT= exec "#{RbConfig.ruby}" --disable-gems "#{fake_tools}" #{tool} "$@" + SH + File.chmod(0o755, path) + end + end + + after { FileUtils.rm_rf(root) } + + # Clears anything from the developer's environment that the installer would read. + def clean_env + names = ENV.keys.select { |name| name.start_with?('AWS_', 'CONVOX_') } + names += ConvoxInstaller::Settings::KNOWN.keys.flat_map { |key| ConvoxInstaller::Settings.env_names(key) } + names += %w[STACK_NAME INSTANCE_TYPE RANDOM_ID ADMIN_EMAIL ADMIN_PASSWORD SECRET_KEY_BASE + AUTOSTART_CONVOX_INSTALLATION] + names.uniq.to_h { |name| [name, nil] } + end + + def run_script(*args, env: registry_env) + full_env = clean_env.merge( + 'PATH' => "#{bin_dir}:#{ENV.fetch('PATH')}", + 'CONVOX_CONFIG' => convox_dir, + 'FAKE_STATE_DIR' => state_dir, + 'AWS_PROFILE' => 'agent-profile' + ).merge(env) + stdout, stderr, status = Open3.capture3(full_env, RbConfig.ruby, script, *args, chdir: work_dir, stdin_data: '') + events = stdout.lines.map { |line| JSON.parse(line) } + { events: events, stderr: stderr, stdout: stdout, exit_code: status.exitstatus, + result: events.find { |e| e['event'] == 'result' } } + end + + def step_statuses(run) + run[:result]['steps'].to_h { |s| [s['step'], s['status']] } + end + + def calls + File.readlines(File.join(state_dir, 'calls.log')).map { |line| JSON.parse(line) } + end + + def fake_state + JSON.parse(File.read(File.join(state_dir, 'state.json'))) + end + + it 'installs everything, then finds nothing to do on the next run' do + run = run_script('--yes', '--json') + expect(run[:exit_code]).to eq(0), run[:stderr] + expect(run[:result]).to include('command' => 'install', 'status' => 'succeeded', 'exit_code' => 0, + 'outputs' => { 'domain' => 'web.example-app.fake123.convox.cloud' }) + expect(step_statuses(run)).to eq( + 'requirements' => 'done', 'config' => 'done', 'convox_rack' => 'done', 'convox_current_rack' => 'done', + 'convox_rack_api' => 'done', 'convox_app' => 'done', 'convox_app_directory' => 'done', + 'docker_registry' => 'done', 'terraform_s3_bucket' => 'done', 'terraform_rds_database' => 'done', + 'terraform_elasticache' => 'done', 'terraform_apply' => 'done', 'convox_env' => 'done', + 'initial_deploy' => 'done', 'database_setup' => 'done' + ) + expect(run[:events].first).to include('event' => 'start', 'command' => 'install', 'version' => ConvoxInstaller::VERSION) + + # Every line on stdout is an event; the human log went to stderr. + expect(run[:events].map { |e| e['event'] }.uniq).to match_array %w[start step config result] + expect(run[:stderr]).to include '==> convox_rack: Install the Convox rack convox' + + # Secrets never reach the output. + output = run[:stdout] + run[:stderr] + %w[registry-password-value fake-exported-secret fake-session-token fake-app-secret fake-api-pw].each do |secret| + expect(output).not_to include(secret) + end + expect(output).not_to include(fake_state['env']['DATABASE_URL'][%r{:([^:@/]+)@}, 1]) + + # convox and terraform got the credentials resolved from the AWS profile. + convox_calls = calls.select do |c| + %w[convox terraform].include?(c['tool']) && !%w[--version version].include?(c['argv'].first) + end + expect(convox_calls.map { |c| c['aws_key'] }.uniq).to eq ['ASIAFAKE'] + install = calls.find { |c| c['argv'].first(2) == %w[rack install] } + expect(install['argv']).to include('aws', 'convox', 'node_type=t3.medium', 'region=us-east-1', + 'proxy_protocol=true') + + expect(fake_state['env']).to include('REDIS_URL' => start_with('rediss://:'), + 'AWS_S3_BUCKET' => start_with('convox-app-uploads-'), + 'DOMAIN_NAME' => 'web.example-app.fake123.convox.cloud') + expect(fake_state['ran']).to eq ['web rake db:prepare --rack convox'] + expect(File.read(File.join(work_dir, '.convox', 'app'))).to eq "example-app\n" + saved = JSON.parse(File.read(File.join(work_dir, '.installer_config.json')))['config'] + expect(saved).to include('aws_account_id' => '123456789012', 'database_setup_done' => 'true') + expect(saved.keys).not_to include('aws_access_key_id', 'aws_secret_access_key') + + rerun = run_script('--yes', '--json') + expect(rerun[:exit_code]).to eq(0), rerun[:stderr] + # The checks report done; every other step finds nothing to do. + statuses = step_statuses(rerun).except('requirements', 'config', 'convox_rack_api') + expect(statuses.values.uniq).to eq(['skipped']), statuses.inspect + + plan = run_script('plan', '--json') + expect(plan[:exit_code]).to eq(0), plan[:stderr] + expect(plan[:result]).to include('command' => 'plan', 'changes_pending' => false, 'pending' => []) + end + + it 'plans a new install without changing anything' do + plan = run_script('plan', '--json') + expect(plan[:exit_code]).to eq(0), plan[:stderr] + expect(plan[:result]).to include('status' => 'succeeded', 'changes_pending' => true) + expect(plan[:result]['pending']).to include('convox_rack', 'convox_app', 'terraform_apply') + expect(calls.map { |c| c['argv'].first(2) }).not_to include(%w[rack install], %w[apps create]) + expect(Dir.exist?(File.join(convox_dir, 'racks'))).to be false + end + + it 'lists the missing settings and exits 2 in a non-interactive run' do + run = run_script('--yes', '--json', env: {}) + expect(run[:exit_code]).to eq 2 + expect(run[:result]).to include('status' => 'failed', 'exit_code' => 2) + expect(run[:result]['error']).to include('type' => 'missing_input', + 'missing' => %w[docker_registry_username docker_registry_password]) + expect(run[:result]['error']['next_step']).to include '--docker-registry-username VALUE' + expect(calls.map { |c| c['argv'].first(2) }).not_to include(%w[rack install]) + end + + it 'asks for --yes instead of prompting when stdin is not a terminal' do + run = run_script('--json') + expect(run[:exit_code]).to eq 2 + expect(run[:result]['error']).to include('missing' => ['confirmation']) + expect(run[:stderr]).to include 'Next: Check the settings above, then run the same command with --yes.' + end + + it 'explains a bad flag' do + run = run_script('--json', '--no-such-flag') + expect(run[:exit_code]).to eq 2 + expect(run[:result]).to include('status' => 'failed', 'error' => include('type' => 'usage')) + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 652d519..8fb4bef 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,118 +1,41 @@ # frozen_string_literal: true -# This file was generated by the `rspec --init` command. Conventionally, all -# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. -# The generated `.rspec` file contains `--require spec_helper` which will cause -# this file to always be loaded, without a need to explicitly require it in any -# files. -# -# Given that it is always loaded, you are encouraged to keep this file as -# light-weight as possible. Requiring heavyweight dependencies from this file -# will add to the boot time of your test suite on EVERY test run, even for an -# individual file that may not need all of that loaded. Instead, consider making -# a separate helper file that requires the additional dependencies and performs -# the additional setup, and require it from the spec files that actually need -# it. -# -# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) -$LOAD_PATH << File.expand_path(__dir__, '../lib') - -require 'vcr' +require 'json' +require 'stringio' +require 'tmpdir' require 'webmock/rspec' -# require 'pry-byebug' +require 'convox_installer' -VCR.configure do |config| - config.cassette_library_dir = 'spec/vcr_cassettes' - config.hook_into :webmock - config.configure_rspec_metadata! +Dir[File.join(__dir__, 'support/**/*.rb')].each { |f| require f } - config.debug_logger = File.open( - File.join(__dir__, '../log/vcr_debug.log'), 'w' - ) - config.default_cassette_options = { record: :none, erb: true } -end +# No network: the gem makes no HTTP calls, and specs must not either. +WebMock.disable_net_connect! RSpec.configure do |config| - # rspec-expectations config goes here. You can use an alternate - # assertion/expectation library such as wrong or the stdlib/minitest - # assertions if you prefer. config.expect_with :rspec do |expectations| - # This option will default to `true` in RSpec 4. It makes the `description` - # and `failure_message` of custom matchers include text for helper methods - # defined using `chain`, e.g.: - # be_bigger_than(2).and_smaller_than(4).description - # # => "be bigger than 2 and smaller than 4" - # ...rather than: - # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end - # rspec-mocks config goes here. You can use an alternate test double - # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| - # Prevents you from mocking or stubbing a method that does not exist on - # a real object. This is generally recommended, and will default to - # `true` in RSpec 4. mocks.verify_partial_doubles = true end - # This option will default to `:apply_to_host_groups` in RSpec 4 (and will - # have no way to turn it off -- the option exists only for backwards - # compatibility in RSpec 3). It causes shared context metadata to be - # inherited by the metadata hash of host groups and examples, rather than - # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups + config.disable_monkey_patching! + config.order = :random + Kernel.srand config.seed + + config.include SpecHelpers - # The settings below are suggested to provide a good initial experience - # with RSpec, but feel free to customize to your heart's content. - # # This allows you to limit a spec run to individual examples or groups - # # you care about by tagging them with `:focus` metadata. When nothing - # # is tagged with `:focus`, all examples get run. RSpec also provides - # # aliases for `it`, `describe`, and `context` that include `:focus` - # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. - # config.filter_run_when_matching :focus - # - # # Allows RSpec to persist some state between runs in order to support - # # the `--only-failures` and `--next-failure` CLI options. We recommend - # # you configure your source control system to ignore this file. - # config.example_status_persistence_file_path = "spec/examples.txt" - # - # # Limits the available syntax to the non-monkey patched syntax that is - # # recommended. For more details, see: - # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ - # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode - # config.disable_monkey_patching! - # - # # This setting enables warnings. It's recommended, but in some cases may - # # be too noisy due to issues in dependencies. - # config.warnings = true - # - # # Many RSpec users commonly either run the entire suite or an individual - # # file, and it's useful to allow more verbose output when running an - # # individual spec file. - # if config.files_to_run.one? - # # Use the documentation formatter for detailed output, - # # unless a formatter has already been configured - # # (e.g. via a command-line flag). - # config.default_formatter = "doc" - # end - # - # # Print the 10 slowest examples and example groups at the - # # end of the spec run, to help surface which specs are running - # # particularly slow. - # config.profile_examples = 10 - # - # # Run specs in random order to surface order dependencies. If you find an - # # order dependency and want to debug it, you can fix the order by providing - # # the seed, which is printed after each run. - # # --seed 1234 - # config.order = :random - # - # # Seed global randomization in this process using the `--seed` CLI option. - # # Setting this allows you to use `--seed` to deterministically reproduce - # # test failures related to randomization by passing the same `--seed` value - # # as the one that triggered the failure. - # Kernel.srand config.seed + # No real command may run in a spec: every Shell gets this executor unless a spec + # passes its own. + config.before do + ConvoxInstaller::Shell.executor = RefusingExecutor.new + end + + config.after do + ConvoxInstaller::Shell.executor = nil + end end diff --git a/spec/support/fake_executor.rb b/spec/support/fake_executor.rb new file mode 100644 index 0000000..c561e10 --- /dev/null +++ b/spec/support/fake_executor.rb @@ -0,0 +1,81 @@ +# frozen_string_literal: true + +# Raises if anything tries to run a real command. +class RefusingExecutor + def capture(_env, argv, **) + raise "A spec tried to run a real command: #{argv.join(' ')}" + end + + def stream(_env, argv, **) + raise "A spec tried to run a real command: #{argv.join(' ')}" + end +end + +# Plays back canned results for commands, matched by prefix, and records every call. +# +# executor.on('convox', 'api', 'get', '/apps') { |call| [JSON.generate([]), '', 0] } +# +# A handler gets a Call and returns [stdout, stderr, exit_code], or a String (stdout, +# exit 0), or an Integer (exit code). Unmatched commands raise. +class FakeExecutor + Call = Struct.new(:argv, :env, :stdin_data, :chdir, :mode, keyword_init: true) do + def to_s = argv.join(' ') + end + + attr_reader :calls + + def initialize + @handlers = [] + @calls = [] + end + + def on(*prefix, &handler) + @handlers.unshift([prefix.map(&:to_s), handler]) + self + end + + def capture(env, argv, stdin_data:, chdir:) + call = record(env, argv, stdin_data, chdir, :capture) + normalize(dispatch(call)) + end + + def stream(env, argv, stdin_data:, chdir:, &) + call = record(env, argv, stdin_data, chdir, :stream) + stdout, stderr, code = normalize(dispatch(call)) + "#{stdout}#{stderr}".each_line(&) + code + end + + def commands + calls.map(&:to_s) + end + + def calls_matching(*prefix) + calls.select { |call| call.argv.first(prefix.length) == prefix.map(&:to_s) } + end + + private + + def record(env, argv, stdin_data, chdir, mode) + call = Call.new(argv: argv, env: env, stdin_data: stdin_data, chdir: chdir, mode: mode) + calls << call + call + end + + def dispatch(call) + _prefix, handler = @handlers.find { |prefix, _| call.argv.first(prefix.length) == prefix } + raise "Unexpected command in spec: #{call}" unless handler + + handler.call(call) + end + + def normalize(result) + case result + when Array then result + when String then [result, '', 0] + when Integer then ['', '', result] + when nil then ['', '', 0] + else raise "Bad fake result: #{result.inspect}" + end + end +end diff --git a/spec/support/fake_rack.rb b/spec/support/fake_rack.rb new file mode 100644 index 0000000..1d64211 --- /dev/null +++ b/spec/support/fake_rack.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +# A temporary Convox config directory (CONVOX_CONFIG) with an optional rack directory, +# plus fake terraform output/state commands that read from instance variables, so a spec +# can change the "state" as commands run. +module FakeRack + API_URL = 'https://convox:rack-api-password-1234@api.abc123def456.convox.cloud' + + def with_convox_config_dir + dir = Dir.mktmpdir('convox-config-') + previous = ENV.fetch('CONVOX_CONFIG', nil) + ENV['CONVOX_CONFIG'] = dir + yield dir + ensure + previous.nil? ? ENV.delete('CONVOX_CONFIG') : ENV['CONVOX_CONFIG'] = previous + FileUtils.rm_rf(dir) + end + + def create_rack_dir(stack_name, main_tf: true) + dir = File.join(ENV.fetch('CONVOX_CONFIG'), 'racks', stack_name) + FileUtils.mkdir_p(File.join(dir, '.terraform')) + File.write(File.join(dir, 'main.tf'), "module \"system\" {}\n") if main_tf + dir + end + + def terraform_resource(type, name, attributes) + { 'mode' => 'managed', 'type' => type, 'name' => name, 'instances' => [{ 'attributes' => attributes }] } + end + + # Handles `terraform output -json` and `terraform state pull` from @tf_outputs and + # @tf_resources. + def stub_terraform_reads(executor) + executor.on('/usr/bin/terraform', 'output', '-json') { JSON.generate(@tf_outputs || {}) } + executor.on('/usr/bin/terraform', 'state', 'pull') do + JSON.generate('version' => 4, 'resources' => @tf_resources || [], 'outputs' => {}) + end + end + + def installed_outputs + { 'api' => { 'sensitive' => true, 'type' => 'string', 'value' => API_URL } } + end +end diff --git a/spec/support/spec_helpers.rb b/spec/support/spec_helpers.rb new file mode 100644 index 0000000..4525e6b --- /dev/null +++ b/spec/support/spec_helpers.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +module SpecHelpers + def build_context(command: :install, json: true, assume_yes: true, settings: {}, executor: nil, + config_path: nil, log_level: Logger::DEBUG) + options = ConvoxInstaller::Options.new(command: command, json: json, assume_yes: assume_yes, + settings: settings, config_path: config_path, env: {}) + ConvoxInstaller::Context.new(options: options, log_level: log_level, event_io: StringIO.new, + human_io: StringIO.new, executor: executor) + end + + def events(context) + io = context.reporter.instance_variable_get(:@event_io) + io.string.lines.map { |line| JSON.parse(line) } + end + + def human_output(context) + context.reporter.human_io.string + end + + # Credentials as `aws configure export-credentials --format process` prints them. + def stub_aws(executor, account: '123456789012', arn: 'arn:aws:sts::123456789012:assumed-role/Admin/me') + executor.on('aws', 'configure', 'export-credentials') do + JSON.generate(Version: 1, AccessKeyId: 'ASIAEXAMPLE', SecretAccessKey: 'exported-secret-key-value', + SessionToken: 'exported-session-token-value', Expiration: (Time.now + 3600).utc.iso8601) + end + executor.on('aws', 'sts', 'get-caller-identity') do + JSON.generate(Account: account, Arn: arn, UserId: 'AROAEXAMPLE:me') + end + executor.on('aws', '--version') { 'aws-cli/2.31.0 Python/3.13.0 Linux/6.8 exe/x86_64' } + end +end diff --git a/terraform/convox_installer.tf.erb b/terraform/convox_installer.tf.erb new file mode 100644 index 0000000..d615f8a --- /dev/null +++ b/terraform/convox_installer.tf.erb @@ -0,0 +1,11 @@ +# Written by convox_installer. It rewrites this file every time it runs. +# Shared by the S3, RDS and ElastiCache configs in this directory. The Convox rack's own +# configuration is in main.tf. + +provider "aws" { + region = <%= s(:region) %> +} + +data "aws_vpc" "convox_installer_rack" { + id = module.system.cluster.vpc +} diff --git a/terraform/elasticache.tf.erb b/terraform/elasticache.tf.erb index fd69ca1..848fea9 100644 --- a/terraform/elasticache.tf.erb +++ b/terraform/elasticache.tf.erb @@ -1,32 +1,41 @@ -resource "aws_elasticache_cluster" "elasticache_cluster" { - cluster_id = "<%= config.fetch(:stack_name) %>-elasticache-<%= config.fetch(:random_id) %>" - engine = "<%= config[:elasticache_engine] || 'redis' %>" - engine_version = "<%= config[:elasticache_engine_version] || '7.1' %>" - node_type = "<%= config[:elasticache_node_type] || 'cache.t3.medium' %>" - num_cache_nodes = <%= config[:elasticache_num_cache_nodes] || 1 %> - port = <%= config[:elasticache_port] || 6379 %> - - subnet_group_name = aws_elasticache_subnet_group.elasticache_subnet_group.name +# Written by convox_installer. It rewrites this file every time it runs. + +resource "aws_elasticache_replication_group" "redis" { + replication_group_id = <%= s(:replication_group_id) %> + description = <%= s(:description) %> + engine = <%= s(:engine) %> + engine_version = <%= s(:engine_version) %> + node_type = <%= s(:node_type) %> + num_cache_clusters = <%= v(:num_cache_clusters) %> + port = <%= v(:port) %> + automatic_failover_enabled = <%= v(:failover) %> + multi_az_enabled = <%= v(:failover) %> + at_rest_encryption_enabled = true + transit_encryption_enabled = true + auth_token = <%= s(:auth_token) %> + apply_immediately = true + + subnet_group_name = aws_elasticache_subnet_group.elasticache_subnet_group.name security_group_ids = [aws_security_group.elasticache_security_group.id] } resource "aws_elasticache_subnet_group" "elasticache_subnet_group" { - name = "<%= config.fetch(:stack_name) %>-elasticache-cluster-subnetgroup-<%= config.fetch(:random_id) %>" + name = <%= s(:subnet_group_name) %> subnet_ids = module.system.cluster.subnets } resource "aws_security_group" "elasticache_security_group" { - name = "<%= config.fetch(:stack_name) %>-elasticache-securitygroup-<%= config.fetch(:random_id) %>" + name = <%= s(:security_group_name) %> description = "Elasticache Security Group (Managed by Terraform)" vpc_id = module.system.cluster.vpc - # Only Redis in + # Redis from inside the rack's VPC only ingress { - from_port = 6379 - to_port = 6379 + from_port = <%= v(:port) %> + to_port = <%= v(:port) %> protocol = "tcp" - cidr_blocks = ["10.1.0.0/16"] + cidr_blocks = [data.aws_vpc.convox_installer_rack.cidr_block] } # Allow all outbound traffic diff --git a/terraform/elasticache_legacy.tf.erb b/terraform/elasticache_legacy.tf.erb new file mode 100644 index 0000000..490853b --- /dev/null +++ b/terraform/elasticache_legacy.tf.erb @@ -0,0 +1,44 @@ +# Written by convox_installer. It rewrites this file every time it runs. +# +# The single-node cluster that convox_installer 3.x created (no TLS, no AUTH). Installs that +# already have it keep it, because moving to a replication group would replace the cluster. + +resource "aws_elasticache_cluster" "elasticache_cluster" { + cluster_id = <%= s(:cluster_id) %> + engine = <%= s(:engine) %> + engine_version = <%= s(:engine_version) %> + node_type = <%= s(:node_type) %> + num_cache_nodes = <%= v(:num_cache_nodes) %> + port = <%= v(:port) %> + + subnet_group_name = aws_elasticache_subnet_group.elasticache_subnet_group.name + security_group_ids = [aws_security_group.elasticache_security_group.id] +} + +resource "aws_elasticache_subnet_group" "elasticache_subnet_group" { + name = <%= s(:subnet_group_name) %> + subnet_ids = module.system.cluster.subnets +} + +resource "aws_security_group" "elasticache_security_group" { + name = <%= s(:security_group_name) %> + + description = "Elasticache Security Group (Managed by Terraform)" + vpc_id = module.system.cluster.vpc + + # Redis from inside the rack's VPC only + ingress { + from_port = 6379 + to_port = 6379 + protocol = "tcp" + cidr_blocks = [data.aws_vpc.convox_installer_rack.cidr_block] + } + + # Allow all outbound traffic + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} diff --git a/terraform/rds.tf.erb b/terraform/rds.tf.erb index 9ccccd6..0c89d3a 100644 --- a/terraform/rds.tf.erb +++ b/terraform/rds.tf.erb @@ -1,38 +1,45 @@ +# Written by convox_installer. It rewrites this file every time it runs. + resource "aws_db_instance" "rds_database" { - allocated_storage = <%= config[:database_allocated_storage] || 30 %> - engine = "<%= config[:database_engine] || 'postgres' %>" - engine_version = "<%= config[:database_engine_version] || '15.7' %>" - instance_class = "<%= config[:database_instance_class] || 'db.t3.small' %>" - db_name = "<%= config.fetch(:stack_name).gsub('-', '_') %>_database" - identifier = "<%= config.fetch(:stack_name) %>-rds-<%= config.fetch(:random_id) %>" - multi_az = <%= config[:database_multi_az] || true %> - username = "<%= config.fetch(:database_username) %>" - password = "<%= config.fetch(:database_password) %>" - - final_snapshot_identifier = "<%= config.fetch(:stack_name) %>-rds-<%= config.fetch(:random_id) %>-final-snapshot" - skip_final_snapshot = false - - db_subnet_group_name = aws_db_subnet_group.rds_subnet_group.name + identifier = <%= s(:identifier) %> + engine = <%= s(:engine) %> + engine_version = <%= s(:engine_version) %> + instance_class = <%= s(:instance_class) %> + allocated_storage = <%= v(:allocated_storage) %> + storage_type = <%= s(:storage_type) %> + storage_encrypted = <%= v(:storage_encrypted) %> + db_name = <%= s(:db_name) %> + username = <%= s(:username) %> + password = <%= s(:password) %> + multi_az = <%= v(:multi_az) %> + backup_retention_period = <%= v(:backup_retention_period) %> + deletion_protection = <%= v(:deletion_protection) %> + allow_major_version_upgrade = <%= v(:allow_major_version_upgrade) %> + + final_snapshot_identifier = <%= s(:final_snapshot_identifier) %> + skip_final_snapshot = false + + db_subnet_group_name = aws_db_subnet_group.rds_subnet_group.name vpc_security_group_ids = [aws_security_group.rds_security_group.id] } resource "aws_db_subnet_group" "rds_subnet_group" { - name = "<%= config.fetch(:stack_name) %>-rds-subnetgroup-<%= config.fetch(:random_id) %>" + name = <%= s(:subnet_group_name) %> subnet_ids = module.system.cluster.subnets } resource "aws_security_group" "rds_security_group" { - name = "<%= config.fetch(:stack_name) %>-rds-database-securitygroup-<%= config.fetch(:random_id) %>" + name = <%= s(:security_group_name) %> description = "RDS Security Group (Managed by Terraform)" vpc_id = module.system.cluster.vpc - # Only Postgres in + # Postgres from inside the rack's VPC only ingress { from_port = 5432 to_port = 5432 protocol = "tcp" - cidr_blocks = ["10.1.0.0/16"] + cidr_blocks = [data.aws_vpc.convox_installer_rack.cidr_block] } # Allow all outbound traffic diff --git a/terraform/s3_bucket.tf.erb b/terraform/s3_bucket.tf.erb index e748055..344241d 100644 --- a/terraform/s3_bucket.tf.erb +++ b/terraform/s3_bucket.tf.erb @@ -1,36 +1,85 @@ -# AWS provider version is 3.33.0 -# https://registry.terraform.io/providers/hashicorp/aws/3.33.0 - -provider "aws" { - region = "<%= config[:aws_region] %>" -} +# Written by convox_installer. It rewrites this file every time it runs. resource "aws_kms_key" "docs_kms_key" { - description = "This key is used to encrypt objects in the DocSpring S3 bucket" + description = "Encrypts objects in the <%= v(:bucket_name) %> S3 bucket" deletion_window_in_days = 14 + enable_key_rotation = true } -# Later versions of aws provider (e.g. 4.8.0) use separate resources for -# aws_s3_bucket_acl and aws_s3_bucket_cors_configuration. -# This will need to be updated in the future. resource "aws_s3_bucket" "docs_s3_bucket" { - bucket = "<%= config.fetch(:stack_name) %>-<%= config.fetch(:s3_bucket_name) %>" - acl = "private" - - server_side_encryption_configuration { - rule { - apply_server_side_encryption_by_default { - kms_master_key_id = aws_kms_key.docs_kms_key.arn - sse_algorithm = "aws:kms" - } + bucket = <%= s(:bucket_name) %> +} + +resource "aws_s3_bucket_public_access_block" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} +<% if v(:ownership_controls) -%> + +resource "aws_s3_bucket_ownership_controls" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id + + rule { + object_ownership = "BucketOwnerEnforced" + } +} +<% end -%> + +resource "aws_s3_bucket_server_side_encryption_configuration" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id + + rule { + apply_server_side_encryption_by_default { + kms_master_key_id = aws_kms_key.docs_kms_key.arn + sse_algorithm = "aws:kms" + } + bucket_key_enabled = true + } +} + +resource "aws_s3_bucket_versioning" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id + + versioning_configuration { + status = <%= s(:versioning) %> + } +} +<% if v(:lifecycle) -%> + +resource "aws_s3_bucket_lifecycle_configuration" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id + depends_on = [aws_s3_bucket_versioning.docs_s3_bucket] + + rule { + id = "expire-noncurrent-versions" + status = "Enabled" + + filter {} + + noncurrent_version_expiration { + noncurrent_days = <%= v(:noncurrent_days) %> + } + + abort_incomplete_multipart_upload { + days_after_initiation = 7 } } +} +<% end -%> +<% if v(:cors_rules) -%> + +resource "aws_s3_bucket_cors_configuration" "docs_s3_bucket" { + bucket = aws_s3_bucket.docs_s3_bucket.id - <%= config[:s3_bucket_cors_rule] %> +<%= v(:cors_rules) %> } +<% end -%> resource "aws_iam_user" "docspring_s3_user" { - name = "<%= config.fetch(:stack_name) %>-<%= config.fetch(:s3_bucket_name) %>" + name = <%= s(:iam_user_name) %> } resource "aws_iam_access_key" "docspring_user_access_key" { @@ -42,31 +91,29 @@ resource "aws_iam_user_policy" "docspring_user_s3_policy" { user = aws_iam_user.docspring_s3_user.name policy = jsonencode({ - "Version": "2012-10-17", - "Statement": [ + Version = "2012-10-17" + Statement = [ { - "Effect": "Allow", - "Action": [ - "s3:PutObject", - "s3:PutObjectAcl", - "s3:GetObject", - "s3:GetObjectAcl", - "s3:DeleteObject" - ], - "Resource": [ - "arn:aws:s3:::<%= config.fetch(:stack_name) %>-<%= config.fetch(:s3_bucket_name) %>/*", + Effect = "Allow" + Action = [ + "s3:PutObject", + "s3:PutObjectAcl", + "s3:GetObject", + "s3:GetObjectAcl", + "s3:DeleteObject" ] + Resource = ["${aws_s3_bucket.docs_s3_bucket.arn}/*"] }, { - "Effect": "Allow", - "Action": [ + Effect = "Allow" + Action = [ "kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey" - ], - "Resource": "*" + ] + Resource = aws_kms_key.docs_kms_key.arn } ] })