diff --git a/ansible/platform/galaxy.yml b/ansible/platform/galaxy.yml index 5874253e..eebe1811 100644 --- a/ansible/platform/galaxy.yml +++ b/ansible/platform/galaxy.yml @@ -7,9 +7,9 @@ readme: README.md authors: - David Julian Albers description: >- - The platform layer (PLX-Platform): what makes an existing host run a tenant's apps — - deploy_user, caddy, ingress, secrets, apps — and the playbook plexus.platform.playbook that - mounts them with the host baseline on the inventory group platform; and the playbook + The platform layer (PLX-Platform): what prepares an existing host for a tenant's stacks — + deploy_user, caddy, ingress — and the playbook plexus.platform.playbook that mounts them + with the host baseline on the inventory group platform; and the playbook plexus.platform.stack, which deploys one environment of a stack onto one host. license: - GPL-3.0-or-later diff --git a/ansible/platform/playbooks/playbook.yml b/ansible/platform/playbooks/playbook.yml index b5406d4d..4a9bff1c 100644 --- a/ansible/platform/playbooks/playbook.yml +++ b/ansible/platform/playbooks/playbook.yml @@ -1,16 +1,24 @@ --- # The platform layer on a tenant's app hosts (PLX-Platform): the host -# baseline, then what makes the host run the tenant's apps, then the lock-down -# roles that have to come last. Mounted on the inventory group `platform`. +# baseline, then what prepares the host for stacks, then the lock-down roles +# that have to come last. Mounted on the inventory group `platform`. # # ansible-playbook plexus.platform.playbook # everything -# ansible-playbook plexus.platform.playbook --tags apps,secrets # the everyday pass +# ansible-playbook plexus.platform.playbook --tags platform # the layer without the baseline # ansible-playbook plexus.platform.playbook --limit host-a --tags ingress # # Tags: every play carries its layer (`host`, `platform`) and every role its -# own name, so `--tags platform` is the whole layer and `--tags apps` one role. -# Not a deploy: deploying is the verb's act (§ 6 PLX-Delivery); this playbook -# binds apps to the host and hands them their environment. +# own name, so `--tags platform` is the whole layer and `--tags ingress` one role. +# It knows no stack: it prepares what every stack's environment needs on the +# host (the deploy user, the deploy root, the proxy with its directory of route +# fragments, and the one rule by which the deploy user reloads the proxy), and +# the stack playbook (plexus.platform.stack) does everything one environment +# needs. It starts, re-creates and removes no container, changes nothing below +# the deploy root, and writes no route. `plexus_apps`, the records of earlier +# versions, is not read, nor is plexus_deploy_root; a host that still sets +# records in the one or another path than /opt/stacks in the other is told so, +# and the run goes on. A proxy configuration Caddy refuses fails the host in the +# last play, after the lock-down roles have run. # # A fresh host is reached as root once (`-u root`), which creates the admins; # every later run connects as an admin, and the first of those closes root @@ -46,12 +54,29 @@ - name: Gather facts ansible.builtin.setup: tags: [always] + - name: Say that plexus_apps is no longer read + when: plexus_apps | default([]) | length > 0 + ansible.builtin.debug: + msg: >- + plexus_apps is no longer read, and the platform playbook writes nothing from it: a change to a record's + values, secrets, port or route reaches no host any more, a rotated secret re-creates no container, and a + new record gets no directory, so it cannot be deployed. Each deployment on this host keeps running, and + keeps deploying, with the .env, .env.secret and route it has, until its repo holds its environment file + and the stack playbook writes them from there. The routes earlier versions wrote stay in + /etc/caddy/apps.caddy until removed by hand; remove the records once no deployment needs them. + tags: [always] + - name: Say that plexus_deploy_root is no longer read + when: plexus_deploy_root | default('/opt/stacks') != '/opt/stacks' + ansible.builtin.debug: + msg: >- + plexus_deploy_root is no longer read: the deploy root is /opt/stacks on every host, which the platform + playbook gives the deploy user, and the stack playbook works there alone. A deployment under + {{ plexus_deploy_root }} is not seen by the stack playbook and stays as it is; remove the variable. + tags: [always] roles: - { role: plexus.platform.deploy_user, tags: [deploy_user] } - { role: plexus.platform.caddy, tags: [caddy] } - { role: plexus.platform.ingress, tags: [ingress] } - - { role: plexus.platform.secrets, tags: [secrets] } # before apps, so the first up sees the secrets - - { role: plexus.platform.apps, tags: [apps] } - name: Lock down the platform hosts hosts: platform @@ -66,21 +91,16 @@ - { role: plexus.host.firewall, tags: [firewall] } # after the roles that open ports in it - { role: plexus.host.sshd, tags: [sshd] } # last: closes root logins once an admin has logged in -# The apps role records an app whose start failed and carries on with the -# others; the failure is raised here, once per host and after the lock-down -# roles, so that a failed start never leaves a host without its firewall and -# sshd settings. Any other failure (a rotation handler, the registry login, -# writing .env, resolving the secrets) still fails the host before them. Tagged `platform` and `apps`, so `--tags apps` reports it too. -- name: Report the apps that failed to start +# The proxy's configuration Caddy refused, which the ingress role records: the +# host fails here, after the lock-down roles, so that a route someone broke +# never keeps a host from its firewall and sshd settings. Tagged `platform` +# and `ingress`, so that `--tags ingress` reports it too. +- name: Report a proxy configuration Caddy refuses hosts: platform gather_facts: false - tags: [platform, apps] + tags: [platform, ingress] tasks: - - name: Fail the host for the apps that did not start - when: apps_failures | default([]) | length > 0 + - name: Fail the host whose proxy configuration Caddy refuses + when: ingress_invalid is defined ansible.builtin.fail: - msg: |- - {{ apps_failures | length }} app(s) did not start: - {% for f in apps_failures %} - - {{ f.app }}: '{{ f.task }}' failed (rc {{ f.rc }}): {{ f.output }} - {% endfor %} + msg: "the proxy's configuration is invalid, and every reload fails until it is mended: {{ ingress_invalid }}" diff --git a/ansible/platform/playbooks/stack.yml b/ansible/platform/playbooks/stack.yml index 13847f3c..fb4591e8 100644 --- a/ansible/platform/playbooks/stack.yml +++ b/ansible/platform/playbooks/stack.yml @@ -1,39 +1,74 @@ --- -# The stack playbook: deploys one environment of one stack onto one host. -# It runs where the deploy starts, a CI job or a person's machine, connects -# as the deploy user, and is never installed on the host. The deploy itself -# is the role plexus.platform.stack; the platform playbook -# (plexus.platform.playbook) lays the environment out before its first deploy. +# The stack playbook: deploys one environment of one stack onto its host. It +# runs where the deploy starts, a CI job or a person's machine, reads there the +# environment's file and the rendered compose file, connects to the host the +# file names as the deploy user, and is never installed on the host. The +# deploy is the role plexus.platform.stack. # -# ansible-playbook -i deploy@app-1.example.com, plexus.platform.stack \ -# -e stack_name=shop -e stack_environment=staging -e stack_compose_file=./compose.yaml +# ansible-playbook plexus.platform.stack -e stack_name=shop \ +# -e stack_environment_file=stack/staging.yaml -e stack_compose_file=./compose.yaml # -# Variables, documented in the role's defaults: stack_name, stack_environment -# and stack_compose_file, given on every run; stack_root (/opt/stacks) and -# stack_wait_timeout (60 seconds). +# Variables, documented in the role's defaults: stack_name, +# stack_environment_file and stack_compose_file, given on every run; the +# environment is named after its file (staging.yaml is staging). Further +# stack_root (the deploy root, /opt/stacks), stack_port_range (20000-20999), +# stack_secret_timeout (30 seconds) and stack_wait_timeout (60 seconds). # -# What it expects on the host: the directory /-, -# which the user it connects as may write, holding the .env (and .env.secret -# where the environment has secrets) that the platform playbook writes; Docker +# What the caller passes, and what not. No inventory (-i) and no --limit: the +# one host is the file's `host`, [user@]address[:port], reached as the user it +# names, else as plexus_deploy_user (the role deploy_user's default, plexus, +# whatever an inventory says), on the port it names, else 22; an inventory +# only lends the connection variables of a host of the same name. No --tags +# or --skip-tags. It refuses a --limit, --tags or --skip-tags it sees, but a +# --limit that leaves out localhost, or --skip-tags always, makes +# ansible-playbook run none of its tasks and exit 0 without a Result line. +# Arguments for the connection, such as --ssh-common-args or --private-key, +# apply. PLEXUS_TAG and PLEXUS_COMMIT_SHA are the caller's: it renders them +# into the compose file it hands over, each app's image pinned by its digest in +# place of ${PLEXUS_TAG} and the commit in place of ${PLEXUS_COMMIT_SHA}; the +# playbook writes neither, and the compose file is otherwise handed over +# uninterpolated, since the host interpolates it from .env. +# +# What it expects where it runs: the vault's CLI, op, with a session or a +# token, where the environment has secrets. On the host, as the platform +# playbook prepares it (PLX-Stack/PreparedHost): the deploy user, owner of +# /opt/stacks; where the environment has a hostname, the directory of route +# fragments the deploy user writes and the sudo rule by which it reloads the +# proxy (both as the header of the ingress role's tasks names them); Docker # with its compose plugin, which that user may run (the docker group); and -# Python. It uses no privilege escalation. The compose project is -# -, the name the platform playbook writes into .env. +# Python. It uses no privilege escalation but that rule. # -# In order: -# 1. Checks its variables, that the inventory holds one host, and that the -# directory and its .env are there. -# 2. Compares the compose file with the compose.yaml in place. Where they are -# the same, 3 to 5 are left out. -# 3. Keeps the compose.yaml in place as compose.yaml.prev and writes the new one. -# 4. Pulls the images, so that an image that cannot be had fails the deploy -# before migrate runs, and a tag that moved since the last deploy is -# fetched, which run and up, pulling only what is missing, would not do. -# Where the file is the one in place, nothing is pulled, so a tag that -# moved is fetched only by a deploy that changes the file. -# 5. Runs the service `migrate` once, where the file has one, and removes its -# container; where it fails, the line says its exit code and the last line -# it wrote. -# 6. Brings up every service Compose starts by itself, `migrate` excepted, with +# In order, where it runs: +# 1. Checks its arguments and variables, and reads the environment's file and +# checks that it can write it: a map of `host`, `hostname`, a DNS name, +# `env`, names to strings, and `secrets`, names to op:// pointers; plx +# doctor checks the file whole. +# 2. Reads each pointer under `secrets` with `op read`, also in a dry run, +# refusing a value that is empty in the vault, and adds the host the file +# names. +# On the host, into /opt/stacks/-, the compose project of +# that name: +# 3. Where the environment has a hostname, claims its loopback port and +# writes its route (the role's files/route.sh says how). +# 4. Creates the directory where it is missing, mode 0750. +# 5. Renders .env from `env`, with COMPOSE_PROJECT_NAME and, where the +# environment has a hostname, PLEXUS_LOOPBACK_PORT; .env.secret, mode +# 0600, from the secrets' values, where the environment has secrets or +# the directory holds one already, which ends empty once the environment +# has none; each value double-quoted and escaped (templates/dotenv.j2), so +# that Compose reads it back as written. Compares them, and the compose +# file, with the files in place: a file that changes is kept as +# .prev, all of them before the first is written, and then written, +# .env, .env.secret, compose.yaml. .env.secret.prev, 0600, keeps the +# previous secrets until .env.secret changes again. +# 6. Pulls the images, where compose.yaml changed, so that an image that +# cannot be had fails the deploy before migrate runs, and a tag that moved +# since the last deploy is fetched, which run and up, pulling only what is +# missing, would not do. +# 7. Runs the service `migrate` once, where compose.yaml changed and has +# one, and removes its container; where it fails, the line says its exit +# code and the last line it wrote. +# 8. Brings up every service Compose starts by itself, `migrate` excepted, with # --no-deps, so that a service that depends on migrate's completion does # not run it again, and --remove-orphans, so that a service the file no # longer has goes. Then waits for every service that declares a @@ -41,41 +76,69 @@ # runs. stack_wait_timeout bounds the whole wait, and a healthcheck's # start_period does not extend it: a service that needs longer to turn # healthy needs the variable raised. Compose re-creates a container only -# where its service changed: an image pinned by digest that did not change -# leaves its line, and its container, as they were. Where no service is -# left to start, a stack of `migrate` alone or of none, it starts nothing -# and takes down whatever the project still runs; a take-down of something -# it ran counts as deployed, as a start does. -# A failure after 3 restores compose.yaml.prev and runs 6 again. After a first -# deploy, where there is no previous file, it removes the stack's containers -# and networks and the compose.yaml; the volumes stay. Where the file was the -# one in place, a failure undoes nothing; so a run after a rollback, with the -# same file, deploys it again and fails the same way. .env and .env.secret are -# the platform playbook's and are neither written nor restored here. +# where its service changed, its image or the files it loads: an image +# pinned by digest that did not change, and values that did not, leave +# the container as it was. Where no service is left to start, a stack of +# `migrate` alone or of none, it starts nothing and takes down whatever +# the project still runs; a take-down of something it ran counts as +# deployed, as a start does. +# A failure after the first write of 5 restores the files that run replaced, +# each from its .prev, removes a file it created, and runs 8 again; the route +# is not rolled back, since it joins the hostname to a port that does not +# change. Where compose.yaml was not there before, a first deploy, it removes +# the stack's containers and networks and the compose.yaml instead; the +# volumes stay, and .env and .env.secret stay with the port the route names. +# Where no file changed, a failure undoes nothing; so a run after a rollback, +# with the same files, deploys them again and fails the same way. A run in +# which nothing changed changes no file, reloads nothing and re-creates no +# container. +# +# Nothing locks an environment as a whole: two runs for the same environment +# at the same time are not supported, and can both fail, one undoing what the +# other made. What keeps them apart is the pipeline's own order, one deploy job +# per branch at a time. # -# Nothing locks an environment: two runs for the same environment at the same -# time are not supported, and can both fail, one undoing what the other made. -# What keeps them apart is the pipeline's own order, one deploy job per branch -# at a time. +# No secret's value appears in the run's output, with -v or --diff either: +# every task that holds one prints nothing of it. # -# The last task, Result, prints one line as its `msg`: -# -: deployed the file changed, or a container was started or -# taken down; healthy +# The last task, Result, prints one line as its `msg`. Every run prints it, and +# exits 0 only where it says deployed, unchanged or would deploy, but for the +# two runs of no task above and a host that cannot be reached, which Ansible's +# own error ends, with exit code 4: +# -: deployed a file or the route changed, or a container was +# started or taken down; healthy # -: unchanged nothing changed, and healthy -# -: would deploy under --check, where compose.yaml would change -# -: rolled back: the previous compose.yaml is up and healthy again +# -: would deploy under --check, where a file or the route would change +# -: rolled back: the previous files are up and healthy again # -: failed: nothing was rolled back, or the undo failed too # names the step that failed and the first line of its error, as in # `'Bring the stack up and wait for health' failed (rc 1): General error: # container shop-staging-web-1 is unhealthy`. Where the check of the -# variables fails, the line begins `the stack:`. The task, and with it the -# run, fails unless the line says deployed, unchanged or would deploy. +# arguments or the variables fails, the line begins `the stack:`. # -# --check, with --diff, runs 1 and 2 and shows whether compose.yaml would -# change, and how. It pulls, migrates and starts nothing, so it says nothing -# about the images, migrate or health. +# --check, with --diff, runs 1 to 5 and shows whether .env, .env.secret, +# compose.yaml and the route would change, and how, but for .env.secret. It +# writes nothing, takes no lock, and pulls, migrates and starts nothing, so it +# says nothing about the images, migrate or health. +- name: Read the environment + hosts: localhost + connection: local + gather_facts: false + vars_files: + - ../roles/deploy_user/defaults/main.yml # plexus_deploy_user + tasks: + - name: Read the environment's file and its secrets + ansible.builtin.include_role: + name: plexus.platform.stack + tasks_from: environment.yml + apply: { tags: [always] } + tags: [always] + - name: Deploy one environment of a stack - hosts: all + hosts: stack_host gather_facts: false + vars_files: + - ../roles/deploy_user/vars/main.yml # deploy_user_root + - ../roles/ingress/defaults/main.yml # ingress_fragments_dir roles: - - { role: plexus.platform.stack } + - { role: plexus.platform.stack, tags: [always] } diff --git a/ansible/platform/roles/apps/handlers/main.yml b/ansible/platform/roles/apps/handlers/main.yml deleted file mode 100644 index 16aaba86..00000000 --- a/ansible/platform/roles/apps/handlers/main.yml +++ /dev/null @@ -1,19 +0,0 @@ ---- -# Rotation closes inside the playbook (PLX-Secrets): environment is injected at -# container creation, so a rewritten .env or .env.secret rotates a file, not a -# credential, until the affected containers are re-created. A bare `up -d` — -# the same invocation the deploy verb and a human use, since compose reads -# .env implicitly and the image is pinned in the file — re-creates exactly the -# services whose environment differs. Skipped where the deploy verb has not -# placed a compose file yet. -- name: Re-create app containers - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ item }}" - loop: "{{ apps_dirs | default([]) }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_up | bool - register: apps_recreate - changed_when: "'Recreated' in apps_recreate.stderr or 'Started' in apps_recreate.stderr" - failed_when: apps_recreate.rc != 0 and 'no configuration file' not in apps_recreate.stderr diff --git a/ansible/platform/roles/apps/tasks/app.yml b/ansible/platform/roles/apps/tasks/app.yml deleted file mode 100644 index e09eb83c..00000000 --- a/ansible/platform/roles/apps/tasks/app.yml +++ /dev/null @@ -1,134 +0,0 @@ ---- -# The deployment's slug (§ 3 PLX-Platform): -, in every -# environment; the stack playbook works in the same directory under the same -# project name. -- name: "{{ app.name }} | resolve the deployment slug" - ansible.builtin.set_fact: - apps_slug: "{{ app.name ~ '-' ~ app.environment }}" - -- name: "{{ app.name }} | resolve app dir" - ansible.builtin.set_fact: - apps_dir: "{{ plexus_deploy_root }}/{{ apps_slug }}" - -- name: "{{ app.name }} | create app dir" - ansible.builtin.file: - path: "{{ apps_dir }}" - state: directory - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0750" - -# The app's run shape — compose.yaml — is NOT placed here. It lives in the -# app's source repo (an app repo, or the operations repo's own apps// for -# third-party software) and the deploy verb renders it at deploy time with the -# image pinned, so the compose file on the host always names the image it -# serves (§ 2 PLX-App). Three files in the app dir, one writer each (§ 3 PLX-Platform): -# this role owns .env, secrets owns .env.secret (PLX-Secrets), and -# the deploy verb owns compose.yaml. -# Compose reads .env from the project dir implicitly, so every invocation — -# the verb's, the rotation handler's, a human's — is a bare `docker compose`. - -# .env (§ 3 PLX-App, § 3 PLX-Platform), three sections: compose's own setting, the reserved -# PLEXUS_ bindings, then the non-secret values the inventory provides for the -# app (`app.env`). The project name is pinned to the deployment's slug, so that -# container, network and volume names never depend on where compose was -# invoked from. The loopback port is the one assigned -# in the inventory, interpolated by compose as ${PLEXUS_LOOPBACK_PORT:?…}, so a -# directory without this file refuses to start instead of publishing on a -# random port (PLX-Stack/LoopbackPort). This -# playbook is the file's only writer and always overwrites — the inventory is -# the truth. -- name: "{{ app.name }} | write .env (compose setting, platform bindings, values)" - ansible.builtin.copy: - dest: "{{ apps_dir }}/.env" - content: | - # Written by the platform playbook from the tenant inventory. Do not edit. - # Compose settings. - COMPOSE_PROJECT_NAME={{ apps_slug }} - - # Platform bindings (reserved PLEXUS_ prefix, § 4 PLX-App). - PLEXUS_LOOPBACK_PORT={{ app.loopback_port }} - - # Values from the inventory record, apps[].env (§ 3 PLX-Platform). - {% for key, value in (app.env | default({})).items() %} - {{ key }}={{ value }} - {% endfor %} - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0640" - notify: Re-create app containers - -- name: "{{ app.name }} | log in to GHCR as the deploy user" - ansible.builtin.command: - cmd: "docker login ghcr.io -u {{ plexus_ghcr_user }} --password-stdin" - stdin: "{{ plexus_ghcr_token }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_ghcr_token | length > 0 - no_log: true - changed_when: false - -# Nothing to bring up until the deploy verb has placed the run shape: a fresh -# host stays provisioned-but-empty until the first CI deploy (or a hand-run of -# the verb), which is the operator's supervised act (§ 6 PLX-Delivery). The -# verb pulls the image before it places compose.yaml, so a compose.yaml on the -# host means its image existed: an absent file is the one "new app" case, and -# a start that fails once the file is there is a failure, not a pending first -# deploy. (A registry such as GHCR answers `denied` for a missing image -# as for bad credentials, so the failure cannot be read for "not there yet".) -- name: "{{ app.name }} | check whether the deploy verb has placed compose.yaml" - ansible.builtin.stat: - path: "{{ apps_dir }}/compose.yaml" - register: apps_compose - -- name: "{{ app.name }} | nothing deployed yet (no compose.yaml), so nothing to start" - when: plexus_up | bool and not apps_compose.stat.exists - ansible.builtin.debug: - msg: >- - {{ app.name }}: no compose.yaml in {{ apps_dir }}, so nothing has been deployed yet and there is no image to start. - Run the CI deploy (or the deploy verb by hand) to bring it up. - -# Runs as the deploy user so a private registry works: that's where the GHCR -# login above put the credentials, and it's the same user the CI deploy verb -# uses. There is no separate pull: `up -d` pulls only the images the host does -# not hold (compose's default pull policy, `missing`), so an app whose image is -# on the host starts without the registry (a service that sets its own -# pull_policy, `always` for instance, still contacts it), and a playbook run no longer -# refreshes a floating tag, which fits a playbook that is not a deploy. -# -# A failure of the start does not stop the other apps: it is recorded (app, -# task, rc, output) in `apps_failures`, and the last play of the platform -# playbook fails the host once, listing every failed app, after the handlers -# and the lock-down roles have run. Only that play raises the failure: a -# playbook that uses this role without it must raise `apps_failures` itself. A failed app's dir is kept from the -# rotation handlers (this role's and the secrets role's), which would only run -# the failing `up -d` again; the next run's `up -d` re-creates it with the -# rotated environment. -- name: "{{ app.name }} | start" - when: plexus_up | bool and apps_compose.stat.exists - become: true - become_user: "{{ plexus_deploy_user }}" - block: - - name: "{{ app.name }} | docker compose up -d" - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ apps_dir }}" - register: apps_up - changed_when: "'Started' in apps_up.stderr or 'Recreated' in apps_up.stderr or 'Created' in apps_up.stderr" - rescue: - - name: "{{ app.name }} | record the failed start" - ansible.builtin.set_fact: - apps_failures: >- - {{ (apps_failures | default([])) + [{ - 'app': apps_slug, - 'dir': apps_dir, - 'task': ansible_failed_task.name, - 'rc': ansible_failed_result.rc | default('none'), - 'output': ([ansible_failed_result.stderr | default(''), ansible_failed_result.stdout | default(''), - ansible_failed_result.msg | default('')] | map('trim') | select | first | default('no output')) - }] }} - -- name: "{{ app.name }} | remember the app dir for the rotation handler" - when: apps_slug not in (apps_failures | default([]) | map(attribute='app') | list) - ansible.builtin.set_fact: - apps_dirs: "{{ (apps_dirs | default([])) + [apps_dir] }}" diff --git a/ansible/platform/roles/apps/tasks/main.yml b/ansible/platform/roles/apps/tasks/main.yml deleted file mode 100644 index 3fd949f2..00000000 --- a/ansible/platform/roles/apps/tasks/main.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- -# The app name is the join key across repos (§ 3 PLX-Platform): the inventory -# record, the host dir and the compose project all key on it, so it is unique -# per tenant and environment — across every app repo and this platform repo. -# Every record names its environment; the deployment's slug on the host is -# -, for every environment. The slug names the host dir and -# is the compose project's name (app.yml writes it to .env). A directory of an -# earlier layout is left as it was: no task here moves or removes one. -- name: Assert every app record names its environment - ansible.builtin.assert: - that: - - plexus_apps | rejectattr('environment', 'defined') | list | length == 0 - fail_msg: >- - {% set missing = plexus_apps | rejectattr('environment', 'defined') | map(attribute='name', default='?') | list -%} - plexus_apps: the record{{ 's' if missing | length > 1 else '' }} '{{ missing | join("', '") }}' - name{{ '' if missing | length > 1 else 's' }} no environment; every record names one, for example environment: production - -- name: Assert app names are unique per tenant and environment - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='name') | zip(plexus_apps | map(attribute='environment')) - | map('join', '@') | list | unique | length == plexus_apps | length - fail_msg: "Duplicate app in plexus_apps — one record per app and environment (§ 3 PLX-Platform)." - -- name: Configure and start each app - ansible.builtin.include_tasks: app.yml - loop: "{{ plexus_apps }}" - loop_control: - loop_var: app - label: "{{ app.name }}" diff --git a/ansible/platform/roles/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 8cb44cdd..5c634cd8 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,7 +1,21 @@ --- -# The unprivileged user that owns the app directories and runs the deploy -# verb over SSH (plexus_deploy_user, plexus_deploy_pubkey: shared with -# apps, so they keep the plexus_ prefix). +# The unprivileged user that owns the deploy root and as which the stack +# playbook deploys over SSH; the role creates both, and changes nothing below +# the root. The deploy root is no setting: vars/main.yml names it. +# +# The plexus_ variables are shared with other roles (plexus.host.docker adds +# the user to the docker group), so they keep that prefix; set them in the +# operations repo's group variables: +# plexus_deploy_pubkey the public key the deployer connects with; unset or +# empty: no key is authorized +# plexus_ghcr_user the registry login the user pulls the stacks' images +# plexus_ghcr_token with, renewed on every run; an unset or empty token: +# no login, the images are public or an earlier login stands + +# The user's name, by convention the same on every host: the stack playbook +# reads it from this file and connects as it where an environment's host names +# no user. +plexus_deploy_user: plexus # noqa: var-naming[no-role-prefix] # Further groups for the deploy user, e.g. the group an image's sshd policy # admits logins from. diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 136b30eb..ca7e2600 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -7,7 +7,16 @@ groups: "{{ deploy_user_groups }}" append: true -- name: Authorize the deploy key (CI runs the deploy verb as this user) +# Not recursive: what lies below is the stack playbook's. +- name: Give the deploy user the deploy root + ansible.builtin.file: + path: "{{ deploy_user_root }}" + state: directory + owner: "{{ plexus_deploy_user }}" + group: "{{ plexus_deploy_user }}" + mode: "0750" + +- name: Authorize the deploy key (the stack playbook connects as this user) ansible.posix.authorized_key: user: "{{ plexus_deploy_user }}" key: "{{ plexus_deploy_pubkey }}" @@ -18,3 +27,15 @@ ansible.builtin.debug: msg: Skipping deploy key authorization as plexus_deploy_pubkey is undefined or empty. when: plexus_deploy_pubkey | default('') | length == 0 + +# The stack playbook pulls on the host, as this user, so the credentials sit in +# the user's own Docker configuration. +- name: Log in to GHCR as the deploy user + ansible.builtin.command: + cmd: "docker login ghcr.io -u {{ plexus_ghcr_user }} --password-stdin" + stdin: "{{ plexus_ghcr_token }}" + become: true + become_user: "{{ plexus_deploy_user }}" + when: plexus_ghcr_token | default('') | length > 0 + no_log: true + changed_when: false diff --git a/ansible/platform/roles/deploy_user/vars/main.yml b/ansible/platform/roles/deploy_user/vars/main.yml new file mode 100644 index 00000000..78f23649 --- /dev/null +++ b/ansible/platform/roles/deploy_user/vars/main.yml @@ -0,0 +1,6 @@ +--- +# The deploy root, the one place it is written: the path the stack contract +# names for every environment (PLX-Stack/HostDirectory), so no setting, and in +# the role's vars, which no inventory overrides. The stack playbook reads this +# file for its stack_root. +deploy_user_root: /opt/stacks diff --git a/ansible/platform/roles/ingress/defaults/main.yml b/ansible/platform/roles/ingress/defaults/main.yml index c3c1f2a8..f9a46ae4 100644 --- a/ansible/platform/roles/ingress/defaults/main.yml +++ b/ansible/platform/roles/ingress/defaults/main.yml @@ -1,4 +1,14 @@ --- +# The directory of route fragments, owned by the deploy user; what a fragment +# is, and who writes it, is the header of tasks/main.yml. +ingress_fragments_dir: /etc/caddy/stacks + +# The maintenance page a stack's route serves while the stack does not +# answer: its language, title and text. +ingress_maintenance_lang: en +ingress_maintenance_title: Back in a minute +ingress_maintenance_text: This service is briefly unavailable for maintenance. This page refreshes automatically. + # Host-level settings of the Caddy server, rendered into the root Caddyfile. # They describe what sits in front of the host, so every tenant co-hosted on # the VM has to set them identically (§ 4 PLX-Tenancy keeps that to one tenant). diff --git a/ansible/platform/roles/ingress/tasks/main.yml b/ansible/platform/roles/ingress/tasks/main.yml index c3dade3c..b229b950 100644 --- a/ansible/platform/roles/ingress/tasks/main.yml +++ b/ansible/platform/roles/ingress/tasks/main.yml @@ -1,69 +1,126 @@ --- # Counterpart of caddy (PLX-Ingress): caddy installs and enables the server; -# this role owns the routing config and runs after it in the platform -# playbook, since the `caddy validate` step needs the binary. +# this role owns its configuration and runs after it in the platform playbook, +# since validating the configuration needs the binary. It knows no stack: it +# writes the root Caddyfile and prepares what the stack playbook writes routes +# with, and writes no route itself. +# +# What the stack playbook uses, by these names: +# - The directory of route fragments, ingress_fragments_dir +# (/etc/caddy/stacks), owned by the deploy user. One file per environment +# that has a hostname, -.caddy, and exactly +# { +# import stack +# } +# The root Caddyfile imports every *.caddy there and defines the snippet +# `stack`: the proxy to 127.0.0.1:, the refusal of /healthz and the +# maintenance page, the same for every stack. +# - The reload rule, /etc/sudoers.d/reload-caddy, exactly +# ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy +# run as `sudo -n /usr/bin/systemctl reload caddy`, a command of its own: +# Ansible's become cannot use the rule, since it wraps every command in a +# shell. The reload reads the whole configuration again; where it is +# invalid (a fragment that does not parse, a hostname that two files +# serve), the reload fails, the proxy goes on serving what it served, and +# every later reload, of any stack's, and this role's validation fail too +# until the file is mended or removed. The deploy user can run +# `caddy validate --config /etc/caddy/Caddyfile` first. +# +# What a fragment can do: whoever writes one configures the proxy whole, as +# the proxy's user. A fragment can serve any file that user reads, listen on +# another port, and reach the proxy's admin API; a global block in it, such +# as `{ admin off }`, is taken by the reload and makes every later reload fail +# until root restarts the proxy. The refusal of /healthz reaches a route only +# because its fragment imports the snippet `stack`. That is the deployer's +# trust by another path, since a key that deploys to a host is root on it +# through Docker anyway; the stack playbook writes fragments of the one shape +# above and nothing else. +# +# While a host migrates, the routes of earlier versions and the fragments +# coexist. Earlier versions rendered every route of the host from plexus_apps +# into /etc/caddy/apps.caddy; this role no longer writes that file and never +# removes it, and the root Caddyfile imports it, where it was there when the +# root was written, beside the fragments. The proxy refuses a hostname that +# both serve, so a person takes an environment's hostname out of apps.caddy +# before the environment's first deploy that writes its fragment: the old +# route goes on being served until that deploy's reload moves the hostname to +# the fragment. A fragment serves a hostname whole: a hostname apps.caddy +# splits by path prefix among several deployments moves to one environment, +# or each deployment takes a hostname of its own. Once apps.caddy holds no +# route, the person deletes it; the next run of this role drops its import. -# Host→port→app is one inventory record per app, so per-VM port uniqueness -# is checkable right here instead of being coordination state (PLX-Ingress). -- name: Assert loopback ports are unique per VM - ansible.builtin.assert: - that: - - plexus_apps | map(attribute='loopback_port') | list | unique | length == plexus_apps | length - fail_msg: "Duplicate loopback port in plexus_apps — each app needs its own loopback_port." +- name: Look for the routes of earlier versions + ansible.builtin.stat: + path: /etc/caddy/apps.caddy + register: ingress_earlier_routes -# A host is one site; the apps on it are told apart by path prefix (PLX-Ingress). -# A prefix is a plain path — leading slash, no trailing slash, no wildcard — -# and each host serves at most one app per prefix, and at most one at its root. -- name: Assert app path prefixes are well-formed - ansible.builtin.assert: - that: - - plexus_apps | selectattr('path', 'defined') | map(attribute='path') | reject('match', '^(/[A-Za-z0-9._~-]+)+$') | list | length == 0 - fail_msg: "apps[].path must look like /name or /a/b — leading slash, no trailing slash, no wildcard." +# The deploy user's one privilege, the reload rule of the header. Before the +# fragment directory: a rule its validation refuses fails the run here. +- name: Let the deploy user reload the proxy, and do nothing else as root + ansible.builtin.copy: + dest: /etc/sudoers.d/reload-caddy + content: | + # Managed by Ansible (plexus.platform.ingress). + {{ plexus_deploy_user }} ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy + owner: root + group: root + mode: "0440" + validate: visudo -cf %s -- name: Assert each host serves one app per path prefix - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='host') | zip(plexus_apps | map(attribute='path', default='')) - | map('join') | list | unique | length == plexus_apps | length - fail_msg: "Two apps in plexus_apps share a host and a path prefix (or both serve the host's root)." - -# The routes are one file, apps.caddy, rendered from the host's app records; -# a host runs one tenant's apps and nothing else (§ 4 PLX-Tenancy). It lands -# before the root stub so the stub's import resolves when it is validated. -- name: Configure the routes (reverse proxy + automatic HTTPS) - ansible.builtin.template: - src: Caddyfile.j2 - dest: /etc/caddy/apps.caddy - mode: "0644" - validate: "caddy validate --config %s --adapter caddyfile" - notify: Reload caddy - -# Versions before 0.114.0 wrote the routes to tenants/.caddy; the stub -# no longer imports that directory, and a leftover would only confuse. -- name: Remove the per-tenant routing directory of earlier versions +# Not recursive: the fragments in it are the stack playbook's. +- name: Give the deploy user the directory of route fragments ansible.builtin.file: - path: /etc/caddy/tenants - state: absent - notify: Reload caddy + path: "{{ ingress_fragments_dir }}" + state: directory + owner: "{{ plexus_deploy_user }}" + group: "{{ plexus_deploy_user }}" + mode: "0755" - name: Load Cloudflare's ranges ansible.builtin.include_vars: file: cloudflare.yml when: ingress_trusted_proxies == 'cloudflare' -# No validate: here — ansible validates a temp copy in a temp dir, where the -# stub's relative import glob cannot resolve. The real check is the next task. -- name: Write the root Caddyfile (host-level options, import of the routes) - ansible.builtin.template: - src: root.Caddyfile.j2 - dest: /etc/caddy/Caddyfile - mode: "0644" - notify: Reload caddy +# A dry run on a fresh host has no binary yet: the caddy role installs it. +- name: Look for the proxy's binary + ansible.builtin.stat: + path: /usr/bin/caddy + register: ingress_caddy + +# A configuration Caddy refuses, the root that would replace the one in place +# or the whole on disk, is recorded in ingress_invalid and fails the host only +# in the last play of the platform playbook, after the lock-down roles: a +# route someone broke never keeps a host from its firewall and sshd settings. +# A playbook that uses this role without that play raises ingress_invalid +# itself. +- name: Write and validate the proxy's configuration + block: + # Validated as a whole before it replaces the one in place, with every + # file it imports: their paths are absolute, so they resolve from the + # copy too. + - name: Write the root Caddyfile + ansible.builtin.template: + src: root.Caddyfile.j2 + dest: /etc/caddy/Caddyfile + mode: "0644" + validate: caddy validate --config %s --adapter caddyfile + notify: Reload caddy + + # The whole configuration as the proxy reads it on its next reload, the + # fragments and apps.caddy included, in every run and in a dry run too: + # the template validates only a root that changes. It changes nothing. + - name: Validate the proxy's whole configuration + when: ingress_caddy.stat.exists + ansible.builtin.command: + cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + changed_when: false + check_mode: false -# Validates the combined config in place, root stub plus routes, before the -# reload handler fires at end of play. -- name: Validate the assembled Caddy config - ansible.builtin.command: - cmd: caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - changed_when: false + rescue: + - name: Record what Caddy says of the configuration + ansible.builtin.set_fact: + ingress_invalid: >- + '{{ ansible_failed_task.name }}' failed: + {{ (ansible_failed_result.stderr | default('')).splitlines() | select('search', '"level":"error"') + | map('from_json') | map(attribute='msg') | join('; ') + or ansible_failed_result.msg | default('no message', true) }} diff --git a/ansible/platform/roles/ingress/templates/Caddyfile.j2 b/ansible/platform/roles/ingress/templates/Caddyfile.j2 deleted file mode 100644 index 244c4139..00000000 --- a/ansible/platform/roles/ingress/templates/Caddyfile.j2 +++ /dev/null @@ -1,61 +0,0 @@ -# Managed by Ansible (plexus.platform.ingress) — one route per app record on this host. -# Imported by /etc/caddy/Caddyfile. -# Caddy obtains + renews Let's Encrypt certs automatically for each host -# below (needs DNS → this host and ports 80/443 open). -# One site per host: apps sharing a host each take a path prefix (`path:` in -# the inventory record); an app without one serves the host's root. The -# prefix is stripped before the request reaches the app, so the app serves -# from its own root and learns its public URL from its environment. -# -# /healthz is refused from outside, for every app, root and prefixed alike: -# defence in depth for apps whose healthcheck answers on that conventional -# path, which publicly would tell anyone whether the app's dependencies are -# up. The deploy does not depend on it; it reads the container's health from -# Docker on the host. -{% for host, apps in plexus_apps | groupby('host') %} -{{ host }} { - encode zstd gzip -{% for app in apps %} -{% if app.path is defined %} - # {{ app.name }}{% if app.environment is defined %} ({{ app.environment }}){% endif %}, under {{ app.path }}/ - redir {{ app.path }} {{ app.path }}/ - handle_path {{ app.path }}/* { -{% else %} - # {{ app.name }}{% if app.environment is defined %} ({{ app.environment }}){% endif %} - - handle { -{% endif %} - respond /healthz 403 - reverse_proxy 127.0.0.1:{{ app.loopback_port }} - } -{% endfor %} -{% if apps | selectattr('path', 'undefined') | list | length == 0 %} - # No app serves this host's root. - handle { - respond 404 - } -{% endif %} - # Backend unreachable (deploy rollout, crash, migration window): serve a - # plain maintenance page instead of a bare 502. Auto-refreshes; Retry-After - # keeps well-behaved clients polling. Tenants override the copy via - # ingress_maintenance_lang / _title / _text in their inventory. - handle_errors { - @backend_down expression `{err.status_code} in [502, 503, 504]` - handle @backend_down { - header Retry-After 120 - header Content-Type "text/html; charset=utf-8" - respond < - - - {{ ingress_maintenance_title | default('Back in a minute') }} - -
-

{{ ingress_maintenance_title | default('Back in a minute') }}

-

{{ ingress_maintenance_text | default('This service is briefly unavailable for maintenance. This page refreshes automatically.') }}

-
- MAINTENANCE 503 - } - } -} -{% endfor %} diff --git a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 index a79a69a5..ade5709f 100644 --- a/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 +++ b/ansible/platform/roles/ingress/templates/root.Caddyfile.j2 @@ -1,5 +1,4 @@ -# Managed by Ansible (plexus.platform.ingress). The routes live in apps.caddy, -# rendered from this host's app records; the options below are host-level +# Managed by Ansible (plexus.platform.ingress). The options below are host-level # (what sits in front of this VM). {% set trusted = ingress_cloudflare_ranges if ingress_trusted_proxies == 'cloudflare' else ingress_trusted_proxies %} {% if ingress_proxy_protocol_from or trusted %} @@ -24,4 +23,48 @@ } } {% endif %} -import apps.caddy + +# What every stack's route does but its hostname and port, imported by each +# route fragment (its shape: the header of the ingress role's tasks). +# /healthz is refused from outside, for every stack: defence in depth for +# stacks whose healthcheck answers on that conventional path, which publicly +# would tell anyone whether their dependencies are up. The deploy does not +# depend on it; it reads the containers' health from Docker on the host. +# Where the stack does not answer (a deploy, a crash, a migration), a plain +# maintenance page instead of a bare 502, which refreshes itself; Retry-After +# keeps well-behaved clients polling. +(stack) { + encode zstd gzip + respond /healthz 403 + reverse_proxy 127.0.0.1:{args[0]} + handle_errors { + @backend_down expression `{err.status_code} in [502, 503, 504]` + handle @backend_down { + header Retry-After 120 + header Content-Type "text/html; charset=utf-8" + respond < + + + {{ ingress_maintenance_title }} + +
+

{{ ingress_maintenance_title }}

+

{{ ingress_maintenance_text }}

+
+ MAINTENANCE 503 + } + } +} +{% if ingress_earlier_routes.stat.exists %} + +# The routes earlier versions rendered from the inventory's records, left as +# they were until removed by hand. A pattern, not the path: Caddy imports +# nothing for a pattern that matches no file but refuses a missing path, so +# apps.caddy can be deleted without a run of the platform playbook. Keep no +# other file here whose name begins with apps and ends in .caddy. +import /etc/caddy/apps*.caddy +{% endif %} + +# The stacks' route fragments. +import {{ ingress_fragments_dir }}/*.caddy diff --git a/ansible/platform/roles/secrets/handlers/main.yml b/ansible/platform/roles/secrets/handlers/main.yml deleted file mode 100644 index 619f13ac..00000000 --- a/ansible/platform/roles/secrets/handlers/main.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -# Rotation closes inside the playbook (§ 2 PLX-Secrets): environment is -# injected at container creation, so a rewritten .env.secret rotates a file, -# not a credential, until the affected containers are re-created. A bare -# `up -d` — the same invocation the deploy verb and a human use, since compose -# reads .env implicitly and the image is pinned in the file — re-creates -# exactly the services whose environment differs. Skipped where the deploy -# verb has not placed a compose file yet, and in check mode, where a new -# deployment's dir does not exist yet and the command would fail on chdir -# before it could skip itself. An app the apps role failed to start is left -# out: the same `up -d` would only fail again, and the playbook reports it. -- name: Re-create app containers for rotated secrets - ansible.builtin.command: - cmd: docker compose up -d - chdir: "{{ item }}" - loop: "{{ secrets_dirs | default([]) | difference(apps_failures | default([]) | map(attribute='dir') | list) }}" - become: true - become_user: "{{ plexus_deploy_user }}" - when: plexus_up | bool and not ansible_check_mode - register: secrets_recreate - changed_when: "'Recreated' in secrets_recreate.stderr or 'Started' in secrets_recreate.stderr" - failed_when: (secrets_recreate.rc | default(1)) != 0 and 'no configuration file' not in (secrets_recreate.stderr | default('')) diff --git a/ansible/platform/roles/secrets/tasks/app.yml b/ansible/platform/roles/secrets/tasks/app.yml deleted file mode 100644 index 0121c9e0..00000000 --- a/ansible/platform/roles/secrets/tasks/app.yml +++ /dev/null @@ -1,46 +0,0 @@ ---- -# The deployment's slug (§ 3 PLX-Platform): -, in every -# environment, as the apps role lays it out. -- name: "{{ app.name }} | resolve the deployment slug" - ansible.builtin.set_fact: - secrets_slug: "{{ app.name ~ '-' ~ app.environment }}" - -- name: "{{ app.name }} | resolve app dir" - ansible.builtin.set_fact: - secrets_dir: "{{ plexus_deploy_root }}/{{ secrets_slug }}" - -# The app dir is laid out by apps (§ 3 PLX-Platform); this role runs -# before it so that the first `up` already sees the secrets, and creates the -# dir identically when it is first here. -- name: "{{ app.name }} | create app dir" - ansible.builtin.file: - path: "{{ secrets_dir }}" - state: directory - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0750" - -# Substance stays on the host: per-app secrets from the tenant's `app.secrets` -# dict — op:// pointers, resolved from the vault here via the 1Password CLI -# the playbook wrapper already runs under — injected into the container by the -# app's compose `env_file`. Never world-readable. Three files in the app dir, -# one writer each (§ 3 PLX-Platform): this role owns .env.secret. -- name: "{{ app.name }} | write .env.secret (vault-resolved secrets)" - ansible.builtin.copy: - dest: "{{ secrets_dir }}/.env.secret" - content: | - # Written by the platform playbook from the tenant inventory, apps[].secrets, - # resolved from the vault (PLX-Secrets). Do not edit. - {% for key, ref in app.secrets.items() %} - {{ key }}={{ lookup('ansible.builtin.pipe', 'op read ' ~ (ref | quote)) }} - {% endfor %} - owner: "{{ plexus_deploy_user }}" - group: "{{ plexus_deploy_user }}" - mode: "0600" - when: app.secrets is defined - no_log: true - notify: Re-create app containers for rotated secrets - -- name: "{{ app.name }} | remember the app dir for the rotation handler" - ansible.builtin.set_fact: - secrets_dirs: "{{ (secrets_dirs | default([])) + [secrets_dir] }}" diff --git a/ansible/platform/roles/secrets/tasks/main.yml b/ansible/platform/roles/secrets/tasks/main.yml deleted file mode 100644 index d011b96f..00000000 --- a/ansible/platform/roles/secrets/tasks/main.yml +++ /dev/null @@ -1,30 +0,0 @@ ---- -# Secrets are vault references, never values (PLX-Secrets): every entry of -# apps[].secrets is an op:// pointer, resolved below at playbook time. -- name: Assert app secrets are op:// pointers - ansible.builtin.assert: - that: - - >- - plexus_apps | map(attribute='secrets', default={}) | map('dict2items') | flatten - | map(attribute='value') | reject('match', '^op://') | list | length == 0 - fail_msg: "Every apps[].secrets value must be an op://vault/item/field pointer (PLX-Secrets) — values never live in git." - -# The app dir is named - (app.yml); this role runs before -# apps in the platform playbook, so it holds the records to that first. The -# apps role has the same check: each role stands alone, and one shared check -# would make one of them include a task file of the other. -- name: Assert every app record names its environment - ansible.builtin.assert: - that: - - plexus_apps | rejectattr('environment', 'defined') | list | length == 0 - fail_msg: >- - {% set missing = plexus_apps | rejectattr('environment', 'defined') | map(attribute='name', default='?') | list -%} - plexus_apps: the record{{ 's' if missing | length > 1 else '' }} '{{ missing | join("', '") }}' - name{{ '' if missing | length > 1 else 's' }} no environment; every record names one, for example environment: production - -- name: Write each app's secrets - ansible.builtin.include_tasks: app.yml - loop: "{{ plexus_apps }}" - loop_control: - loop_var: app - label: "{{ app.name }}" diff --git a/ansible/platform/roles/stack/defaults/main.yml b/ansible/platform/roles/stack/defaults/main.yml index a63da470..6ecd63ba 100644 --- a/ansible/platform/roles/stack/defaults/main.yml +++ b/ansible/platform/roles/stack/defaults/main.yml @@ -3,13 +3,25 @@ # plexus.platform.stack mounts; its header says what it does, in order. # # Given on every run, with no default (`-e`, as `plx deploy` passes them): -# stack_name the stack's name, as in `shop` -# stack_environment the environment's name, one lowercase word, as in `staging` -# stack_compose_file the stack's rendered compose file on the machine that -# runs the playbook, every app's image pinned by digest +# stack_name the stack's name, as in `shop` +# stack_environment_file the environment's file on the machine that runs +# the playbook, as in `stack/staging.yaml`; the +# environment is named after it +# stack_compose_file the stack's rendered compose file on that machine, +# every app's image pinned by digest -# Where the environments live on the host, each in /-. -stack_root: /opt/stacks +# Where the environments live on the host, each in /-: +# the deploy root, which the playbook reads from the role deploy_user's vars. +stack_root: "{{ deploy_user_root }}" + +# The ports an environment's loopback port is taken from, -: the +# lowest that no other environment on the host holds, taken once and kept. +stack_port_range: 20000-20999 + +# How long, in seconds, each `op read` may take where the playbook runs +# before the deploy fails; a read that hangs waits mostly for an unlock +# nobody answers. +stack_secret_timeout: 30 # How long, in seconds, the deploy waits for every service that declares a # healthcheck to turn healthy: the whole wait, which a healthcheck's diff --git a/ansible/platform/roles/stack/files/route.sh b/ansible/platform/roles/stack/files/route.sh new file mode 100755 index 00000000..574b1db8 --- /dev/null +++ b/ansible/platform/roles/stack/files/route.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# The port and the route of one environment, run on the host as the deploy +# user by the stack role (tasks/main.yml), where the environment has a +# hostname. Under the lock /.lock, which a second run waits for, it +# 1. refuses the hostname where the route fragment of another environment +# serves it; +# 2. takes the environment's loopback port from its .env, and where that +# names none, the lowest port of the range that neither another +# directory's .env nor another environment's fragment names, and that +# nothing on the host listens on (TCP, IPv4 and IPv6, as /proc/net/tcp +# and /proc/net/tcp6 list it, which every Linux host has); +# 3. writes the fragment /.caddy where its text changes, +# and reloads the proxy through the deploy user's one sudo rule; where the +# proxy refuses the reload, it puts back what was there, and says what +# `caddy validate` says of the configuration with the new fragment, which +# the deploy user can run (the ingress role's header). +# It prints `port= route=changed|unchanged`, or why it refuses, and then +# exits 1. With `check` last it takes no lock, writes and reloads nothing, and +# prints what it would do. The fragment's shape and the reload rule are the +# ingress role's (the header of its tasks/main.yml). +# +# route.sh - [check] +set -eu +root=$1 fragments=$2 project=$3 hostname=$4 first=${5%-*} last=${5#*-} check=${6:-} +fragment=$fragments/$project.caddy + +if [ "$check" != check ]; then + command -v flock >/dev/null || { echo "flock, of util-linux, is not on this host; the deploy takes its lock with it"; exit 1; } + exec 9>>"$root/.lock" + flock -w 300 9 || { echo "$root/.lock is held by another deploy and was not released within 300 seconds"; exit 1; } +fi + +# The hostnames a fragment serves: the addresses before its first `{`, without +# a scheme or a port. +served() { + sed -n '1{s/{.*//;s/,/ /g;p;}' "$1" | tr '[:upper:]' '[:lower:]' | tr -s ' \t' '\n' | sed 's|^[a-z]*://||;s|:[0-9]*$||' +} +for other in "$fragments"/*.caddy; do + [ -f "$other" ] && [ "$other" != "$fragment" ] || continue + if served "$other" | grep -qxF "$hostname"; then + echo "$hostname is the hostname of $(basename "$other" .caddy) on this host, whose route $other serves it" + exit 1 + fi +done + +port_in() { sed -n "s/^PLEXUS_LOOPBACK_PORT=[\"']\{0,1\}\([0-9][0-9]*\).*/\1/p" "$1" 2>/dev/null | tail -1; } +port=$(port_in "$root/$project/.env") +if [ -z "$port" ]; then + taken=" " + for env in "$root"/*/.env; do + [ -f "$env" ] && [ "$env" != "$root/$project/.env" ] && taken="$taken$(port_in "$env") " + done + for other in "$fragments"/*.caddy; do + [ -f "$other" ] && [ "$other" != "$fragment" ] && + taken="$taken$(sed -n 's/^[[:space:]]*import stack \([0-9][0-9]*\).*/\1/p' "$other" | tr '\n' ' ')" + done + # The local port, in hex, of each socket in state 0A, LISTEN. + for hex in $(cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | sed -n 's/^ *[0-9]*: [0-9A-Fa-f]*:\([0-9A-Fa-f]*\) [0-9A-Fa-f]*:[0-9A-Fa-f]* 0A .*/\1/p'); do + taken="$taken$((0x$hex)) " + done + port=$first + while case "$taken" in *" $port "*) true ;; *) false ;; esac; do port=$((port + 1)); done + [ "$port" -le "$last" ] || { echo "no port from $first to $last is free on this host for $project"; exit 1; } +fi + +text=$(printf '%s {\n\timport stack %s\n}' "$hostname" "$port") +if [ -f "$fragment" ] && [ "$(cat "$fragment")" = "$text" ]; then + echo "port=$port route=unchanged" + exit 0 +fi +if [ "$check" != check ]; then + previous=$(cat "$fragment" 2>/dev/null) && had=1 || had=0 + printf '%s\n' "$text" >"$fragment.new" && mv "$fragment.new" "$fragment" + if ! sudo -n /usr/bin/systemctl reload caddy >/dev/null 2>&1; then + # Its error, as a line `Error: …` or a log line of level error. + why=$(caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile 2>&1 | + sed -n -e 's/^Error: //p' -e 's/.*"level":"error".*"msg":"\([^"]*\)".*/\1/p' | tail -1) + if [ "$had" = 1 ]; then printf '%s\n' "$previous" >"$fragment.new" && mv "$fragment.new" "$fragment"; else rm -f "$fragment"; fi + echo "the proxy refused to reload with the route of $hostname, which is as it was${why:+: caddy validate says $why}" + exit 1 + fi +fi +echo "port=$port route=changed" diff --git a/ansible/platform/roles/stack/tasks/environment.yml b/ansible/platform/roles/stack/tasks/environment.yml new file mode 100644 index 00000000..ffb3b7ac --- /dev/null +++ b/ansible/platform/roles/stack/tasks/environment.yml @@ -0,0 +1,137 @@ +--- +# Steps 1 and 2 of the playbook's header, where the playbook runs: the +# variables, the environment's file, its secrets, and the one host it names, +# added to the group stack_host with what the deploy there reads. +- name: Read the environment + block: + # The run is whole and its one host the file's: a --limit or a tag would + # leave out the deploy, or the line that says how it ended. + - name: Check the arguments + ansible.builtin.assert: + that: + - ansible_limit is not defined + - ansible_run_tags | list == ['all'] + - ansible_skip_tags | length == 0 + fail_msg: the stack playbook takes no --limit, --tags or --skip-tags; it deploys the environment's file whole + quiet: true + + - name: Check the variables + ansible.builtin.assert: + that: + - stack_name | default('') is match('^[a-z0-9][a-z0-9_-]*$') + - stack_environment_file | default('') | basename is match('^[a-z]+\.yaml$') + - stack_compose_file | default('') | length > 0 + fail_msg: >- + the stack playbook deploys one environment of a stack: a stack_name of lowercase letters, digits, - and _, + a stack_environment_file named after the environment, .yaml, and a stack_compose_file + quiet: true + + - name: Name the environment's project after the stack and the file + ansible.builtin.set_fact: + stack_project: "{{ stack_name }}-{{ stack_environment_file | basename | regex_replace('\\.yaml$', '') }}" + + - name: Read the environment's file + ansible.builtin.set_fact: + stack_file: "{{ lookup('ansible.builtin.file', stack_environment_file) | from_yaml }}" + + # What the playbook needs to write the files faithfully; plx doctor checks + # the file whole (packages/lib/src/environments.ts). The forms are the + # role's vars. + - name: Check the environment's file + vars: + file: "{{ stack_file if stack_file is mapping else {} }}" + env: "{{ file.env | default({}, true) }}" + secrets: "{{ file.secrets | default({}, true) }}" + names: "{{ (env.keys() | list) + (secrets.keys() | list) if env is mapping and secrets is mapping else [] }}" + ansible.builtin.assert: + that: + - stack_file is mapping + - file.keys() | difference(['host', 'hostname', 'env', 'secrets']) | length == 0 + - file.host | default('') is string + - file.host | default('') is match(stack_host_form) + - file.hostname is not defined or (file.hostname is string and file.hostname | lower is match(stack_hostname_form)) + - env is mapping and env.values() | select('string') | list | length == env | length + - secrets is mapping and secrets.values() | select('string') | select('match', 'op://') | list | length == secrets | length + - names | reject('match', '^[A-Za-z_][A-Za-z0-9_]*$') | list | length == 0 + - names | length == names | unique | length + # Of the names PLATFORM_VARIABLES lists (packages/lib/src/environments.ts), the two this playbook writes. + - names | intersect(['COMPOSE_PROJECT_NAME', 'PLEXUS_LOOPBACK_PORT']) | length == 0 + fail_msg: >- + {{ stack_environment_file }} is not an environment the playbook can write: a map of host, an SSH destination + [user@]address[:port], hostname, a DNS name, env, names to strings, and secrets, names to op:// pointers, no + name in both and none the playbook writes itself; plx doctor says what is wrong + quiet: true + + # Each pointer resolved where the playbook runs, by the vault's CLI and the + # session or token it finds there; the value as the vault holds it, a + # trailing newline included. Read in a dry run too, to tell whether + # .env.secret would change. Each read is given stack_secret_timeout seconds + # by the Python that runs Ansible, which kills op where it does not answer + # and exits 124. + - name: Resolve the secrets + ansible.builtin.command: + argv: + - "{{ ansible_playbook_python }}" + - -c + - | + import subprocess, sys + try: + sys.exit(subprocess.run(['op', 'read', '--no-newline', sys.argv[2]], timeout=float(sys.argv[1])).returncode) + except subprocess.TimeoutExpired: + sys.exit(124) + except FileNotFoundError: + sys.exit('op, the vault\'s CLI, is not on the PATH') + - "{{ stack_secret_timeout }}" + - "{{ item.value }}" + strip_empty_ends: false + loop: "{{ stack_file.secrets | default({}, true) | dict2items }}" + register: stack_reads + changed_when: false + failed_when: false + check_mode: false + no_log: true + + # A value that is empty in the vault is refused: it is never a secret, and + # mostly a field that was never filled. The line names the pointer, never + # a value. + - name: Check that every secret was read + when: (stack_failed_reads + stack_empty_reads) | length > 0 + vars: + stack_failed_reads: "{{ stack_reads.results | default([]) | rejectattr('rc', 'equalto', 0) | list }}" + stack_empty_reads: "{{ stack_reads.results | default([]) | selectattr('rc', 'equalto', 0) | selectattr('stdout', 'equalto', '') | list }}" + stack_failed: "{{ (stack_failed_reads + stack_empty_reads) | first }}" + ansible.builtin.fail: + msg: >- + the secret {{ stack_failed.item.key }} ({{ stack_failed.item.value }}) + {{ 'is empty in the vault' if stack_failed.rc == 0 + else ('could not be read: op read did not answer within ' ~ stack_secret_timeout ~ ' seconds, mostly because it waits' + ~ ' for an unlock nobody answers: a locked app or an expired session where it runs') if stack_failed.rc == 124 + else ('could not be read: ' ~ (stack_failed.stderr | default('', true) or stack_failed.msg | default('no message')).splitlines() | last) }} + + - name: Add the environment's host + vars: + target: "{{ stack_file.host | regex_search(stack_host_form, '\\1', '\\2', '\\3', '\\4', '\\5', '\\6') }}" + ansible.builtin.add_host: + name: "{{ target[1] or target[3] or target[5] }}" + groups: [stack_host] + ansible_host: "{{ target[1] or target[3] or target[5] }}" + ansible_user: "{{ target[0] or plexus_deploy_user }}" + ansible_port: "{{ target[2] or target[4] or 22 }}" + stack_project: "{{ stack_project }}" + stack_hostname: "{{ stack_file.hostname | default('') | lower }}" + stack_env: "{{ stack_file.env | default({}, true) }}" + stack_secrets: >- + {{ dict(stack_reads.results | default([]) | map(attribute='item.key') + | zip(stack_reads.results | default([]) | map(attribute='stdout'))) }} + no_log: true + changed_when: false + + rescue: + - name: Note why the environment was not read + ansible.builtin.set_fact: + stack_outcome: >- + failed: '{{ ansible_failed_task.name }}' failed: + {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} + + - name: Say why + ansible.builtin.include_tasks: result.yml diff --git a/ansible/platform/roles/stack/tasks/main.yml b/ansible/platform/roles/stack/tasks/main.yml index 5cbd26c3..61ad8900 100644 --- a/ansible/platform/roles/stack/tasks/main.yml +++ b/ansible/platform/roles/stack/tasks/main.yml @@ -1,70 +1,124 @@ --- -- name: Deploy, and roll back what a failure after the write of compose.yaml leaves +# Steps 3 to 8 of the playbook's header, on the environment's host as the +# deploy user; tasks/environment.yml has read the environment before. +- name: Deploy, and roll back what a failure after the first write leaves block: - - name: Check the variables - ansible.builtin.assert: - that: - - ansible_play_hosts_all | length == 1 - - stack_name | default('') is match('^[a-z0-9][a-z0-9_-]*$') - - stack_environment | default('') is match('^[a-z0-9]+$') - - stack_compose_file | default('') | length > 0 - fail_msg: >- - the stack playbook deploys one environment onto one host: an inventory of one host, a stack_name of - lowercase letters, digits, - and _, a stack_environment of lowercase letters and digits, and a - stack_compose_file - quiet: true - - - name: Resolve the environment's project, directory and compose file + - name: Resolve the environment's directory and files ansible.builtin.set_fact: - stack_project: "{{ stack_name }}-{{ stack_environment }}" - stack_dir: "{{ stack_root }}/{{ stack_name }}-{{ stack_environment }}" + stack_dir: "{{ stack_root }}/{{ stack_project }}" stack_compose: "{{ stack_compose_file | ansible.builtin.realpath }}" + stack_files: [.env, .env.secret, compose.yaml] + stack_replaced: [] - - name: Look for the environment's directory + - name: Look for the deploy root ansible.builtin.stat: - path: "{{ stack_dir }}" - register: stack_laid_out + path: "{{ stack_root }}" + register: stack_root_found - - name: Look for the environment's .env - ansible.builtin.stat: - path: "{{ stack_dir }}/.env" - register: stack_env - - - name: Check that the platform playbook has laid the environment out + - name: Check that the platform has prepared the host ansible.builtin.assert: that: - - stack_laid_out.stat.isdir | default(false) - - stack_env.stat.exists + - stack_root_found.stat.isdir | default(false) + - stack_root_found.stat.writeable fail_msg: >- - {{ stack_dir ~ ('/.env' if stack_laid_out.stat.exists else '') }} is not there; the platform playbook - lays out an environment's directory and writes its .env before the environment's first deploy + {{ stack_root }} is not there, or not the deploy user's; the platform playbook prepares a host for stacks quiet: true - - name: Read the compose file + - name: Claim the port and write the route + when: stack_hostname | length > 0 + ansible.builtin.script: + cmd: >- + route.sh {{ stack_root | quote }} {{ ingress_fragments_dir | quote }} {{ stack_project | quote }} {{ stack_hostname | quote }} + {{ stack_port_range | quote }} {{ 'check' if ansible_check_mode else '' }} + register: stack_route + changed_when: "'route=changed' in stack_route.stdout" + failed_when: false + check_mode: false + + - name: Check that the route was claimed + when: stack_route is not skipped and stack_route.rc != 0 + ansible.builtin.fail: + msg: "{{ (stack_route.stdout_lines + stack_route.stderr_lines) | first | default(stack_route.msg) }}" + + - name: Lay out the environment's directory + ansible.builtin.file: + path: "{{ stack_dir }}" + state: directory + mode: "0750" + + # COMPOSE_PROJECT_NAME and PLEXUS_LOOPBACK_PORT are two of the names + # PLATFORM_VARIABLES lists (packages/lib/src/environments.ts). + - name: Render .env and read the compose file ansible.builtin.set_fact: stack_text: "{{ lookup('ansible.builtin.file', stack_compose, rstrip=false) }}" + stack_env_text: >- + {{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_env + | combine({'COMPOSE_PROJECT_NAME': stack_project}) + | combine({'PLEXUS_LOOPBACK_PORT': stack_route.stdout | regex_findall('port=([0-9]+)') | first} + if stack_route is not skipped else {})}) }} + + # The lookup gives no string, but none, for an environment without secrets. + - name: Render .env.secret + ansible.builtin.set_fact: + stack_secret_text: "{{ lookup('ansible.builtin.template', 'dotenv.j2', template_vars={'variables': stack_secrets}) or '' }}" + no_log: true - - name: Look for the compose.yaml in place + - name: Look for the files in place ansible.builtin.stat: - path: "{{ stack_dir }}/compose.yaml" + path: "{{ stack_dir }}/{{ item }}" checksum_algorithm: sha1 - register: stack_present + loop: "{{ stack_files }}" + register: stack_in_place + + # .env.secret where the environment has secrets, or one is there already. + - name: Note the files that change + when: >- + (item.item != '.env.secret' or stack_secrets | length > 0 or item.stat.exists) + and (not item.stat.exists or item.stat.checksum != stack_new[item.item] | hash('sha1')) + vars: + stack_new: { .env: "{{ stack_env_text }}", .env.secret: "{{ stack_secret_text }}", compose.yaml: "{{ stack_text }}" } + ansible.builtin.set_fact: + stack_replaced: "{{ stack_replaced + [item.item] }}" + loop: "{{ stack_in_place.results }}" + loop_control: + label: "{{ item.item }}" - # Nothing to pull or migrate where the file is the one in place: Compose - # re-creates nothing then, and the run reports no change. - - name: Compare the compose file with the one in place + - name: Note which files were there ansible.builtin.set_fact: - stack_changed: "{{ not stack_present.stat.exists or stack_present.stat.checksum != stack_text | hash('sha1') }}" + stack_existed: "{{ dict(stack_files | zip(stack_in_place.results | map(attribute='stat.exists'))) }}" + stack_changed: "{{ 'compose.yaml' in stack_replaced }}" stack_services: "{{ (stack_text | from_yaml).services | default({}, true) }}" - - name: Keep the compose.yaml in place as the previous copy - when: stack_changed and stack_present.stat.exists + - name: Keep each file that changes as its previous copy + when: stack_existed[item] ansible.builtin.copy: - src: "{{ stack_dir }}/compose.yaml" - dest: "{{ stack_dir }}/compose.yaml.prev" + src: "{{ stack_dir }}/{{ item }}" + dest: "{{ stack_dir }}/{{ item }}.prev" remote_src: true + mode: "{{ '0600' if item == '.env.secret' else '0640' }}" + loop: "{{ stack_replaced }}" + diff: false + + - name: Note that a failure from here on is undone + ansible.builtin.set_fact: + stack_written: "{{ stack_replaced }}" + + - name: Write .env + when: "'.env' in stack_replaced" + ansible.builtin.copy: + content: "{{ stack_env_text }}" + dest: "{{ stack_dir }}/.env" mode: "0640" + - name: Write .env.secret + when: "'.env.secret' in stack_replaced" + ansible.builtin.copy: + content: "{{ stack_secret_text }}" + dest: "{{ stack_dir }}/.env.secret" + mode: "0600" + no_log: true + diff: false + - name: Write compose.yaml when: stack_changed ansible.builtin.copy: @@ -72,11 +126,7 @@ dest: "{{ stack_dir }}/compose.yaml" mode: "0640" - - name: Note that a failure from here on is undone - ansible.builtin.set_fact: - stack_written: "{{ stack_changed }}" - - # A dry run stops here: Compose would run against the file in place, + # A dry run stops here: Compose would run against the files in place, # which the dry run has not replaced. - name: Pull, migrate and bring the stack up when: not ansible_check_mode @@ -126,8 +176,9 @@ - name: Note that the environment is deployed ansible.builtin.set_fact: stack_outcome: >- - {{ ('would deploy' if stack_changed else 'unchanged') if ansible_check_mode - else ('deployed' if stack_changed or stack_up is changed or stack_down is changed else 'unchanged') }} + {{ ('would deploy' if stack_replaced or stack_route is changed else 'unchanged') if ansible_check_mode + else ('deployed' if stack_replaced or stack_route is changed or stack_up is changed or stack_down is changed + else 'unchanged') }} rescue: - name: Note why the deploy failed @@ -137,30 +188,42 @@ {{- (' (rc ' ~ ansible_failed_result.rc ~ ')') if ansible_failed_result.rc is defined else '' }}: {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} - # Back to the previous compose.yaml, or, after a first deploy, to none: - # its containers and networks go, its volumes stay. - - name: Undo the write of compose.yaml - when: stack_written | default(false) + # Where compose.yaml was there before, back to the files it ran with: each + # file the run replaced from its previous copy, and one it created removed. + # After a first deploy, to no compose.yaml: its containers and networks go, + # its volumes stay, and .env and .env.secret stay with the port the route + # names. A dry run has written nothing to undo. + - name: Undo the writes + when: stack_written | default([]) | length > 0 and not ansible_check_mode block: - - name: Restore the previous compose.yaml - when: stack_present.stat.exists + - name: Restore the files the run replaced + when: stack_existed['compose.yaml'] and stack_existed[item] ansible.builtin.copy: - src: "{{ stack_dir }}/compose.yaml.prev" - dest: "{{ stack_dir }}/compose.yaml" + src: "{{ stack_dir }}/{{ item }}.prev" + dest: "{{ stack_dir }}/{{ item }}" remote_src: true - mode: "0640" + mode: "{{ '0600' if item == '.env.secret' else '0640' }}" + loop: "{{ stack_written }}" + diff: false + + - name: Remove the files the run created + when: stack_existed['compose.yaml'] and not stack_existed[item] + ansible.builtin.file: + path: "{{ stack_dir }}/{{ item }}" + state: absent + loop: "{{ stack_written }}" - name: Bring the previous stack up - when: stack_present.stat.exists + when: stack_existed['compose.yaml'] ansible.builtin.include_tasks: up.yml - name: Note that the environment is rolled back - when: stack_present.stat.exists + when: stack_existed['compose.yaml'] ansible.builtin.set_fact: stack_outcome: "rolled back: {{ stack_outcome | regex_replace('^failed: ', '') }}" - name: Take down what the first deploy started - when: not stack_present.stat.exists + when: not stack_existed['compose.yaml'] community.docker.docker_compose_v2: project_src: "{{ stack_dir }}" project_name: "{{ stack_project }}" @@ -168,7 +231,7 @@ remove_orphans: true - name: Remove the compose.yaml of the first deploy - when: not stack_present.stat.exists + when: not stack_existed['compose.yaml'] ansible.builtin.file: path: "{{ stack_dir }}/compose.yaml" state: absent @@ -180,8 +243,5 @@ {{ stack_outcome }}; the undo failed too, at '{{ ansible_failed_task.name }}': {{ (ansible_failed_result.msg | default('no message') | string).splitlines() | first | default('') }} -# The one line `plx deploy` reads (the playbook's header says its form). -- name: Result - ansible.builtin.debug: - msg: "{{ stack_project | default('the stack') }}: {{ stack_outcome }}" - failed_when: stack_outcome not in ['deployed', 'unchanged', 'would deploy'] +- name: Say how the deploy ended + ansible.builtin.include_tasks: result.yml diff --git a/ansible/platform/roles/stack/tasks/result.yml b/ansible/platform/roles/stack/tasks/result.yml new file mode 100644 index 00000000..0d590b8f --- /dev/null +++ b/ansible/platform/roles/stack/tasks/result.yml @@ -0,0 +1,6 @@ +--- +# The one line `plx deploy` reads (the playbook's header says its form). +- name: Result + ansible.builtin.debug: + msg: "{{ stack_project | default('the stack') }}: {{ stack_outcome }}" + failed_when: stack_outcome not in ['deployed', 'unchanged', 'would deploy'] diff --git a/ansible/platform/roles/stack/templates/dotenv.j2 b/ansible/platform/roles/stack/templates/dotenv.j2 new file mode 100644 index 00000000..a830ae06 --- /dev/null +++ b/ansible/platform/roles/stack/templates/dotenv.j2 @@ -0,0 +1,8 @@ +{#- `variables` as a dotenv file Compose reads, as .env and .env.secret: a line + NAME="value" per name, in the order of the names. Inside the double quotes + a backslash, a double quote, a $ and the line breaks and tabs are escaped, + so that Compose reads every value back as written, from env_file and for + interpolation alike, and interpolates nothing inside one. -#} +{% for name, value in variables | dictsort(true) %} +{{ name }}="{{ value | string | replace('\\', '\\\\') | replace('"', '\\"') | replace('$', '\\$') | replace('\n', '\\n') | replace('\r', '\\r') | replace('\t', '\\t') }}" +{% endfor %} diff --git a/ansible/platform/roles/stack/vars/main.yml b/ansible/platform/roles/stack/vars/main.yml new file mode 100644 index 00000000..8beb1432 --- /dev/null +++ b/ansible/platform/roles/stack/vars/main.yml @@ -0,0 +1,12 @@ +--- +# The forms tasks/environment.yml holds an environment's file to, each ending +# in \Z, the end of the text, where $ would let a trailing line break pass. +# host: [user@]address[:port], an IPv6 address in brackets where a port +# follows; the groups are the user, a bracketed address, its port, an address +# without a colon, its port, and a bare IPv6 address. +stack_host_form: "^(?:([A-Za-z0-9_][A-Za-z0-9._-]*)@)?\ + (?:\\[([0-9A-Fa-f:.]+)\\](?::([0-9]+))?\ + |([A-Za-z0-9][A-Za-z0-9.-]*)(?::([0-9]+))?\ + |([0-9A-Fa-f.]*:[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*))\\Z" +# hostname, lowercased: a DNS name, labels of letters, digits and -. +stack_hostname_form: '^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\Z' diff --git a/mise.toml b/mise.toml index c9812737..bb643cc6 100644 --- a/mise.toml +++ b/mise.toml @@ -75,7 +75,7 @@ run = 'mise run check-js ${usage_name:+"$usage_name"}' [tasks.test] depends = ["install"] -description = "Run check, then the tests of the Terraform modules (against a mocked provider, and offline), the order of the tasks of plexus.ci.playbook, the stack playbook against this machine's Docker daemon (skipped without one) and the unit tests of the packages (the other roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" +description = "Run check, then the tests of the Terraform modules (against a mocked provider, and offline), the order of the tasks of plexus.ci.playbook, the stack playbook against this machine's Docker daemon and the platform playbook against containers of it (each skipped without one), and the unit tests of the packages (the other roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" usage = 'arg "[name]" help="Package to test, by its directory name under packages/ (e.g. lib, defaults to all)"' run = ''' dir= @@ -166,9 +166,9 @@ hide = true run = 'tests/terraform-modules.sh check' [tasks.test-ansible] -description = "What the playbooks must do that their syntax check does not hold: the order of the tasks of plexus.ci.playbook (the vault's CLI after the jobs' user, before the first vault read), and plexus.platform.stack deploying a stack on this machine's Docker daemon (skipped without one)" +description = "What the playbooks must do that their syntax check does not hold: the order of the tasks of plexus.ci.playbook (the vault's CLI after the jobs' user, before the first vault read), plexus.platform.stack deploying a stack on this machine's Docker daemon, and plexus.platform.playbook preparing a host that is a container of it (each skipped without one)" hide = true -run = ['./tests/link-collections.sh', './tests/runner-host-vault-cli.sh', './tests/stack-playbook.sh'] +run = ['./tests/link-collections.sh', './tests/runner-host-vault-cli.sh', './tests/stack-playbook.sh', './tests/platform-playbook.sh'] # The collections path check-ops fills and reads; link-collections fills it here too, so that the task works alone in a fresh checkout. env = { ANSIBLE_HOME = "{{config_root}}/.ansible", ANSIBLE_COLLECTIONS_PATH = "{{config_root}}/.ansible/collections" } diff --git a/newborns/deploy-job.test.ts b/newborns/deploy-job.test.ts index 868a44aa..945073b5 100644 --- a/newborns/deploy-job.test.ts +++ b/newborns/deploy-job.test.ts @@ -4,7 +4,7 @@ // step that installs plx, with the job's environment and what each step leaves the next (GITHUB_ENV and // GITHUB_PATH) read as the runner reads them. // -// The job holds the deploy key and the operations repo's token and runs nothing of the repo's code, so +// The job holds the deploy key and the vault token of its repo's secrets and runs nothing of the repo's code, so // the repo's own configuration must reach nothing: a repo's author puts into its mise.toml, beside // the pins, everything mise runs or trusts. Each case below is such a repo, and a probe that must not // fire (a file the code would write, a request the setting would send); after the steps `plx`, run as a diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index a482650a..78e73dc0 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -412,7 +412,7 @@ test('the check sets the root up again where what is on disk is no longer what t // --- the job deploy ---------------------------------------------------------------------- -/** The deploy key as the vault holds it: made up. */ +/** The deploy key as the repository secret holds it: made up. */ const DEPLOY_KEY = '-----BEGIN OPENSSH PRIVATE KEY-----\nbmV3Ym9ybi1kZXBsb3kta2V5\n-----END OPENSSH PRIVATE KEY-----'; /** The two stacks of third-party software, each on a host of its own: `broken` cannot pull its image. */ @@ -441,8 +441,8 @@ function stand(bin: string, name: string, script: string): void { } /** - * The tools of a runner that a deploy reaches, as stand-ins on a PATH of their own. `op` answers the deploy key and - * nothing else. + * The tools of a runner that a deploy reaches, as stand-ins on a PATH of their own. `op` answers its version and + * reads nothing: the deploy key is a repository secret, and the stacks of this repo have no secrets. */ function runnerTools(root: string): string { const bin = join(root, 'bin'); @@ -453,7 +453,6 @@ function runnerTools(root: string): string { 'op', `echo "op $*" >> "$LOGS/op" [ "$1" = --version ] && { echo 2.42.0; exit 0; } -[ "$1 $2" = "read op://acme-ci/deploy-ssh/private key?ssh-format=openssh" ] && { printf '%s\\n' '${DEPLOY_KEY.replaceAll('\n', "' '")}'; exit 0; } echo "op: no item $2" >&2; exit 1`, ); // setup starts the agent on a socket and feeds it the key; the stand-ins record both. @@ -464,25 +463,35 @@ echo "op: no item $2" >&2; exit 1`, } /** - * The stack playbook in a collection plexus.platform under `collections`, as the workflow installs it: on each host, - * reached without ssh, it logs the host, the stack, the environment, whether it runs in check mode and the agent it was - * handed, and ends as the playbook's task Result does: `deployed`, `would deploy` in check mode, and a failed pull for - * the stack `broken`. + * The stack playbook in a collection plexus.platform under `collections`, as the workflow installs it: on the host its + * environment's file names, reached without ssh, it logs the host, the stack, the environment named by the file, whether + * it runs in check mode and the agent it was handed, and ends as the playbook's task Result does: `deployed`, `would + * deploy` in check mode, and a failed pull for the stack `broken`. */ function standInCollection(collections: string): void { put(join(collections, 'ansible_collections', 'plexus', 'platform'), { 'galaxy.yml': 'namespace: plexus\nname: platform\nversion: 0.0.0\nreadme: README.md\nauthors: [acme]\n', - 'playbooks/stack.yml': `- name: The stack playbook, stood in for - hosts: all + 'playbooks/stack.yml': `- name: Read the environment's file, as the playbook does + hosts: localhost connection: local gather_facts: false + tasks: + - name: Add the environment's host + ansible.builtin.add_host: + name: "{{ (lookup('ansible.builtin.file', stack_environment_file) | from_yaml).host }}" + groups: stack_host + ansible_connection: local +- name: The stack playbook, stood in for + hosts: stack_host + gather_facts: false vars: - project: "{{ stack_name }}-{{ stack_environment }}" + environment_name: "{{ stack_environment_file | basename | regex_replace('[.]yaml$', '') }}" + project: "{{ stack_name }}-{{ environment_name }}" fails: "{{ stack_name == 'broken' and not ansible_check_mode }}" tasks: - name: Log the run ansible.builtin.set_fact: - logged: "{{ lookup('ansible.builtin.pipe', 'echo ' ~ ([inventory_hostname, stack_name, stack_environment, ansible_check_mode] | join(' ')) ~ ' $SSH_AUTH_SOCK >> $LOGS/ansible') }}" + logged: "{{ lookup('ansible.builtin.pipe', 'echo ' ~ ([inventory_hostname, stack_name, environment_name, ansible_check_mode] | join(' ')) ~ ' $SSH_AUTH_SOCK >> $LOGS/ansible') }}" # As the playbook's own: one debug, failed where the outcome is a failure. - name: Result ansible.builtin.debug: @@ -521,7 +530,8 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa for (const [stack, host] of Object.entries(STACKS)) put(dir, { [`stacks/${stack}/compose.yaml`]: COMPOSE.replace('%STACK%', stack), - [`inventory/host_vars/${host}.yml`]: `plexus_deploy_target: ssh://deploy@${host}\nplexus_apps:\n - name: ${stack}\n`, + [`stacks/${stack}/production.yaml`]: `host: ${host}\nhostname: ${stack}.example.com\n`, + [`stacks/${stack}/staging.yaml`]: `host: ${host}\nhostname: ${stack}.staging.example.com\n`, }); await assertBuilt(dir); // The stacks are deployable as born and written: plx doctor finds nothing. @@ -551,7 +561,8 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa standInCollection(join(temp, 'collections')); /** The values of the expressions a step's environment holds here. */ const expressions: Record = { - '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}': 'a-service-account-token', + '${{ secrets.DEPLOY_SSH_KEY }}': DEPLOY_KEY, + '${{ secrets.DEPLOY_VAULT_TOKEN }}': 'a-vault-token', '${{ github.token }}': 'a-job-token', '${{ runner.temp }}': temp, }; @@ -578,13 +589,10 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa jobEnv = { ...jobEnv, ...handedOn(files.GITHUB_ENV) }; } // The deploy key is in the agent, the job is logged in to the registry, and the setup step asked the forge for - // nothing and read nothing else. + // nothing and read nothing from the vault. assert.match(readFileSync(join(logs, 'agent'), 'utf8'), /^ssh-agent -a .*ssh-agent\.sock$/m); assert.match(readFileSync(join(logs, 'agent'), 'utf8'), /^ssh-add - 3$/m); - assert.deepEqual(readFileSync(join(logs, 'op'), 'utf8').trim().split('\n'), [ - 'op --version', - 'op read op://acme-ci/deploy-ssh/private key?ssh-format=openssh', - ]); + assert.deepEqual(readFileSync(join(logs, 'op'), 'utf8').trim().split('\n'), ['op --version']); assert.equal(existsSync(join(logs, 'curl')), false, 'the operations repo’s setup asks the forge for nothing'); assert.deepEqual(handedOn(files.GITHUB_OUTPUT), {}, 'it mints no token for another repo'); assert.match(jobEnv.SSH_AUTH_SOCK ?? '', /ssh-agent\.sock$/); @@ -592,7 +600,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa /** The verb step of the workflow, run as the forge runs it: its command, and its environment with the input `dry_run` given as `input`. */ const verb = async (input: string) => { - const step = steps.find((s) => /\bdeploy --environment production --inventory inventory$/.test(s.run ?? '')); + const step = steps.find((s) => /\bplx deploy --environment production$/.test(s.run ?? '')); assert.ok(step?.run, 'the workflow has the verb step'); const env = envOf(step, { '${{ inputs.dry_run }}': input }); return tryRun('mise', ['exec', '--', ...step.run.split(' ')], dir, { ...jobEnv, ...env }); @@ -604,10 +612,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa /** A run's line in the log: the host, the stack, production, check mode or not, and the agent setup handed on. */ const expect = (stack: keyof typeof STACKS, check: string) => `${STACKS[stack]} ${stack} production ${check} ${jobEnv.SSH_AUTH_SOCK}`; - const BLOCKS = [ - 'broken-production → ssh://deploy@broken.example.internal', - 'good-production → ssh://deploy@good.example.internal', - ]; + const BLOCKS = ['broken-production → broken.example.internal', 'good-production → good.example.internal']; // The dry run: the playbook's own, in check mode, for both stacks. const dry = await verb('true'); diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index d4ace612..c2ff3f65 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -36,6 +36,9 @@ import { startRegistry } from './registry.ts'; const RELEASED = '0.134.1'; const FIRST = '0.135.0'; const SECOND = '0.136.0'; +// The released version whose template stack renders no environment file, and the one after it, packed here. +const STACKED = '0.138.0'; +const NEXT = '0.139.0'; const WORKSPACE = join(import.meta.dirname, '..'); const CLI = join(WORKSPACE, 'packages', 'cli'); @@ -93,11 +96,16 @@ before(async () => { mkdirSync(tarballs); // The released ones come from npm, the engine and the plx that bundles the templates it was born with. for (const name of ['cli-template', 'cli']) - execFileSync('npm', ['pack', `@plexus-ms/${name}@${RELEASED}`, '--registry', NPM, '--pack-destination', tarballs], { - cwd: here, - stdio: 'ignore', - }); - for (const version of [FIRST, SECOND]) packAs(version, tarballs); + for (const released of [RELEASED, STACKED]) + execFileSync( + 'npm', + ['pack', `@plexus-ms/${name}@${released}`, '--registry', NPM, '--pack-destination', tarballs], + { + cwd: here, + stdio: 'ignore', + }, + ); + for (const version of [FIRST, SECOND, NEXT]) packAs(version, tarballs); const registry = await startRegistry(tarballs); stop = registry.stop; const npmrc = join(here, 'npmrc.update'); @@ -143,7 +151,7 @@ esac`, GIT_CONFIG_VALUE_1: 'false', }; mkdirSync(env.HOME as string, { recursive: true }); - for (const version of [RELEASED, FIRST, SECOND]) + for (const version of [RELEASED, FIRST, SECOND, STACKED, NEXT]) await sh( 'npm', [ @@ -188,7 +196,8 @@ async function repoAt( here, env, ); - await sh('git', ['init', '--bare', '--quiet', origin], here, env); + // The forge's default branch is the branch the repo is on, as a forge makes it when a first push creates one. + await sh('git', ['init', '--bare', '--quiet', '--initial-branch', branch as string, origin], here, env); await sh('git', ['checkout', '-q', '-B', branch as string], dir, env); await sh('git', ['remote', 'add', 'origin', origin], dir, env); await git(dir, 'add', '-A'); @@ -252,6 +261,36 @@ for (const kind of ['app', 'operations'] as const) { }); } +/** A stack of version 0.138.0 in `repo`, at `stacks/docs`, with its files committed and pushed; the branch the repo is on. */ +async function addStack(repo: string): Promise { + await sh('node', [plxOf(STACKED), 'new', 'stacks/docs', 'stack'], repo, env); + await git(repo, 'add', '-A'); + await git(repo, 'commit', '-q', '-m', 'a stack of the released version'); + await sh('git', ['push', '-q', 'origin', 'main'], repo, env); +} + +test(`operations: a stack of ${STACKED} gets no environment file from the update, which touches none the person wrote`, async () => { + const repo = await repoAt(STACKED, 'operations'); + await addStack(repo); + const written = 'host: deploy@own.example.com\nenv: {}\nsecrets: {}\n'; + writeFileSync(join(repo, 'stacks', 'docs', 'production.yaml'), written); + await git(repo, 'add', '-A'); + await git(repo, 'commit', '-q', '-m', 'the production file, written by a person'); + await sh('git', ['push', '-q', 'origin', 'main'], repo, env); + const taken = await take(NEXT, repo, NEXT); + assert.ok(taken.ok, taken.output); + const files = execFileSync('git', ['ls-tree', '--name-only', `plexus/${NEXT}`, 'stacks/docs/'], { + cwd: originOf(repo), + encoding: 'utf8', + }) + .trim() + .split('\n'); + // Its own file stays as written; no staging file is added, and nothing is said of one. + assert.deepEqual(files, ['stacks/docs/PLEXUS.md', 'stacks/docs/compose.yaml', 'stacks/docs/production.yaml']); + assert.equal(taken.read('stacks/docs/production.yaml'), written); + assert.doesNotMatch(taken.output, /staging\.yaml/); +}); + /** The repo's group `ci`, as 0.134.1 renders it empty; with `host` listed in it, the tenant's own edit, committed and pushed. */ async function listHost(repo: string, host: string): Promise { const hosts = join(repo, 'inventory', 'hosts.yml'); diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index b73ae5e1..4dcc6a8f 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -2,7 +2,6 @@ // variables and files, and fakes for the vault's CLI and every other tool on // the PATH (testing/job.ts). import assert from 'node:assert/strict'; -import { createVerify, generateKeyPairSync } from 'node:crypto'; import { readdirSync, readFileSync, statSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { test } from 'node:test'; @@ -53,8 +52,8 @@ test('a Connect server’s address without its token is no Connect server', () = assert.deepEqual(credentialsOf(job.calls), [['OP_SERVICE_ACCOUNT_TOKEN']]); }); -test('with neither, a deploy job fails in one line that names both, and nothing is read', () => { - const job = runJob(['deploy'], { vault: VAULT }); +test('a deploy job that joins the overlay with neither credential fails in one line that names both, and nothing is read', () => { + const job = runJob(['deploy', '--overlay', 'netbird'], { env: { ...DEPLOY_KEY, ...FORGE_RUNNER }, vault: VAULT }); assert.equal(job.status, 1, job.log); assert.deepEqual(credentialsOf(job.calls), []); assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); @@ -132,27 +131,28 @@ test('under --dry-run the vault is read and masked, and nothing is handed or wri const SSH_KEY = [ '-----BEGIN OPENSSH PRIVATE KEY-----', 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW', - 'QyNTUxOQAAACDfakefakefakefakefakefakefakefakefakefakefakeAAAA', + 'QyNTUxOQAAACDfakefakefakefakefakefakefakefakefakefakeAAAA', '-----END OPENSSH PRIVATE KEY-----', ].join('\n'); -const SSH_REF = 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh'; -const APP = generateKeyPairSync('rsa', { - modulusLength: 2048, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, -}); -/** The App's client ID: as short and numeric as a port, which the old pipeline's masking found inside a hash. */ -const CLIENT_ID = '587'; - -/** What the vault acme-ci holds for a deploy job. */ -const DEPLOY_VAULT = { - [SSH_REF]: SSH_KEY, - 'op://acme-ci/github-app/client-id': CLIENT_ID, - 'op://acme-ci/github-app/private-key': APP.privateKey.trim(), -}; +/** The deploy key, a repository secret the workflow hands the step. */ +const DEPLOY_KEY = { DEPLOY_SSH_KEY: SSH_KEY }; + +/** The vault's reads a job made. */ +const readsOf = (job: ReturnType) => job.calls.filter((c) => c.tool === 'op' && c.args[0] === 'read'); + +test('a deploy job without the deploy key fails in one line that names it, and starts no agent', () => { + const job = runJob(['deploy'], {}); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /DEPLOY_SSH_KEY/); + assert.equal(job.log.trim().split('\n').length, 1, job.log); + assert.deepEqual( + job.calls.filter((c) => c.tool === 'ssh-add' || c.tool === 'ssh-agent'), + [], + ); +}); -test('a deploy job’s SSH agent holds the deploy key, and the agent’s socket is a variable of the job', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); +test('a deploy job’s SSH agent holds the deploy key it was handed, and the agent’s socket is a variable of the job', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); const socket = join(job.temp, 'ssh-agent.sock'); assert.deepEqual(job.env, { DOCKER_CONFIG: join(job.temp, 'docker'), SSH_AUTH_SOCK: socket }); @@ -160,14 +160,22 @@ test('a deploy job’s SSH agent holds the deploy key, and the agent’s socket const add = job.calls.find((c) => c.tool === 'ssh-add'); assert.deepEqual([add?.args, add?.seen.SSH_AUTH_SOCK, add?.input], [['-'], socket, `${SSH_KEY}\n`]); for (const line of SSH_KEY.split('\n')) assert.ok(masksFirst(job.log).includes(`::add-mask::${line}`), line); - assert.ok( - !job.calls.some((c) => c.tool === 'op' && c.args[1] === KEY_REF), - 'a deploy job reads no server-actions key', +}); + +test('a deploy job reads nothing from the vault, mints no token for a second repo and hands nothing on as an output', () => { + const job = runJob(['deploy'], { env: { ...DEPLOY_KEY, ...CONNECT, ...SERVICE_ACCOUNT }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(readsOf(job), []); + assert.deepEqual( + job.calls.filter((c) => c.tool === 'curl'), + [], ); + assert.deepEqual(job.output, {}); + assert.doesNotMatch(job.log, /vault|token of the tenant/); }); test('a deploy job is logged in to the forge’s image registry with its own token, which plx deploy reads the digests with', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); + const job = runJob(['deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); assert.equal(job.env.DOCKER_CONFIG, join(job.temp, 'docker')); const config = join(job.temp, 'docker', 'config.json'); @@ -181,23 +189,16 @@ test('a deploy job is logged in to the forge’s image registry with its own tok }); test('a key pasted into a one-line field gets its lines back before the agent reads it', () => { - const vault = { ...DEPLOY_VAULT, [SSH_REF]: SSH_KEY.replaceAll('\n', ' ') }; - const job = runJob(['deploy'], { env: CONNECT, vault }); + const job = runJob(['deploy'], { env: { DEPLOY_SSH_KEY: SSH_KEY.replaceAll('\n', ' ') } }); assert.equal(job.status, 0, job.log); assert.equal(job.calls.find((c) => c.tool === 'ssh-add')?.input, `${SSH_KEY}\n`); }); test('with -v, a key pasted into a one-line field shows no line that was not masked before it', () => { - const pasted = (key: string) => key.trim().replaceAll('\n', ' '); - const vault = { - ...DEPLOY_VAULT, - [SSH_REF]: pasted(SSH_KEY), - 'op://acme-ci/github-app/private-key': pasted(APP.privateKey), - }; - const job = runJob(['-v', 'deploy'], { env: CONNECT, vault }); + const job = runJob(['-v', 'deploy'], { env: { DEPLOY_SSH_KEY: SSH_KEY.replaceAll('\n', ' ') } }); assert.equal(job.status, 0, job.log); const lines = job.log.split('\n'); - for (const keyLine of [...SSH_KEY.split('\n'), ...APP.privateKey.trim().split('\n')]) { + for (const keyLine of SSH_KEY.split('\n')) { const masked = lines.indexOf(`::add-mask::${keyLine}`); const shown = lines.findIndex((l) => !l.startsWith('::add-mask::') && l.includes(keyLine)); assert.ok(masked >= 0 && (shown < 0 || masked < shown), `${keyLine} is masked before it is shown`); @@ -208,94 +209,18 @@ test('with -v, a key pasted into a one-line field shows no line that was not mas ); }); -/** The JWT a curl call authorized with, and the request's data. */ -const requestOf = (input = '') => ({ - url: /^url = "(.*)"$/m.exec(input)?.[1], - method: /^request = "(.*)"$/m.exec(input)?.[1], - jwt: /^header = "Authorization: Bearer (.*)"$/m.exec(input)?.[1] ?? '', - data: /^data = (.*)$/m.exec(input)?.[1], -}); - -test('a deploy job is handed a token of the tenant’s App that may read the operations repo, and nothing more', () => { - const job = runJob(['deploy'], { env: SERVICE_ACCOUNT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(job.output, { 'operations-token': 'ghs_operations' }); - assert.ok(masksFirst(job.log).includes('::add-mask::ghs_operations')); - const [installation, token] = job.calls.filter((c) => c.tool === 'curl').map((c) => requestOf(c.input)); - assert.deepEqual( - [installation?.method, installation?.url], - ['GET', 'https://api.github.com/repos/acme/operations/installation'], - ); - assert.deepEqual( - [token?.method, token?.url, JSON.parse(JSON.parse(token?.data ?? '""'))], - [ - 'POST', - 'https://api.github.com/app/installations/42/access_tokens', - { repositories: ['operations'], permissions: { contents: 'read' } }, - ], - ); - for (const { jwt } of [installation, token]) { - const [header = '', payload = '', signature = ''] = jwt.split('.'); - assert.ok( - createVerify('RSA-SHA256').update(`${header}.${payload}`).verify(APP.publicKey, signature, 'base64url'), - 'signed with the App’s key', - ); - const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()); - assert.equal(claims.iss, CLIENT_ID); - assert.ok(claims.exp - claims.iat <= 600, 'no longer than GitHub allows'); - } -}); - -/** The lines of a job's log that are no mask and name `text`. */ -const linesNaming = (log: string, ...texts: string[]) => - log.split('\n').filter((l) => !l.startsWith('::add-mask::') && texts.every((t) => l.includes(t))); - -test('an App not installed on the operations repo fails the job in one line that names the App and the repo', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT, apiStatus: 404 }); - assert.equal(job.status, 1, job.log); - const [line, ...more] = linesNaming(job.log, CLIENT_ID, 'acme/operations'); - assert.deepEqual(more, [], job.log); - assert.match(line ?? '', /not installed/); - assert.doesNotMatch(job.log, /curl -K - exited/); - const { jwt } = requestOf(job.calls.find((c) => c.tool === 'curl')?.input); - assert.deepEqual(linesNaming(job.log, jwt), [], 'the JWT is in no line but its mask'); -}); - -test('a key or client ID GitHub refuses fails the job in one line that names the App and the repo, and tells it from the above', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT, apiStatus: 401 }); - assert.equal(job.status, 1, job.log); - const [line, ...more] = linesNaming(job.log, CLIENT_ID, 'acme/operations'); - assert.deepEqual(more, [], job.log); - assert.match(line ?? '', /refused/); - assert.doesNotMatch(line ?? '', /not installed/); - assert.doesNotMatch(job.log, /curl -K - exited/); - const { jwt } = requestOf(job.calls.find((c) => c.tool === 'curl')?.input); - assert.deepEqual(linesNaming(job.log, jwt), [], 'the JWT is in no line but its mask'); -}); - -test('under --dry-run a deploy job reads and masks, and calls nothing: no API, no agent', () => { - const job = runJob(['--dry-run', 'deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); +test('under --dry-run a deploy job masks the deploy key, and starts and writes nothing', () => { + const job = runJob(['--dry-run', 'deploy'], { env: DEPLOY_KEY }); assert.equal(job.status, 0, job.log); + assert.ok(SSH_KEY.split('\n').every((line) => masksFirst(job.log).includes(`::add-mask::${line}`))); assert.deepEqual( job.calls.map((c) => c.tool), - ['op', 'op', 'op', 'op'], - 'the probe for op, then the three reads', + ['op'], + 'the probe for op, and nothing else', ); assert.deepEqual([job.output, job.env], [{}, {}]); }); -test('the operations repo is the one the tenant names', () => { - const job = runJob(['deploy', '--operations-repo', 'ops'], { env: CONNECT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.match(job.calls.find((c) => c.tool === 'curl')?.input ?? '', /\/repos\/acme\/ops\/installation/); -}); - -test('the App’s client ID is read as no secret and is not masked, as the port of a relay should have been', () => { - const job = runJob(['deploy'], { env: CONNECT, vault: DEPLOY_VAULT }); - assert.equal(job.status, 0, job.log); - assert.ok(!job.log.includes(`::add-mask::${CLIENT_ID}\n`), job.log); -}); - const FORGE_RUNNER = { RUNNER_ENVIRONMENT: 'github-hosted' }; const SLOT = { RUNNER_ENVIRONMENT: 'self-hosted' }; /** The repo names the tenant's cache host, as mise's environment hands it to every step. */ @@ -338,8 +263,8 @@ test('on a slot a job joins nothing and reads no cache token: the slot is on the ['deploy', '--overlay', 'netbird'], ]) { const job = runJob(args, { - env: { ...CONNECT, ...SLOT, ...CACHE_HOST }, - vault: { ...VAULT, ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...CONNECT, ...SLOT, ...CACHE_HOST, ...DEPLOY_KEY }, + vault: { ...VAULT, ...OVERLAY_VAULT }, }); assert.equal(job.status, 0, job.log); assert.ok(!job.calls.some((c) => c.tool === 'netbird' || c.tool === 'sudo'), args[0]); @@ -364,8 +289,8 @@ test('on a forge runner, a repo job joins nothing where the repo names no cache test('on a forge runner, a deploy job on netbird joins the overlay and waits for its network map', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, }); assert.equal(job.status, 0, job.log); assert.equal(job.output.joined, 'true'); @@ -387,8 +312,8 @@ test('a repo job whose join fails goes on without the remote cache, and says so test('a deploy job whose join fails fails', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, netbirdFails: true, }); assert.equal(job.status, 1, job.log); @@ -397,8 +322,8 @@ test('a deploy job whose join fails fails', () => { test('a deploy job waits for the network map, never for the cache host its repo names: the cache host is the repo job’s', () => { const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, - vault: { ...DEPLOY_VAULT, ...OVERLAY_VAULT }, + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST, ...DEPLOY_KEY }, + vault: OVERLAY_VAULT, }); assert.equal(job.status, 0, job.log); assert.equal(job.output.joined, 'true'); @@ -509,8 +434,7 @@ test('a trusted server named without its token is asked nothing and handed no lo test('a deploy job, and a repo job under --dry-run, ask no cache server', () => { const deploy = runJob(['deploy'], { - env: { ...CONNECT, ...SLOT, ...SLOT_CACHES }, - vault: DEPLOY_VAULT, + env: { ...CONNECT, ...SLOT, ...SLOT_CACHES, ...DEPLOY_KEY }, cacheStatus: 200, }); assert.equal(deploy.status, 0, deploy.log); diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index ccc6801b..2025ba9e 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -10,12 +10,13 @@ // repo; `npm` or `github`, a package repo's packages, to npm or // to the forge's package registry; `nothing`, as an operations // repo's. -// deploy plx deploy, of an app repo or of the operations repo. The -// checkout the step runs in (the cwd) is the operations repo -// where its root marker lists the operations template, by the -// rule plx has for it (isOperationsRepo of @plexus-ms/lib); no -// marker, or one that cannot be read, is an app repo. In the -// operations repo the step therefore follows the checkout. +// deploy plx deploy, of any repo that has stacks: the same for every +// repo, since a deploy reads only its own checkout. The step +// holds the deploy key, a repository secret, in an SSH agent, and +// puts the vault's CLI where the stack playbook finds it; the +// playbook resolves the stacks' secrets with the read-only token +// of the vault of the tenant, another repository secret, which +// the workflow hands the step of `plx deploy` alone. // changeset the job that commits the changeset a bump of the update bot // owes, and pushes it to the bot's branch. // update the job that takes a version (plx update): pushes a branch @@ -42,17 +43,21 @@ // and the runner no `op`, as the forge's own runners have none, install // the pinned version into RUNNER_TEMP/op, verified by its signature // (core/op.ts says how, and where the version is stated); a runner that -// has `op` is left as it is. A job with nothing to read installs nothing. +// has `op` is left as it is. A job with nothing to read installs nothing, +// but a deploy job, whose playbook reads the stacks' secrets with `op` +// under a token of its own, installs it all the same, and its directory +// is put on the PATH of the later steps (step 10). // Where the job has no credential, as the job of a pull request from a // fork has none, a repo job reads nothing from the vault, says so in one // line, a warning annotation of the run, and goes on at step 7 with the // logins, which are its own token's: no server-actions key and no overlay // join, so that the verbs run without the remote cache, except where the // runner itself names cache servers and tokens, as a slot of a runner -// host does. A deploy job, a repo job publishing images in the workflow -// on_push, whose images carry the repo's one key, and a changeset or -// update job without the App on the forge fail there, in one line that -// names the credentials missing; the last names both ways to the App. +// host does. A repo job publishing images in the workflow on_push, whose +// images carry the repo's one key, a deploy job that joins the overlay, +// and a changeset or update job without the App on the forge fail there, +// in one line that names the credentials missing; the last names both +// ways to the App. // 4. Read from the vault `-ci` what the job needs, every read through // the one function of core/vault.ts, which reaches the vault through the // runner's Connect server where the runner carries one and with the @@ -65,15 +70,16 @@ // turbo-cache/shared-token and turbo-cache/trusted-token. // Publishing no image, only the latter three, and where // there is no overlay to join nothing at all. -// deploy deploy-ssh/private key (as OpenSSH); except in the -// operations repo itself, github-app/client-id, which is -// no secret and is not masked, and github-app/private-key; -// on a forge runner with `--overlay netbird`, also -// netbird/setup-key +// deploy on a forge runner with `--overlay netbird`, netbird/setup-key +// and nothing else: the deploy key is no item of the vault +// but the repository secret DEPLOY_SSH_KEY, which a job +// without it fails for in one line, as nothing can be +// deployed // changeset without the App on the forge: github-app/client-id and // update github-app/private-key -// A key pasted into a one-line field gets its lines back, and each of -// them is masked as it is restored. +// A key pasted into a one-line field, of the vault or of the repository +// secret, gets its lines back, and each of them is masked as it is +// restored. // 5. update: where the runner has no `gh`, which plx update asks the forge // with, install the pinned version with mise (core/gh.ts), before any // token is minted; a runner without mise either fails in one line. @@ -82,9 +88,7 @@ // never leaves this process: the calls to the forge's API are handed the // JWT on stdin and run without the App's key and the vault's // credentials. -// deploy the operations repo (`--operations-repo`, default -// `operations`), contents read; none in the operations -// repo itself, whose checkout holds the inventory +// deploy none: a deploy reads only its own repo // changeset the job's own repo, contents write // update the job's own repo, contents, pull requests and workflows // write @@ -105,7 +109,7 @@ // owner's scope, in lower case, to that registry, so that // `changeset publish` asks it which versions exist // deploy: start an SSH agent on a socket under RUNNER_TEMP and add the -// deploy key. +// deploy key, DEPLOY_SSH_KEY. // 8. On a forge runner, where step 4 read a setup key: join the overlay as // an ephemeral peer named `ci--`, and wait until the cache // host resolves (repo) or the network map names a peer (deploy, whose @@ -126,8 +130,6 @@ // 10. Hand later steps what they need. As outputs of the step: // repo server-actions-key, publishing images, for the build and // publish steps alone -// deploy operations-token, for the checkout of the operations repo, -// except in the operations repo itself // changeset app-token, for the checkout that pushes and, in update, // update for gh (GH_TOKEN) // repo and joined=true, where the job joined the overlay @@ -137,14 +139,15 @@ // PLX_TURBO_TRUSTED_TOKEN where step 4 read them; PLX_TURBO_TRUSTED=local // (step 9); SSH_AUTH_SOCK. No secret of the vault is a variable of the job // but the two cache tokens. First on the job's PATH (GITHUB_PATH): the -// directory of the gh installed in step 5. +// directory of the gh installed in step 5, and of the op installed in +// step 3 for a deploy job. // // Under --dry-run it reads and masks, calls no API, and writes, installs and // starts nothing. Exit code 1 where the refusal, a missing credential, // a read, the token, the install of op or gh, or a deploy job's join fails; // 2 for a mistake in the arguments, among them an option of another kind of // job, before anything is read: `--private-packages` belongs to repo, -// changeset and update, `--publishes` to repo, `--operations-repo` to deploy. +// changeset and update, `--publishes` to repo. // // plx-ci setup repo --overlay netbird --private-packages // plx-ci setup repo --publishes github @@ -185,15 +188,10 @@ export function register(program: Command): void { .choices(PUBLISHES) .default('images'), ) - .option( - '--operations-repo ', - 'deploy: the tenant’s operations repo, in the owner’s organisation, which an app repo’s deploy reads', - 'operations', - ) .action( async ( job: Job, - opts: { overlay: Overlay; privatePackages?: boolean; publishes: Publishes; operationsRepo: string }, + opts: { overlay: Overlay; privatePackages?: boolean; publishes: Publishes }, command: Command, ) => { for (const [option, key, kinds] of OWN) { @@ -211,5 +209,4 @@ export function register(program: Command): void { const OWN: [string, string, Job[]][] = [ ['--private-packages', 'privatePackages', ['repo', 'changeset', 'update']], ['--publishes', 'publishes', ['repo']], - ['--operations-repo', 'operationsRepo', ['deploy']], ]; diff --git a/packages/cli-ci/src/commands/setupAppToken.test.ts b/packages/cli-ci/src/commands/setupAppToken.test.ts index 81e463fd..d553b852 100644 --- a/packages/cli-ci/src/commands/setupAppToken.test.ts +++ b/packages/cli-ci/src/commands/setupAppToken.test.ts @@ -197,16 +197,10 @@ for (const job of ['changeset', 'update'] as const) }); test('the calls to the forge’s API see neither the App’s key nor the vault’s credentials', () => { - const deployVault = { - ...VAULT, - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': - '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----', - }; for (const [args, env, vault] of [ [['changeset'], { ...FORGE_APP, ...CONNECT, ...SERVICE_ACCOUNT }, {}], [['update'], { ...CONNECT, ...SERVICE_ACCOUNT }, VAULT], [['update'], { GH_PRIVATE_KEY: APP.privateKey, ...SERVICE_ACCOUNT }, VAULT], - [['deploy'], { ...CONNECT, ...SERVICE_ACCOUNT }, deployVault], ] as const) { const job = runJob([...args], { env, vault }); assert.equal(job.status, 0, job.log); @@ -228,21 +222,14 @@ test('the calls to the forge’s API give up after 10 s without a connection and } }); -for (const job of ['update', 'deploy'] as const) - test(`${job}: a forge that never answers fails the job in one line that names the App and the repo`, () => { - const vault = { - ...VAULT, - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': - '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----', - }; - const run = runJob([job], { env: job === 'update' ? FORGE_APP : CONNECT, vault, apiHangs: true }); - assert.equal(run.status, 1, run.log); - const repo = job === 'update' ? 'acme/web' : 'acme/operations'; - const [line, ...more] = linesNaming(run.log, CLIENT_ID, repo); - assert.deepEqual(more, [], run.log); - assert.match(line ?? '', /did not answer/); - assert.equal(shown(run.log).filter((l) => !/^the vault /.test(l)).length, 1, run.log); - }); +test('update: a forge that never answers fails the job in one line that names the App and the repo', () => { + const run = runJob(['update'], { env: FORGE_APP, vault: VAULT, apiHangs: true }); + assert.equal(run.status, 1, run.log); + const [line, ...more] = linesNaming(run.log, CLIENT_ID, 'acme/web'); + assert.deepEqual(more, [], run.log); + assert.match(line ?? '', /did not answer/); + assert.equal(shown(run.log).filter((l) => !/^the vault /.test(l)).length, 1, run.log); +}); test('a forge that is down fails the job in one line that names the App and the repo, with curl itself', () => { const job = runJob(['changeset'], { env: { ...FORGE_APP, GITHUB_API_URL: 'http://127.0.0.1:1' }, realCurl: true }); diff --git a/packages/cli-ci/src/commands/setupOp.test.ts b/packages/cli-ci/src/commands/setupOp.test.ts index 40830e06..c2ca6eef 100644 --- a/packages/cli-ci/src/commands/setupOp.test.ts +++ b/packages/cli-ci/src/commands/setupOp.test.ts @@ -12,6 +12,8 @@ import { type Call, runJob } from '../testing/job.ts'; const KEY_REF = 'op://acme-ci/repo_web/server-actions-key'; const VAULT = { [KEY_REF]: 'a-key' }; const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; +/** The deploy key, a repository secret the workflow hands the deploy job's step. */ +const DEPLOY_KEY = { DEPLOY_SSH_KEY: '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----' }; const ARCH = ({ x64: 'amd64', arm64: 'arm64' } as Record)[process.arch]; const ZIP = `https://cache.agilebits.com/dist/1P/op2/pkg/v${OP_VERSION}/op_linux_${ARCH}_v${OP_VERSION}.zip`; const KEY = 'https://downloads.1password.com/linux/keys/1password.asc'; @@ -110,14 +112,22 @@ test('a runner that has op is left as it is: nothing is downloaded, and the vaul assert.ok(!(read?.path ?? '').startsWith(job.temp)); }); -test('a deploy job installs op the same way', () => { - const job = runJob(['deploy'], { env: SERVICE_ACCOUNT, vault: {}, noOp: true }); - assert.equal(job.status, 1, 'the vault holds no deploy key, which is the fake’s to refuse'); +test('a deploy job installs op the same way, with no credential for the vault, and puts it on the PATH for the playbook that reads the secrets', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY, noOp: true }); + assert.equal(job.status, 0, job.log); assert.deepEqual( downloads(job.calls).map((c) => c.args.at(-1)), [ZIP, KEY], ); - assert.ok(reads(job.calls).every((c) => c.path === join(job.temp, 'op', 'bin', 'op'))); + assert.deepEqual(reads(job.calls), [], 'nothing is read from the vault'); + assert.deepEqual(job.path, [join(job.temp, 'op', 'bin')]); +}); + +test('a deploy job on a runner that has op downloads nothing and changes no PATH', () => { + const job = runJob(['deploy'], { env: DEPLOY_KEY }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(downloads(job.calls), []); + assert.deepEqual(job.path, []); }); test('a job without a token installs nothing, whether or not the runner has op', () => { diff --git a/packages/cli-ci/src/commands/setupOperations.test.ts b/packages/cli-ci/src/commands/setupOperations.test.ts deleted file mode 100644 index c71415b5..00000000 --- a/packages/cli-ci/src/commands/setupOperations.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// plx-ci setup deploy in the operations repo itself, which deploys the third-party apps under its apps/: prepared as -// an app repo's deploy job is, the deploy key in an SSH agent and the overlay joined on a forge runner, but with no -// token of the tenant's App, since the inventory the deploy reads is in the job's own checkout. A checkout is the -// operations repo where its root marker lists the operations template, as plx tells it, whatever the repo is called. -import assert from 'node:assert/strict'; -import { generateKeyPairSync } from 'node:crypto'; -import { join } from 'node:path'; -import { test } from 'node:test'; -import { runJob } from '../testing/job.ts'; - -const CONNECT = { OP_CONNECT_HOST: 'http://localhost:8080', OP_CONNECT_TOKEN: 'connect-token' }; -const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; -/** An operations repo the tenant called infra, which the option --operations-repo does not name. */ -const OPERATIONS = { GITHUB_REPOSITORY: 'acme/infra' }; -const MARKER = '---\ntemplates: [repo-operations]\n---\n'; -const SSH_KEY = [ - '-----BEGIN OPENSSH PRIVATE KEY-----', - 'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW', - '-----END OPENSSH PRIVATE KEY-----', -].join('\n'); -const VAULT = { - 'op://acme-ci/deploy-ssh/private key?ssh-format=openssh': SSH_KEY, - 'op://acme-ci/netbird/setup-key': 'nb-setup-key-0123456789', - 'op://acme-ci/github-app/client-id': '587', - 'op://acme-ci/github-app/private-key': generateKeyPairSync('rsa', { - modulusLength: 2048, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, - }).privateKey, -}; -const reads = (job: ReturnType) => - job.calls.filter((c) => c.tool === 'op' && c.args[0] === 'read').map((c) => c.args[1]); - -test('a deploy job of the operations repo holds the deploy key in an agent, and reads and mints nothing of the App', () => { - const job = runJob(['deploy'], { env: { ...CONNECT, ...OPERATIONS }, vault: VAULT, marker: MARKER }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(reads(job), ['op://acme-ci/deploy-ssh/private key?ssh-format=openssh']); - assert.deepEqual( - job.calls.filter((c) => c.tool === 'curl'), - [], - ); - assert.deepEqual(job.output, {}); - const socket = join(job.temp, 'ssh-agent.sock'); - assert.deepEqual(job.env, { DOCKER_CONFIG: join(job.temp, 'docker'), SSH_AUTH_SOCK: socket }); - assert.equal(job.calls.find((c) => c.tool === 'ssh-add')?.input, `${SSH_KEY}\n`); -}); - -/** The calls to the forge's API a job made, by method and URL. */ -const asked = (job: ReturnType) => - job.calls.filter((c) => c.tool === 'curl').map((c) => /^url = "(.*)"$/m.exec(c.input ?? '')?.[1]); - -for (const [what, marker] of [ - ['an app repo’s marker', '---\ntemplates: [repo-turbo]\n---\n'], - ['no marker', undefined], - ['a marker that cannot be read', '---\ntemplates: repo-operations\n---\n'], -] as const) - test(`a deploy job of a repo called operations whose checkout has ${what} mints the token for the operations repo, as an app repo’s does`, () => { - const job = runJob(['deploy'], { - env: { ...CONNECT, GITHUB_REPOSITORY: 'acme/operations' }, - vault: VAULT, - ...(marker === undefined ? {} : { marker }), - }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(asked(job), [ - 'https://api.github.com/repos/acme/operations/installation', - 'https://api.github.com/app/installations/42/access_tokens', - ]); - assert.deepEqual(job.output, { 'operations-token': 'ghs_operations' }); - }); - -test('on a forge runner, a deploy job of the operations repo on netbird joins the overlay and waits for its network map', () => { - const job = runJob(['deploy', '--overlay', 'netbird'], { - env: { ...SERVICE_ACCOUNT, ...OPERATIONS, RUNNER_ENVIRONMENT: 'github-hosted' }, - vault: VAULT, - marker: MARKER, - }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(job.output, { joined: 'true' }); - const up = job.calls.find((c) => c.tool === 'netbird' && c.args[0] === 'up'); - assert.deepEqual(up?.args, ['up', '--hostname', 'ci-41-deploy']); - assert.ok(!job.calls.some((c) => c.tool === 'getent'), 'it waits for the map, not for a cache host'); -}); - -test('under --dry-run a deploy job of the operations repo reads and masks the deploy key, and says nothing of a token', () => { - const job = runJob(['--dry-run', 'deploy'], { env: { ...CONNECT, ...OPERATIONS }, vault: VAULT, marker: MARKER }); - assert.equal(job.status, 0, job.log); - assert.deepEqual(reads(job), ['op://acme-ci/deploy-ssh/private key?ssh-format=openssh']); - assert.doesNotMatch(job.log, /token of the tenant’s App/); - assert.deepEqual([job.output, job.env], [{}, {}]); -}); diff --git a/packages/cli-ci/src/commands/setupUsage.test.ts b/packages/cli-ci/src/commands/setupUsage.test.ts index c0df79d2..07fd01df 100644 --- a/packages/cli-ci/src/commands/setupUsage.test.ts +++ b/packages/cli-ci/src/commands/setupUsage.test.ts @@ -10,9 +10,6 @@ for (const [args, belongs] of [ [['deploy', '--publishes', 'npm'], /--publishes is an option of the job repo, not of deploy/], [['changeset', '--publishes', 'images'], /--publishes is an option of the job repo, not of changeset/], [['update', '--publishes', 'github'], /--publishes is an option of the job repo, not of update/], - [['repo', '--operations-repo', 'ops'], /--operations-repo is an option of the job deploy, not of repo/], - [['changeset', '--operations-repo', 'ops'], /--operations-repo is an option of the job deploy, not of changeset/], - [['update', '--operations-repo', 'operations'], /--operations-repo is an option of the job deploy, not of update/], [ ['deploy', '--private-packages'], /--private-packages is an option of the jobs repo, changeset and update, not of deploy/, @@ -27,11 +24,15 @@ for (const [args, belongs] of [ assert.deepEqual([job.output, job.env], [{}, {}]); }); +test('--operations-repo is an option of no job: a deploy reads only its own repo', () => { + const job = runJob(['deploy', '--operations-repo', 'operations'], { env: CONNECT }); + assert.notEqual(job.status, 0, job.log); + assert.match(job.log, /unknown option '--operations-repo'/); + assert.deepEqual(job.calls, []); +}); + test('an option of its own kind, named with its default, is no mistake', () => { - for (const args of [ - ['repo', '--publishes', 'images'], - ['deploy', '--operations-repo', 'operations'], - ]) { + for (const args of [['repo', '--publishes', 'images']]) { const job = runJob(args, { env: CONNECT, vault: { 'op://acme-ci/repo_web/server-actions-key': 'k' }, diff --git a/packages/cli-ci/src/commands/setupWithoutToken.test.ts b/packages/cli-ci/src/commands/setupWithoutToken.test.ts index 500a8b66..b9f239e5 100644 --- a/packages/cli-ci/src/commands/setupWithoutToken.test.ts +++ b/packages/cli-ci/src/commands/setupWithoutToken.test.ts @@ -56,12 +56,14 @@ test('a repo job of the workflow on_commit or on_pr reads nothing where it has n assert.deepEqual(job.output, {}); }); -test('a deploy job with no token fails, since it cannot deploy', () => { +test('a deploy job with no deploy key fails, since it cannot deploy, and needs no token for the vault', () => { const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT }); assert.equal(job.status, 1, job.log); - assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); - assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); + assert.match(job.log, /DEPLOY_SSH_KEY/); assert.ok(!SAYS.test(job.log), 'it does not go on as a job that deploys nothing'); + const keyed = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH, DEPLOY_SSH_KEY: 'k' }, vault: VAULT }); + assert.equal(keyed.status, 0, keyed.log); + assert.ok(!SAYS.test(keyed.log), 'a deploy job reads no vault, so has no token to miss'); }); test('a job with a token reads as before and says nothing of the kind', () => { diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index f437d1c8..06cbf6ec 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -7,7 +7,6 @@ import { detailOf, ENVIRONMENT_BRANCHES, environmentOf, - isOperationsRepo, orAbsent, type Plan, run, @@ -55,8 +54,6 @@ export interface SetupOptions { privatePackages?: boolean; /** What the repo's publish puts into a registry; a repo job's, `images` unless named. */ publishes?: Publishes; - /** The tenant's operations repo, in the owner's organisation, whose inventory an app repo's deploy reads. */ - operationsRepo?: string; } /** The forge's registries, which the job's own token logs in to. */ @@ -99,11 +96,11 @@ function refuseOnPushWithoutEnvironment(env: NodeJS.ProcessEnv): void { * slot hands its host's cache servers and tokens whatever the job has, and the * line says so there. A job with a credential reads with the runner's * `op`, or with one installed for the job where the runner has none - * (core/op.ts). A deploy job cannot deploy without the vault, and - * a run of on_push publishes images of the repo's one key (§ 3.8): both fail - * here, in a line that names the credentials missing. So does a job that - * pushes to its repo where the forge does not hand it the App's credentials, - * which it then reads from the vault (`appOf`). + * (core/op.ts), which the caller finds first for a deploy job. A run of + * on_push publishes images of the repo's one key (§ 3.8): it fails here, in a + * line that names the credentials missing, as does a job that joins the + * overlay or pushes to its repo where the forge does not hand it the App's + * credentials, which it then reads from the vault (`appOf`). */ async function vaultFor( ctx: Context, @@ -111,8 +108,9 @@ async function vaultFor( env: NodeJS.ProcessEnv, temp: string, images: boolean, + op?: string, ): Promise { - if (vaultAccess(env)) return vaultOf(ctx, env, await opOf(ctx, env, temp)); + if (vaultAccess(env)) return vaultOf(ctx, env, op ?? (await opOf(ctx, env, temp))); if (PUSHES[options.job]) { try { vaultOf(ctx, env); @@ -152,6 +150,11 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro const vaultName = `${owner}-ci`; const temp = need('RUNNER_TEMP', env); const permissions = PUSHES[options.job]; + const outputs: Record = {}; + const variables: Record = {}; + /** Directories later steps put first on their PATH. */ + const paths: string[] = []; + const plan: Plan = []; const forgeApp = permissions && env.GH_CLIENT_ID && env.GH_PRIVATE_KEY ? appOfForge(ctx, env) : undefined; // A slot of a runner host shares the host's network, which is on the overlay, and a repo slot carries its host's // cache tokens: only a forge runner joins, and only for what it reaches there. @@ -161,13 +164,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro options.overlay === 'netbird' && (options.job === 'deploy' || (options.job === 'repo' && cacheHost !== undefined)); // A repo job of a repo that pushes no image reads the vault only to join the overlay. - const reads = options.job === 'repo' ? images || overlay : !forgeApp; - const vault = reads ? await vaultFor(ctx, options, env, temp, images) : undefined; - const outputs: Record = {}; - const variables: Record = {}; - /** Directories later steps put first on their PATH. */ - const paths: string[] = []; - const plan: Plan = []; + // A deploy job's `op` is the playbook's, which reads the stacks' secrets with a token of its own; the job reads the + // vault only to join the overlay. + const op = options.job === 'deploy' ? await opOf(ctx, env, temp) : undefined; + if (op && op !== 'op') paths.push(dirname(op)); + const reads = options.job === 'repo' ? images || overlay : options.job === 'deploy' ? overlay : !forgeApp; + const vault = reads ? await vaultFor(ctx, options, env, temp, images, op) : undefined; const setupKey = overlay && vault ? await vault.read(`op://${vaultName}/netbird/setup-key`) : undefined; if (options.job === 'repo') { @@ -190,17 +192,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro ctx.say(`[dry-run] a token of the tenant’s App for ${repository}: ${Object.keys(permissions).join(', ')} write`); if (forgeApp) ctx.say('the tenant’s GitHub App, from the variable GH_CLIENT_ID and the secret GH_PRIVATE_KEY'); } else { - if (!vault) throw new Error('a deploy job reads the vault'); - const sshKey = keyLines(ctx, await vault.read(`op://${vaultName}/deploy-ssh/private key?ssh-format=openssh`)); - // The operations repo's own deploy job has the inventory in its checkout, told as plx tells an operations repo, by - // the root marker of the checkout the step runs in; an app repo's reads it with a token of the App. - if (!(await isOperationsRepo(ctx))) { - const operations = options.operationsRepo || 'operations'; - const app = await appOf(ctx, vault, vaultName); - const token = await mint(ctx, env, { owner, repo: operations, permissions: { contents: 'read' }, ...app }); - if (token) outputs['operations-token'] = token; - else ctx.say(`[dry-run] a token of the tenant’s App that may read ${owner}/${operations}`); - } + // The deploy key is a repository secret of the repo that deploys (§ 3 PLX-Secrets), handed to this step alone. + if (!env.DEPLOY_SSH_KEY) + throw new Error( + 'the deploy job has no deploy key: the step was handed no DEPLOY_SSH_KEY, the repository secret that holds it', + ); + const sshKey = keyLines(ctx, env.DEPLOY_SSH_KEY); const socket = join(temp, 'ssh-agent.sock'); plan.push( run('ssh-agent', ['-a', socket]), @@ -389,11 +386,12 @@ function login(path: string, content: string): Plan { } /** - * A PEM key with its line breaks: a key pasted into a one-line field of the - * vault arrives with spaces in their place, which neither ssh-add nor a signer - * takes. Ends with a newline, which ssh-add needs. Masked line by line as it - * is returned, since the vault masked the key as one line: whatever prints the - * key later, at any verbosity, prints it masked. + * A PEM key with its line breaks: a key pasted into a one-line field, of the + * vault or of a repository secret, arrives with spaces in their place, which + * neither ssh-add nor a signer takes. Ends with a newline, which ssh-add + * needs. Masked line by line as it is returned, since the forge masked the key + * as one line: whatever prints the key later, at any verbosity, prints it + * masked. */ function keyLines(ctx: Context, key: string): string { const k = key.trim(); diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts index 6c241660..35be7edf 100644 --- a/packages/cli-ci/src/core/vault.ts +++ b/packages/cli-ci/src/core/vault.ts @@ -6,7 +6,9 @@ // `plx-ci setup` and no other). Where both are present the Connect server // alone: `op` is started without the service account's token, so that no read // spends the account's budget or depends on which of the two `op` prefers. -// Nothing else in plx-ci or plx reads the vault in a job. +// Nothing else in plx-ci or plx reads the vault `-ci` in a job; the +// stacks' secrets are read from the vault `` by the stack playbook that +// `plx deploy` runs, with the deploy job's own read-only token. // // A value read as a secret is masked in the job's log as soon as it is read, // so that nothing the caller prints afterwards can show it. A value read as diff --git a/packages/cli-template/src/directories.test.ts b/packages/cli-template/src/directories.test.ts index 8792a404..81d8614b 100644 --- a/packages/cli-template/src/directories.test.ts +++ b/packages/cli-template/src/directories.test.ts @@ -107,7 +107,7 @@ test('planMerge rejects a target that is not a directory', async () => { }); /** A side from literal files, every one under one policy. */ -function literal(files: Record, policy: 'merge' | 'born-once' = 'merge') { +function literal(files: Record, policy: 'merge' | 'born-once' | 'birth-only' = 'merge') { return { tree: new Map(Object.entries(files).map(([path, text]) => [path, { bytes: Buffer.from(text), mode: 0o100644 }])), policies: new Map(Object.keys(files).map((path) => [path, { policy }])), diff --git a/packages/cli-template/src/directory.ts b/packages/cli-template/src/directory.ts index f38889d4..a3a84282 100644 --- a/packages/cli-template/src/directory.ts +++ b/packages/cli-template/src/directory.ts @@ -294,7 +294,7 @@ export const policiesOf = (dir: string): string => `${resolve(dir)}.plx-template /** The version of the policies file `render` writes and `readRender` reads. */ export const POLICIES_VERSION = 1; -const POLICIES: readonly string[] = ['merge', 'born-once'] satisfies Policy[]; +const POLICIES: readonly string[] = ['merge', 'born-once', 'birth-only'] satisfies Policy[]; /** Whether `value` is a JSON object: not null, not a list. */ export function isObject(value: unknown): value is Record { @@ -337,7 +337,7 @@ async function readPolicies(dir: string, tree: Tree): Promise { if (!isObject(parsed.files)) return fail('has no files: a map of path to { template, policy }'); const files = Object.entries(parsed.files); const bad = files.filter(([, v]) => !isObject(v) || !POLICIES.includes(v.policy as string)).map(([path]) => path); - if (bad.length > 0) return fail(`gives no policy, merge or born-once, to ${bad.join(', ')}`); + if (bad.length > 0) return fail(`gives no policy, merge, born-once or birth-only, to ${bad.join(', ')}`); const lacking = [...tree.keys()].filter((path) => !(path in (parsed.files as object))); if (lacking.length > 0) return fail(`lacks ${lacking.join(', ')}, which its render holds`); const extra = files.map(([path]) => path).filter((path) => !tree.has(path)); diff --git a/packages/cli-template/src/manifest.ts b/packages/cli-template/src/manifest.ts index 70c0c025..025461e6 100644 --- a/packages/cli-template/src/manifest.ts +++ b/packages/cli-template/src/manifest.ts @@ -31,7 +31,7 @@ // colour: # required: an error when nothing supplies it // size: {default: small} # optional: the default when nothing supplies it // policies: # by source path below files/, as written there -// "notes.md.jinja": born-once # merge (every path not listed) or born-once +// "notes.md.jinja": born-once # merge (every path not listed), born-once or birth-only // birth: # commands for whoever creates a directory from the // - [git, init] # template, each an argument vector; never run here // @@ -79,7 +79,7 @@ export const VARIABLES = 'variables.json'; const KEYS = ['name', 'questions', 'reads', 'policies', 'birth']; const FIELDS = ['type', 'default', 'help', 'when', 'validator', 'choices']; const TYPES: readonly string[] = ['str', 'int', 'float', 'bool', 'yaml', 'json'] satisfies QuestionType[]; -const POLICIES: readonly string[] = ['merge', 'born-once'] satisfies Policy[]; +const POLICIES: readonly string[] = ['merge', 'born-once', 'birth-only'] satisfies Policy[]; /** What a template is called: lowercase letters, digits and hyphens, from a letter. */ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]*$/; const VARIABLE = /^[A-Za-z][A-Za-z0-9_]*$/; diff --git a/packages/cli-template/src/merge.test.ts b/packages/cli-template/src/merge.test.ts index e593ca48..979e7a1f 100644 --- a/packages/cli-template/src/merge.test.ts +++ b/packages/cli-template/src/merge.test.ts @@ -15,6 +15,8 @@ interface Case { readonly current?: Listing; /** The paths whose policy is born-once: in both renders, or in each. */ readonly bornOnce?: readonly string[] | { readonly old: readonly string[]; readonly new: readonly string[] }; + /** The paths whose policy is birth-only, in the new render. */ + readonly birthOnly?: readonly string[]; /** What the fake merge of one file reports. */ readonly conflicted?: boolean; } @@ -38,8 +40,14 @@ async function run(c: Case) { }; const bornOnce = c.bornOnce ?? []; const { old: bornOld, new: bornNew } = 'old' in bornOnce ? bornOnce : { old: bornOnce, new: bornOnce }; - const policies = (l: Listing, born: readonly string[]): Policies => - new Map(Object.keys(l).map((path) => [path, { policy: born.includes(path) ? 'born-once' : 'merge' }])); + const birthOnly = c.birthOnly ?? []; + const policies = (l: Listing, born: readonly string[], only: readonly string[] = []): Policies => + new Map( + Object.keys(l).map((path) => [ + path, + { policy: only.includes(path) ? 'birth-only' : born.includes(path) ? 'born-once' : 'merge' }, + ]), + ); const old = c.old ?? {}; const next = c.new ?? {}; const result = await merge( @@ -47,7 +55,7 @@ async function run(c: Case) { old: tree(old), new: tree(next), current: tree(c.current ?? {}), - files: { old: policies(old, bornOld), new: policies(next, bornNew) }, + files: { old: policies(old, bornOld, birthOnly), new: policies(next, bornNew, birthOnly) }, }, mergeFile, ); @@ -283,6 +291,29 @@ test('merge leaves absent a path the user deleted, even where the template chang }); }); +test('merge writes a birth-only path where the old render holds nothing, a birth, and never where the old render holds anything: an update adds none, and touches none the current tree has', async () => { + const born = await run({ new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, birthOnly: ['env.txt'] }); + assert.deepEqual(born, { + tree: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + report: ['compose.txt: added', 'env.txt: added'], + calls: [], + }); + const updated = await run({ + old: { 'compose.txt': 'c\n' }, + new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + current: { 'compose.txt': 'mine\n' }, + birthOnly: ['env.txt'], + }); + assert.deepEqual(updated, { tree: { 'compose.txt': 'mine\n' }, report: [], calls: [] }); + const had = await run({ + old: { 'compose.txt': 'c\n' }, + new: { 'compose.txt': 'c\n', 'env.txt': 'e\n' }, + current: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, + birthOnly: ['env.txt'], + }); + assert.deepEqual(had, { tree: { 'compose.txt': 'c\n', 'env.txt': 'mine\n' }, report: ['env.txt: kept'], calls: [] }); +}); + // Ported from tests/test_updatediff.py, test_skip_update_deleted, where our // rule differs: copier writes a skipped file the user deleted again on an // update; merge leaves it absent, like any file the user deleted, since the old diff --git a/packages/cli-template/src/merge.ts b/packages/cli-template/src/merge.ts index b6613c09..542f85d9 100644 --- a/packages/cli-template/src/merge.ts +++ b/packages/cli-template/src/merge.ts @@ -10,7 +10,8 @@ // // 1. the new render holds it, and neither the old render nor current does: // the path is new to the template and written, `added`, whatever its -// policy, since this is a born-once file's birth; but `kept` where a +// policy, since this is a born-once file's birth; but not at all where its +// policy is birth-only and the old render holds anything, an update; and `kept` where a // directory it lies in is a symlink in the current tree, and // `conflicted` where one is a file // 2. the old and the new render hold it alike: left alone @@ -101,7 +102,10 @@ export async function merge(input: MergeInput, mergeFile: MergeFile): Promise 0 && !old.has(path) && !tree.has(path)) continue; const outcome = await mergePath(path, old.get(path), next.get(path), bornOnce, tree, mergeFile); if (outcome !== undefined) report.push({ path, outcome }); } diff --git a/packages/cli-template/src/types.ts b/packages/cli-template/src/types.ts index 7bb77677..b85b92b1 100644 --- a/packages/cli-template/src/types.ts +++ b/packages/cli-template/src/types.ts @@ -51,7 +51,9 @@ // Each rendered path has an owner, the template that wrote it, and a policy: // `merge` (the default) or `born-once`, written only at birth, where neither // the old render nor the current directory holds the path, and never touched -// or deleted after. `merge` takes the policies of both renders, the old one's +// or deleted after; or `birth-only`, a born-once path that is written at a +// birth alone, where the old render holds nothing, so that an update never adds +// it to a directory that was born before the template had it. `merge` takes the policies of both renders, the old one's // for the paths only it has. // // `merge` takes three trees, the old render, the new render and the current @@ -97,7 +99,7 @@ export type Tree = ReadonlyMap; export type Answers = Readonly>; /** How `merge` treats a path. */ -export type Policy = 'merge' | 'born-once'; +export type Policy = 'merge' | 'born-once' | 'birth-only'; /** The six types an answer is cast to. */ export type QuestionType = 'str' | 'int' | 'float' | 'bool' | 'yaml' | 'json'; diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index db8f4baa..a151a5fe 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -72,17 +72,33 @@ exit 1 * the Result's. */ const ANSIBLE = `printf '%s\\n' "$*" >> "$FAKE/ansible.log" -check= syntax= name= environment= file= last= +check= syntax= name= envfile= file= last= +# An extra variable as Ansible reads it: a JSON object, else key=value words split on whitespace, which a word with no +# \`=\` is no variable of. +extra() { + node -e 'const v = process.argv[1]; let o = {}; + if (v.startsWith("{")) o = JSON.parse(v); + else for (const w of v.split(/\\s+/).filter(Boolean)) { + const i = w.indexOf("="); + if (i < 0) { console.error("ERROR: Invalid extra vars: " + w); process.exit(1); } + o[w.slice(0, i)] = w.slice(i + 1); + } + console.log([o.stack_name ?? "", o.stack_environment_file ?? "", o.stack_compose_file ?? ""].join("\\n"));' "$1" +} for a in "$@"; do case "$a" in --syntax-check) syntax=1 ;; --check) check=1 ;; esac - case "$last$a" in - -estack_name=*) name=\${a#stack_name=} ;; - -estack_environment=*) environment=\${a#stack_environment=} ;; - -estack_compose_file=*) file=\${a#stack_compose_file=} ;; - esac + if [ "$last" = -e ]; then + got=$(extra "$a") || exit 1 + { read -r n; read -r e; read -r c; } < "$FAKE/$project.yaml" +cat "$envfile" > "$FAKE/$project.environment.yaml" echo "PLAY [Deploy one environment of a stack] ****" echo "TASK [plexus.platform.stack : Check the variables] ($project) ****" : > "$FAKE/running.$name" @@ -170,22 +188,23 @@ const stack = (name: string, compose: string) => ({ [`stacks/${name}/PLEXUS.md`]: '---\nprofile: stateless\n---\n', [`stacks/${name}/compose.yaml`]: compose, }); -const record = (target: string | undefined, ...stacks: string[]) => - `${target ? `plexus_deploy_target: ${target}\n` : ''}plexus_apps:\n${stacks.map((s) => ` - name: ${s}\n environment: staging\n`).join('')}`; +/** The file of an environment of a stack, in its directory: the host it deploys to, as the file says it. */ +const environment = (stackName: string, name: string, host: string, more = '') => ({ + [`stacks/${stackName}/${name}.yaml`]: `host: ${host}\n${more}`, +}); interface Fixture { root: string; repo: string; - inv: string; fake: string; } /** - * A checkout with the apps shop and admin and the stacks shop, admin and docs, which has no app; an inventory with - * records in staging for all three, shop and admin on one host, docs on another reached on its own port. + * A checkout with the apps shop and admin and the stacks shop, admin and docs, which has no app; a file for staging + * in each, shop and admin on one host, docs on another as a user of its own and on its own port. */ -function fixture(): Fixture { - const root = mkdtempSync(join(scratch, 'case-')); +function fixture(prefix = 'case-'): Fixture { + const root = mkdtempSync(join(scratch, prefix)); const repo = join(root, 'repo'); put(repo, { 'PLEXUS.md': '---\nrepo: shop\n---\n', @@ -194,13 +213,11 @@ function fixture(): Fixture { ...stack('shop', SHOP_COMPOSE), ...stack('admin', ADMIN_COMPOSE), ...stack('docs', DOCS_COMPOSE), + ...environment('shop', 'staging', 'a.example.com'), + ...environment('admin', 'staging', 'a.example.com'), + ...environment('docs', 'staging', 'deploy@b.example.com:2222'), }); - const inv = join(root, 'inv'); - put(inv, { - 'host_vars/a.yml': record('ssh://deploy@a.example.com', 'shop', 'admin'), - 'host_vars/b.yml': record('ssh://deploy@b.example.com:2222', 'docs'), - }); - return { root, repo, inv, fake: fakes(root) }; + return { root, repo, fake: fakes(root) }; } /** What the last `plx` wrote, whether it ended or threw. */ @@ -236,19 +253,13 @@ async function plx(args: string[], fake: string, env: Record = { return wrote.err; } -/** `plx deploy` for staging in the fixture's checkout with its inventory, with more arguments. */ -const staging = (f: Fixture, ...more: string[]) => [ - 'deploy', - '-e', - 'staging', - '--inventory', - f.inv, - '--commit', - SHA, - '-C', - f.repo, - ...more, -]; +/** `plx deploy` for staging in the fixture's checkout, with more arguments. */ +const staging = (f: Fixture, ...more: string[]) => ['deploy', '-e', 'staging', '--commit', SHA, '-C', f.repo, ...more]; + +/** The one JSON object of variables a call of the playbook was given, as the text it was written in. */ +const varsIn = (call: string): string => /-e (\{.*\})/.exec(call)?.[1] ?? ''; +/** The variables of a call. */ +const varsOf = (call: string): Record => JSON.parse(varsIn(call) || '{}'); /** The calls of the stack playbook that deployed, one line each, without the check that it is installed. */ const runs = (fake: string): string[] => @@ -289,27 +300,49 @@ test('plx deploy renders each stack with every app image pinned by the digest it ]); }); -test('plx deploy runs the stack playbook once per stack against the host of its record, all stacks at once, and ends with one line per stack', async () => { +test('the variables go to the playbook as one JSON object, so a checkout whose path has a space and an = deploys', async () => { + const f = fixture('sp ace=x-'); + assert.match(f.repo, /sp ace=x-/); + const err = await plx(staging(f), f.fake); + assert.deepEqual(summary(err), ['✓ admin-staging: deployed', '✓ docs-staging: deployed', '✓ shop-staging: deployed']); + const calls = runs(f.fake); + assert.equal(calls.length, 3); + for (const call of calls) { + assert.equal(call.match(/ -e /g)?.length, 1, 'one -e: a variable of the call is no word of its own'); + assert.equal(varsOf(call).stack_environment_file?.startsWith(f.repo), true, call); + } +}); + +test('plx deploy runs the stack playbook once per stack with the environment file of the stack, all stacks at once, and ends with one line per stack', async () => { const f = fixture(); writeFileSync(join(f.fake, 'together'), 'shop\nadmin\ndocs\n'); const err = await plx(staging(f), f.fake); const calls = runs(f.fake); assert.equal(calls.length, 3, calls.join('\n')); - const call = (name: string) => calls.find((c) => c.includes(`stack_name=${name} `)) ?? ''; - assert.match( - call('shop'), - /^-i a\.example\.com, -u deploy .*-e stack_name=shop -e stack_environment=staging -e stack_compose_file=\S+ plexus\.platform\.stack$/, + const call = (name: string) => calls.find((c) => varsOf(c).stack_name === name) ?? ''; + // The host, its user and its port are the file's, which the playbook reads: no inventory, no user, no environment name. + assert.equal( + call('shop').replace(varsIn(call('shop')), ''), + '--ssh-common-args -o StrictHostKeyChecking=accept-new -e plexus.platform.stack', ); - assert.match(call('docs'), /^-i b\.example\.com, -u deploy -e ansible_port=2222 /); + assert.deepEqual( + { ...varsOf(call('shop')), stack_compose_file: '' }, + { + stack_name: 'shop', + stack_environment_file: join(f.repo, 'stacks/shop/staging.yaml'), + stack_compose_file: '', + }, + ); + for (const call of calls) assert.doesNotMatch(call, /(^| )-[iu] |stack_environment=|ansible_port/); assert.doesNotMatch(err, /ran alone/, 'every stack ran while the others did'); // Each run's output is one block under a line naming the stack, its environment and the host, never interleaved. const projects = { 'shop-staging': 'a.example.com', 'admin-staging': 'a.example.com', - 'docs-staging': 'b.example.com:2222', + 'docs-staging': 'deploy@b.example.com:2222', }; for (const [project, host] of Object.entries(projects)) { - const block = err.split(`── ${project} → ssh://deploy@${host} ──\n`)[1]?.split(/^── /m)[0] ?? ''; + const block = err.split(`── ${project} → ${host} ──\n`)[1]?.split(/^── /m)[0] ?? ''; assert.match(block, new RegExp(`\\(${project}\\) \\*+\\nok: \\[host\\] \\(${project}\\)`), err); for (const other of Object.keys(projects).filter((p) => p !== project)) assert.doesNotMatch(block, new RegExp(`\\(${other}\\)`), err); @@ -318,10 +351,9 @@ test('plx deploy runs the stack playbook once per stack against the host of its assert.equal(process.exitCode, undefined); }); -test('plx deploy says what each stack came to: unchanged, rolled back, a run that ended early, no record, no target; one failure fails the run and stops no other', async () => { +test('plx deploy says what each stack came to: unchanged, rolled back, a run that ended early, no file for the environment; one failure fails the run and stops no other', async () => { const f = fixture(); - put(f.repo, { ...stack('blog', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE) }); - put(f.inv, { 'group_vars/platform.yml': record(undefined, 'wiki') }); + put(f.repo, stack('blog', DOCS_COMPOSE)); writeFileSync(join(f.fake, 'outcome.admin'), 'unchanged\n'); writeFileSync( join(f.fake, 'outcome.shop'), @@ -334,12 +366,44 @@ test('plx deploy says what each stack came to: unchanged, rolled back, a run tha const err = await plx(staging(f), f.fake); assert.deepEqual(summary(err), [ '✓ admin-staging: unchanged', - '- blog-staging: no record in staging; not deployed', + '- blog-staging: no staging.yaml; not deployed', '✗ docs-staging: failed: ansible-playbook exited 4: fatal: [b.example.com]: UNREACHABLE! ssh: connect to host b.example.com port 2222: Connection refused', "✗ shop-staging: rolled back: 'Bring the stack up and wait for health' failed (rc 1): General error: container shop-staging-web-1 is unhealthy", - `✗ wiki-staging: its record in ${join(f.inv, 'group_vars/platform.yml')} names no plexus_deploy_target`, ]); - assert.equal(runs(f.fake).length, 3, 'blog and wiki were deployed nowhere'); + assert.equal(runs(f.fake).length, 3, 'blog was deployed nowhere'); + assert.equal(process.exitCode, 1); +}); + +test('a checkout or scratch path holding {{ or {% is refused before anything runs, saying why: Ansible would template it', async () => { + for (const prefix of ['{{ 7 * 7 }}-', '{% x %}-']) { + const f = fixture(prefix); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => e instanceof UsageError && e.message.includes('Ansible') && e.message.includes(prefix), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); + } + const f = fixture(); + const odd = join(f.root, 'tmp {{ x }}'); + mkdirSync(odd); + await assert.rejects( + plx(staging(f), f.fake, { TMPDIR: odd }), + (e: unknown) => e instanceof UsageError && e.message.includes('Ansible') && e.message.includes(odd), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false); +}); + +test('a run that exits 0 and prints no Result line is a failure whatever its exit code', async () => { + // As ansible-playbook ends when a --limit or --skip-tags leaves it no task to run. + const f = fixture(); + writeFileSync(join(f.fake, 'outcome.docs'), 'exit 0 skipping: no hosts matched\n'); + const err = await plx(staging(f), f.fake); + assert.ok( + summary(err).includes('✗ docs-staging: failed: ansible-playbook exited 0: skipping: no hosts matched'), + err, + ); + assert.ok(summary(err).includes('✓ admin-staging: deployed'), 'the others ran'); assert.equal(process.exitCode, 1); }); @@ -358,16 +422,17 @@ test('a repo whose stacks have zero apps deploys the same way: no image is resol 'PLEXUS.md': '---\ntemplates: [repo-operations]\n---\n', ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs', 'wiki'), + ...environment('docs', 'staging', 'b.example.com'), + ...environment('wiki', 'staging', 'b.example.com'), }); - const err = await plx(['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '-C', ops], f.fake); + const err = await plx(['deploy', '-e', 'staging', '-C', ops], f.fake); assert.deepEqual(summary(err), ['✓ docs-staging: deployed', '✓ wiki-staging: deployed']); assert.equal(existsSync(join(f.fake, 'docker.log')), false); }); test('without --environment the environment follows the branch; where it follows none, the verb says so', async () => { const f = fixture(); - const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo]; + const args = ['deploy', '--commit', SHA, '-C', f.repo]; await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'pull_request', GITHUB_REF_NAME: '3/merge' }), UsageError, @@ -378,34 +443,27 @@ test('without --environment the environment follows the branch; where it follows assert.equal(summary(err).length, 3); }); -test('plx deploy needs the inventory the records are read from, and says what to pass in the same words in every repo', async () => { +/** `plx` as its own process, which ends as a command line does: its exit code and what it wrote to stderr. */ +function plxProcess(args: string[]): { status: number | null; stderr: string } { + const bin = fileURLToPath(new URL('../bin.ts', import.meta.url)); + const env: NodeJS.ProcessEnv = { ...process.env }; + for (const name of ['GITHUB_EVENT_NAME', 'GITHUB_REF_NAME', 'PLX_DRY_RUN', 'NODE_TEST_CONTEXT']) delete env[name]; + const { status, stderr } = spawnSync(process.execPath, [bin, ...args], { env, encoding: 'utf8' }); + return { status, stderr }; +} + +test('plx deploy has no --inventory: a deploy reads only its own repo, and the flag is an unknown option', () => { const f = fixture(); - const refusal = (e: unknown) => - e instanceof UsageError && - e.message.includes('--inventory /inventory') && - e.message.includes('--inventory inventory'); - let first = ''; - await assert.rejects(plx(['deploy', '-e', 'staging', '-C', f.repo], f.fake), (e: unknown) => { - first = (e as Error).message; - return refusal(e); - }); - const ops = join(f.root, 'operations'); - put(ops, { 'PLEXUS.md': '---\ntemplates: [repo-operations]\n---\n', ...stack('docs', DOCS_COMPOSE) }); - await assert.rejects( - plx(['deploy', '-e', 'staging', '-C', ops], f.fake), - (e: unknown) => refusal(e) && (e as Error).message === first, - ); - await assert.rejects( - plx(['deploy', '-e', 'staging', '--inventory', join(f.root, 'nowhere'), '-C', f.repo], f.fake), - (e: unknown) => e instanceof UsageError && /no inventory directory/.test(e.message), - ); + const { status, stderr } = plxProcess(['deploy', '-e', 'staging', '--inventory', join(f.root, 'inv'), '-C', f.repo]); + assert.notEqual(status, 0); + assert.match(stderr, /unknown option '--inventory'/); assert.deepEqual(runs(f.fake), []); }); test('a --commit that is not a full hash is one usage error naming it, before any stack is deployed', async () => { const f = fixture(); await assert.rejects( - plx(['deploy', '-e', 'staging', '--inventory', f.inv, '--commit', 'abc1234', '-C', f.repo], f.fake), + plx(['deploy', '-e', 'staging', '--commit', 'abc1234', '-C', f.repo], f.fake), (e: unknown) => e instanceof UsageError && /--commit.*full/.test(e.message), ); assert.deepEqual(runs(f.fake), []); @@ -457,7 +515,7 @@ test('a checkout without a stack is refused, for there is nothing to deploy; a c const f = fixture(); const bare = join(f.root, 'bare'); put(bare, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); - const args = ['deploy', '-e', 'staging', '--inventory', f.inv, '-C', bare]; + const args = ['deploy', '-e', 'staging', '-C', bare]; await assert.rejects( plx(args, f.fake), (e: unknown) => e instanceof Error && /has no stack to deploy/.test(e.message) && !/apps\//.test(e.message), @@ -479,7 +537,7 @@ test('a checkout without a stack is refused, for there is nothing to deploy; a c assert.deepEqual(runs(f.fake), []); }); -test('where no stack has a record in the environment, each is named, and the run fails, for nothing was deployed; it needs no Ansible', async () => { +test('where no stack has a file for the environment, each is named, and the run fails, for nothing was deployed; it needs no Ansible', async () => { const f = fixture(); const noAnsible = fakes(join(f.root, 'no-ansible'), ['docker']); const err = await plx( @@ -489,25 +547,82 @@ test('where no stack has a record in the environment, each is named, and the run true, ); assert.deepEqual(err.trimEnd().split('\n').slice(-4), [ - '- admin-production: no record in production; not deployed', - '- docs-production: no record in production; not deployed', - '- shop-production: no record in production; not deployed', - '✗ no stack has a record in production: nothing was deployed', + '- admin-production: no production.yaml; not deployed', + '- docs-production: no production.yaml; not deployed', + '- shop-production: no production.yaml; not deployed', + '✗ no stack has a production.yaml: nothing was deployed', ]); assert.equal(process.exitCode, 1); - // One stack with a record: the others are skipped, and no failure. - put(f.inv, { 'host_vars/a.yml': record('ssh://deploy@a.example.com', 'shop') }); - put(f.inv, { 'host_vars/b.yml': 'plexus_apps: []\n' }); + // One stack with a file: the others are skipped, and no failure. + for (const name of ['admin', 'docs']) rmSync(join(f.repo, 'stacks', name, 'staging.yaml')); process.exitCode = undefined; const one = await plx(staging(f), f.fake); assert.deepEqual(summary(one), [ - '- admin-staging: no record in staging; not deployed', - '- docs-staging: no record in staging; not deployed', + '- admin-staging: no staging.yaml; not deployed', + '- docs-staging: no staging.yaml; not deployed', '✓ shop-staging: deployed', ]); assert.equal(process.exitCode, undefined); }); +test('an environment file with a problem refuses the run before any host is reached, naming every problem; another environment’s file is not read', async () => { + const f = fixture(); + put(f.repo, { + ...environment('admin', 'staging', '-oProxyCommand=x'), + ...environment('docs', 'staging', 'b.example.com', 'env: {PORT: 3000}\n'), + ...environment('docs', 'production', '-oProxyCommand=y'), + }); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.includes('stacks/admin/staging.yaml') && + e.message.includes('stacks/docs/staging.yaml') && + !e.message.includes('production.yaml') && + /no stack was deployed/.test(e.message), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); +}); + +test('a refusal gives the loader’s message as it wrote it: an op:// pointer stays op://', async () => { + const f = fixture(); + put(f.repo, environment('admin', 'staging', 'a.example.com', 'secrets: {TOKEN: not-a-pointer}\n')); + await assert.rejects( + plx(staging(f), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.includes('stacks/admin/staging.yaml') && + e.message.includes('is no `op://` pointer') && + !e.message.includes('op:/`'), + ); +}); + +test('in CI an environment with secrets and no vault token is refused by naming the repository secret, before any host or registry is touched; a person at a checkout is not', async () => { + const withSecrets = (f: Fixture) => + put(f.repo, environment('admin', 'staging', 'a.example.com', 'secrets: {TOKEN: op://acme/admin/token}\n')); + const ci = { GITHUB_ACTIONS: 'true', OP_SERVICE_ACCOUNT_TOKEN: '' }; + const f = fixture(); + withSecrets(f); + await assert.rejects( + plx(staging(f), f.fake, ci), + (e: unknown) => + e instanceof UsageError && + e.message.includes('DEPLOY_VAULT_TOKEN') && + e.message.includes('stacks/admin/staging.yaml'), + ); + assert.equal(existsSync(join(f.fake, 'ansible.log')), false, 'no playbook ran'); + assert.equal(existsSync(join(f.fake, 'docker.log')), false, 'no registry was read'); + // A token, a person's session (no CI), or no secrets at all: the run goes on. + await plx(staging(f), f.fake, { ...ci, OP_SERVICE_ACCOUNT_TOKEN: 'a-token' }); + const person = fixture(); + withSecrets(person); + await plx(staging(person), person.fake, { GITHUB_ACTIONS: '', OP_SERVICE_ACCOUNT_TOKEN: '' }); + const bare = fixture(); + await plx(staging(bare), bare.fake, ci); + assert.equal(runs(bare.fake).length, 3); +}); + test('in the human mode plx deploy prints no result on stdout, and with --json the result', async () => { const f = fixture(); await plx(staging(f), f.fake); @@ -531,9 +646,9 @@ test('a commit that YAML would read as a number goes in quoted, for PLEXUS_TAG a `services:\n web:\n image: docker.io/acme/docs:1.2.3\n environment:\n RELEASE: \${PLEXUS_TAG}\n COMMIT: \${PLEXUS_COMMIT_SHA:-}\n`, ), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs'), + ...environment('docs', 'staging', 'b.example.com'), }); - await plx(['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '--commit', numeric, '-C', ops], f.fake); + await plx(['deploy', '-e', 'staging', '--commit', numeric, '-C', ops], f.fake); assert.equal( readFileSync(join(f.fake, 'docs-staging.yaml'), 'utf8'), `services:\n web:\n image: docker.io/acme/docs:1.2.3\n environment:\n RELEASE: "${numeric}"\n COMMIT: "${numeric}"\n`, @@ -614,8 +729,9 @@ test('a repo whose stack/ its root marker does not name is refused, naming the k 'apps/shop/Dockerfile': 'FROM scratch\n', 'stack/PLEXUS.md': '---\nprofile: stateless\n---\n', 'stack/compose.yaml': SHOP_COMPOSE, + 'stack/staging.yaml': 'host: a.example.com\n', }); - const args = ['deploy', '-e', 'staging', '--inventory', f.inv, '--commit', SHA, '-C', one]; + const args = ['deploy', '-e', 'staging', '--commit', SHA, '-C', one]; await assert.rejects( plx(args, f.fake), (e: unknown) => @@ -643,15 +759,16 @@ test('a repo whose stacks the loader finds a problem with is refused with every assert.equal(existsSync(join(f.fake, 'ansible.log')), false); }); -/** A repo of the stacks docs and wiki, which have no app, and its inventory. */ +/** A repo of the stacks docs and wiki, which have no app, each with a file for staging. */ function operations(f: Fixture): string[] { const ops = join(f.root, 'operations'); put(ops, { ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), - 'inventory/host_vars/b.yml': record('ssh://deploy@b.example.com', 'docs', 'wiki'), + ...environment('docs', 'staging', 'b.example.com'), + ...environment('wiki', 'staging', 'b.example.com'), }); - return ['deploy', '-e', 'staging', '--inventory', join(ops, 'inventory'), '-C', ops]; + return ['deploy', '-e', 'staging', '-C', ops]; } test('without ansible-playbook on the PATH the run is refused, saying what to install', async () => { @@ -682,7 +799,7 @@ test('without the collection where Ansible looks the run is refused, saying how // --- the dry run and the arguments for ansible-playbook ------------------------------------------- /** The compose file a call of the playbook was handed. */ -const handed = (call: string) => /-e stack_compose_file=(\S+)/.exec(call)?.[1] ?? ''; +const handed = (call: string) => varsOf(call).stack_compose_file ?? ''; test('a dry run is the playbook’s own, --check --diff, after every read; it keeps the files it handed over and names where', async () => { const f = fixture(); @@ -936,14 +1053,11 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r `, [`stacks/${run}-docs/compose.yaml`]: `services:\n web:\n image: ${docs}\n init: true\n command: ["sleep", "3600"]\n`, }); - const inv = join(root, 'inventory'); - put(inv, { - 'host_vars/localhost.yml': `plexus_deploy_target: ssh://localhost\nplexus_apps:\n${['shop', 'docs'].map((s) => ` - name: ${run}-${s}\n environment: staging\n`).join('')}`, - }); - // Each environment's directory and .env, as the platform playbook lays them out. + // Each stack's file for staging: the host it deploys to, here this machine, and a scratch directory as the root. + for (const s of ['shop', 'docs']) put(repo, { [`stacks/${run}-${s}/staging.yaml`]: 'host: localhost\n' }); + // The root of the stacks, which the platform playbook prepares on a host. const stacks = join(root, 'stacks'); - for (const s of ['shop', 'docs']) - put(stacks, { [`${run}-${s}-staging/.env`]: `COMPOSE_PROJECT_NAME=${run}-${s}-staging\n` }); + mkdirSync(stacks); // The collection of this checkout, alone where Ansible looks; community.docker is the one the ansible package brings. const collections = join(root, 'collections'); mkdirSync(join(collections, 'ansible_collections', 'plexus'), { recursive: true }); @@ -957,7 +1071,7 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r plx( [ ...global, - ...['deploy', '-e', 'staging', '--inventory', inv, '--commit', commit(n), '-C', repo, '--'], + ...['deploy', '-e', 'staging', '--commit', commit(n), '-C', repo, '--'], ...['-c', 'local', '-e', 'ansible_python_interpreter=auto_silent', '-e', `stack_root=${stacks}`], ...['-e', 'stack_wait_timeout=30'], ], diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index a4e4f61e..85d40189 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -1,21 +1,22 @@ -// plx deploy: every stack of the checkout that has a record in an -// environment, onto the host its record names, through the stack playbook +// plx deploy: every stack of the checkout that has an environment's file, +// onto the host the file names, through the stack playbook // (§ 6 PLX-Delivery). lib's `deploy` does the work, and its header says how, // in order; this file maps the arguments and sets the exit code. // // The environment is --environment, else follows from the branch of the -// forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME). The records are read from -// --inventory, the inventory directory of the operations repo, which is -// required in every repo, the operations repo too (`--inventory inventory`). -// The images are the commit's, --commit (a full hash, SHA-1 or SHA-256), else +// forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME). Nothing but the checkout +// is read: the host is in each stack's file, and the secrets the file points +// at are read by the playbook, with the `op` of whoever runs the verb, in a job +// with its service account's token (OP_SERVICE_ACCOUNT_TOKEN) and by a person +// with their own session. The images are the commit's, --commit (a full hash, SHA-1 or SHA-256), else // the checkout's HEAD. Arguments after `--` go to every run of // ansible-playbook; an operand before it is refused. Exit code 1 when any // stack failed or none was deployed. An empty option value is the same as an // absent one, so a mount can always pass the flag. // -// plx deploy --environment staging --inventory ../operations/inventory -// plx deploy --inventory operations/inventory # in a job, on a push to main or develop -// plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180 +// plx deploy --environment staging +// plx deploy # in a job, on a push to main or develop +// plx deploy -e production -- -e stack_wait_timeout=180 import { resolve } from 'node:path'; import { deploy, ENVIRONMENT_BRANCHES, environmentOf, UsageError } from '@plexus-ms/lib'; import type { Command } from 'commander'; @@ -23,7 +24,6 @@ import { contextOf, version } from '../program.ts'; interface Opts { environment?: string; - inventory?: string; commit?: string; dir: string; } @@ -32,23 +32,18 @@ export function register(program: Command): void { program .command('deploy') .description( - 'deploy every stack of the checkout that has a record in the environment: render its compose file with each app’s image pinned by digest, run the stack playbook against its host, all stacks at once', + 'deploy every stack of the checkout that has a file for the environment: render its compose file with each app’s image pinned by digest, run the stack playbook against its host, all stacks at once', ) .argument('[ansible-playbook-arguments...]', 'after --: arguments for every run of ansible-playbook') .option( '-e, --environment ', 'the environment deployed into (default: from the branch, in a job of the forge)', ) - .option('--inventory ', 'the operations repo’s inventory, which holds each stack’s record') .option('--commit ', 'the commit whose images are deployed (default: the checkout’s HEAD)') .option('-C, --dir ', 'the checkout to read', '.') .action(async (operands: string[], opts: Opts, command: Command) => { const ctx = contextOf(command); const ansible = afterDoubleDash(command, operands); - if (!opts.inventory) - throw new UsageError( - 'plx deploy needs the inventory its records are read from: pass --inventory /inventory, which in the operations repo itself is --inventory inventory', - ); if (opts.commit && !/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(opts.commit)) throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 or 64 hex digits in lower case`); const env = process.env; @@ -59,7 +54,6 @@ export function register(program: Command): void { ); const result = await deploy(ctx, { environment, - inventory: resolve(opts.inventory), commit: opts.commit || undefined, dir: resolve(opts.dir), ansible, diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index c62b4bbb..ab025479 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -371,9 +371,10 @@ const fakeLog = () => read(FAKE_LOG()).split('\n').filter(Boolean); const up = (r: string) => join(WS, 'plexus-ms', r); const remote = (r: string) => join(WS, 'remotes', `${r}.git`); -/** A bare origin for a repo, with its branches and tags pushed. */ +/** A bare origin for a repo, with its branches and tags pushed, and the branch the repo is on as its default. */ const withOrigin = (path: string, name: string) => { git(WS, 'init', '--quiet', '--bare', remote(name)); + git(remote(name), 'symbolic-ref', 'HEAD', `refs/heads/${git(path, 'symbolic-ref', '--short', 'HEAD')}`); git(path, 'remote', 'add', 'origin', remote(name)); git(path, 'push', '--quiet', 'origin', '--all'); git(path, 'push', '--quiet', 'origin', '--tags'); @@ -1480,19 +1481,54 @@ test('update --recursive: a named version is validated, and asks every repo for assert.equal(result?.pulls.length, 2); }); -test('update --recursive: a repo whose origin lacks the branch the version lands on is skipped, with the reason', async () => { - fixture('no-branch'); +test('update --recursive: an app repo whose default branch is main, with no develop, takes the version on main', async () => { + fixture('default-main'); + git(remote('acme-web'), 'branch', '--quiet', '-m', 'develop', 'main'); + git(remote('acme-web'), 'symbolic-ref', 'HEAD', 'refs/heads/main'); + const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-web', '0.2.0', '.base'), 'main'); + assert.equal(git(remote('acme-web'), 'rev-list', '--count', 'main..plexus/0.2.0'), '1'); + const alone = await runUpdate({ yes: true }, { repo: join(WS, 'acme/platform'), to: '0.2.0' }); + assert.equal(alone.error, undefined, alone.out); + assert.equal(pull('acme-platform', '0.2.0', '.base'), 'main'); +}); + +test('update: an operations repo takes the version on its default branch, whatever it is called', async () => { + fixture('default-trunk'); + git(remote('acme-platform'), 'branch', '--quiet', '-m', 'main', 'trunk'); + git(remote('acme-platform'), 'symbolic-ref', 'HEAD', 'refs/heads/trunk'); + const { result, error, out } = await runUpdate({ yes: true }, { repo: join(WS, 'acme/platform'), to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-platform', '0.2.0', '.base'), 'trunk'); +}); + +test('update --recursive: a repo whose origin says no default branch is skipped, with why and what to do', async () => { + fixture('no-default'); git(remote('acme-web'), 'update-ref', '-d', 'refs/heads/develop'); const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); assert.equal(error, undefined, out); - const reason = 'origin has no branch `develop`, the one the version lands on'; - assert.ok(has(out, `⚠ acme/web: ${reason} — skipped`), out); - assert.deepEqual(result?.skipped, [{ path: 'acme/web', reason }]); + assert.match( + out, + /⚠ acme\/web: origin's HEAD names no existing branch.*set the default branch on the forge.* — skipped/, + ); + assert.equal(result?.skipped.length, 1); assert.deepEqual(result?.failed, []); assert.equal(result?.pulls.length, 1, 'the other repo takes the version'); - const alone = await runUpdate({ yes: true }, { repo: join(WS, 'acme/web'), to: '0.2.0' }); - assert.equal(alone.error, undefined, alone.out); - assert.deepEqual(alone.result?.skipped, [{ path: 'web', reason }]); +}); + +test('update --recursive: a clone made while develop was the default lands the version on the default branch origin has now', async () => { + fixture('stale-record'); + git(join(WS, 'acme/web'), 'remote', 'set-head', 'origin', 'develop'); + git(remote('acme-web'), 'branch', '--quiet', 'main', 'develop'); + git(remote('acme-web'), 'symbolic-ref', 'HEAD', 'refs/heads/main'); + const { result, error, out } = await runRecursive({ yes: true }, { to: '0.2.0' }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.skipped, []); + assert.equal(pull('acme-web', '0.2.0', '.base'), 'main'); + assert.equal(git(remote('acme-web'), 'rev-list', '--count', 'main..plexus/0.2.0'), '1'); }); test('the confirmation aborts cleanly without a terminal', async () => { @@ -2698,7 +2734,7 @@ test('update: the dry run says a conflict would be committed with its markers, n assert.ok(!has(out, 'CONFLICTS at web/apps/site, committed'), 'nothing is committed in a dry run'); }); -test('the preview reports a consumer without an origin, one that cannot be cloned and one that has not crossed over, and removes its scratch', async () => { +test('the preview reports a consumer without an origin, one whose origin cannot be asked and one that has not crossed over, and removes its scratch', async () => { fixture('dry-others'); const tmp = join(WS, 'tmp'); mkdirSync(tmp); @@ -2724,10 +2760,16 @@ test('the preview reports a consumer without an origin, one that cannot be clone else process.env.TMPDIR = outer; }); assert.equal(error, undefined, out); - assert.deepEqual(result?.skipped, [{ path: 'acme/noorigin', reason: 'no origin remote' }]); + assert.deepEqual( + result?.skipped.map((s) => s.path), + ['acme/gone', 'acme/noorigin'], + ); assert.ok(has(out, '⚠ acme/noorigin: no origin remote — not previewed'), out); - assert.deepEqual([...(result?.failed ?? [])].sort(), ['acme/gone', 'acme/legacy']); - assert.ok(has(out, '✗ FAILED — clone'), 'the clone that failed is named'); + assert.ok( + has(out, '⚠ acme/gone: origin did not answer') && has(out, '— not previewed'), + 'an origin that cannot be asked leaves no default branch to clone', + ); + assert.deepEqual(result?.failed, ['acme/legacy']); assert.ok(has(out, 'acme/legacy: ') && has(out, 'still tracks a .copier-answers.yml'), out); assert.deepEqual(result?.clean, ['acme/platform', 'acme/web', 'acme/web/apps/site'], 'the others are previewed'); assert.ok(has(out, join(tmp, 'plx-preview')), 'the scratch is made where TMPDIR says, on every system'); diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index 15eb5af3..d1954da7 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -3,7 +3,9 @@ // the deploy verb the images of its apps, and doctor runs the compose checks // of PLX-Stack over it. It reads what compose would read as far as plain YAML // goes, with anchors and merge keys resolved, and `${…}` interpolation left as -// written. A service that `extends` another service of the same file is read +// written. A +// document whose aliases form a cycle is a usage error, as compose refuses it, so +// that no walk of the document meets one. A service that `extends` another service of the same file is read // merged with it, through a chain of such services (`resolveExtends`); // services that extend each other in a cycle are an error naming them, as // compose refuses them. Not read: the files an `include` names, whose presence @@ -21,6 +23,8 @@ import { UsageError } from './version.ts'; export type Mapping = Record; export interface Compose { + /** The whole document as parsed, anchors and merge keys resolved, interpolation as written; what interpolation is read from. */ + document: unknown; /** The services by name, same-file `extends` merged in; an entry that is not a mapping is left out. */ services: Record; /** The file has a top-level `include`, whose files are not read. */ @@ -30,6 +34,32 @@ export interface Compose { export const isMapping = (value: unknown): value is Mapping => value !== null && typeof value === 'object' && !Array.isArray(value); +/** The path of a node of the document that holds itself through its aliases, or none; each node is visited once. */ +function aliasCycle(doc: unknown): string | undefined { + const done = new Set(); + const path: string[] = []; + const onPath = new Set(); + const visit = (node: unknown): string | undefined => { + if (node === null || typeof node !== 'object' || done.has(node)) return undefined; + if (onPath.has(node)) return path.join('.') || 'the root'; + onPath.add(node); + for (const [key, child] of Object.entries(node)) { + path.push(key); + const found = visit(child); + path.pop(); + if (found !== undefined) return found; + } + onPath.delete(node); + done.add(node); + return undefined; + }; + return visit(doc); +} + +/** What a YAML error says, in one line: `not valid YAML: `. */ +export const yamlError = (error: unknown): string => + `not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`; + /** * A compose file from its text. A file that is not YAML compose could read * (duplicate keys among them) is a usage error naming the file. @@ -39,13 +69,15 @@ export function parseCompose(text: string, path: string): Compose { try { doc = parse(text, { merge: true }); } catch (error) { - throw new UsageError(`${path}: not valid YAML: ${(error as Error).message.split('\n')[0]?.replace(/:$/, '')}`); + throw new UsageError(`${path}: ${yamlError(error)}`); } + const cycle = aliasCycle(doc); + if (cycle) throw new UsageError(`${path}: aliases form a cycle at ${cycle}; compose refuses such a file`); const declared = isMapping(doc) && isMapping(doc.services) ? doc.services : {}; const written: Record = {}; for (const [name, service] of Object.entries(declared)) if (isMapping(service)) written[name] = service; const services = resolveExtends(written, path); - return { services, ...(isMapping(doc) && doc.include != null ? { includes: true as const } : {}) }; + return { document: doc, services, ...(isMapping(doc) && doc.include != null ? { includes: true as const } : {}) }; } /** diff --git a/packages/lib/src/consumers.test.ts b/packages/lib/src/consumers.test.ts index 2d2d2694..c8b742d6 100644 --- a/packages/lib/src/consumers.test.ts +++ b/packages/lib/src/consumers.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { expectedBranch, findRepos } from './consumers.ts'; +import { findRepos } from './consumers.ts'; import { Context } from './context.ts'; import type { Directory } from './model.ts'; import { fakeIo } from './testing/fakeIo.ts'; @@ -13,25 +13,6 @@ const dir = (path: string, facets: Partial = {}, children: Directory[ }); const marker = () => ({ declaration: { deviations: [], body: '' } }); -test('expectedBranch follows what the markers say the repo is, and the answers for a package repo', () => { - const config = (templates: string[], answers: Record = {}) => ({ - config: { version: '0.2.0', templates, deviations: [], answers }, - }); - assert.equal(expectedBranch(dir('/o', { ...config(['repo-operations']), ...marker() })), 'main'); - assert.equal(expectedBranch(dir('/w', { ...config(['repo-turbo']), ...marker() })), 'develop'); - assert.equal( - expectedBranch(dir('/l', { ...config(['repo-turbo'], { publishes_packages: true }), ...marker() })), - 'main', - 'a package repo, by the answer in its marker', - ); - assert.equal(expectedBranch(dir('/x', config(['repo-operations']))), undefined, 'no marker'); - assert.equal( - expectedBranch(dir('/y', { ...marker(), uncrossed: true })), - undefined, - 'not crossed over: the checkout’s', - ); -}); - test('findRepos takes a repo by a root marker that names a version or lists templates, or by an answers file beside its marker', async () => { const git = { branch: 'develop', dirty: false }; const config = (keys: Record) => ({ config: { deviations: [], answers: {}, ...keys } }); @@ -53,3 +34,82 @@ test('findRepos takes a repo by a root marker that names a version or lists temp 'a repo with templates and no version is found, for update to refuse it by name, and one that has not crossed over, for update to refuse it with the runbook', ); }); + +/** A workspace of one marked repo `name` per kind, with what `git` answers about its origin's default branch. */ +const kinds: Record = { + shop: ['repo-turbo'], + platform: ['repo-operations'], +}; +async function consumersWith( + git: (args: string[]) => string | undefined, + facets: Partial = {}, + names = Object.keys(kinds), +) { + const repos = names.map((name) => + dir(`/w/${name}`, { + git: { branch: 'checked-out', dirty: false }, + ...marker(), + config: { version: '0.2.0', templates: kinds[name] ?? [], deviations: [], answers: {} }, + ...facets, + }), + ); + const ctx = new Context( + { quiet: true }, + fakeIo({}, (_cwd, args) => (args[0] === 'remote' ? 'git@example.com:acme/x.git' : git(args))), + ); + return findRepos(ctx, dir('/w', {}, repos)); +} + +const says = (branch: string) => `ref: refs/heads/${branch}\tHEAD\n0123456789abcdef\tHEAD\n`; + +test('a version lands on the default branch origin says, in an app repo and an operations repo alike, whatever the checkout records', async () => { + const calls: string[][] = []; + const repos = await consumersWith((args) => { + calls.push(args); + if (args[0] === 'ls-remote') return says('trunk'); + return args[0] === 'symbolic-ref' ? 'origin/develop' : undefined; + }); + assert.deepEqual( + repos.map((r) => [r.rel, r.branch, r.skipped]), + [ + ['shop', 'trunk', undefined], + ['platform', 'trunk', undefined], + ], + 'a clone made while develop was the default does not land on develop', + ); + assert.ok(!calls.some((c) => c[0] === 'symbolic-ref'), 'the checkout’s record is not read'); +}); + +test('a package repo lands on its origin’s default branch too, and a branch name with a slash is read whole', async () => { + const repos = await consumersWith( + (args) => (args[0] === 'ls-remote' ? says('release/1') : undefined), + { config: { version: '0.2.0', templates: ['repo-turbo'], deviations: [], answers: { publishes_packages: true } } }, + ['shop'], + ); + assert.deepEqual([repos[0]?.branch, repos[0]?.skipped], ['release/1', undefined]); +}); + +test('an origin that does not answer skips the repo, saying so and what helps, and none is guessed', async () => { + const repos = await consumersWith(() => undefined, {}, ['shop']); + assert.equal(repos[0]?.branch, 'checked-out', 'the branch it is on is no answer'); + assert.match(repos[0]?.skipped ?? '', /origin did not answer/); + assert.match(repos[0]?.skipped ?? '', /check the access/); + assert.doesNotMatch(repos[0]?.skipped ?? '', /set-head/); +}); + +test('an origin whose HEAD names no existing branch skips the repo, saying so and what helps', async () => { + const repos = await consumersWith((args) => (args[0] === 'ls-remote' ? '' : undefined), {}, ['shop']); + assert.match(repos[0]?.skipped ?? '', /HEAD names no existing branch/); + assert.match(repos[0]?.skipped ?? '', /set the default branch on the forge/); +}); + +test('a repo that has not crossed over is taken on the branch its checkout is on, and origin is not asked', async () => { + const repos = await consumersWith( + () => { + throw new Error('asked'); + }, + { uncrossed: true, config: undefined }, + ['shop'], + ); + assert.deepEqual([repos[0]?.branch, repos[0]?.skipped], ['checked-out', undefined]); +}); diff --git a/packages/lib/src/consumers.ts b/packages/lib/src/consumers.ts index 71a3d643..6bfd9a8a 100644 --- a/packages/lib/src/consumers.ts +++ b/packages/lib/src/consumers.ts @@ -1,10 +1,15 @@ // The consumers of the templates: the repos under a directory that take a // version. A consumer is updated in a scratch checkout of its origin's branch, -// never in its own checkout, on the branch the version lands on: the -// operations repo rides main, an app repo rides develop (§ 3 PLX-Delivery), -// and a package repo (its root answers say `publishes_packages`) is -// trunk-based on main (§ 5 PLX-Delivery). A repo without a marker, or that has -// not crossed over, is taken on the branch its checkout is on. +// never in its own checkout, on the branch the version lands on: the default +// branch of its origin, whatever kind of repo it is. A repo without a marker, +// or that has not crossed over, is taken on the branch its checkout is on. +// +// The default branch is what origin says its HEAD is, asked with +// `git ls-remote --symref origin HEAD`: one call per repo, which works in a +// fresh CI checkout and with any forge, and never reads what the checkout +// remembers of origin. A repo whose origin does not answer, or whose HEAD names +// no existing branch, is skipped, never guessed from the branch it is on or +// from a name. // // `findRepos` finds them for `plx update`: every git repo whose root marker // names a version or lists templates, and every one that carries a marker and @@ -12,56 +17,74 @@ // the crossover runbook. import { relative } from 'node:path'; import type { Context } from './context.ts'; -import { type Directory, hasMarker, isOperations } from './model.ts'; +import { type Directory, hasMarker } from './model.ts'; export interface Consumer { path: string; rel: string; - /** The branch the version lands on: the expected one, or the checkout's own when the marker names none. */ + /** The branch the version lands on: origin's default branch, or the checkout's own for a repo that has not crossed over. */ branch: string; - expected?: 'main' | 'develop'; /** The URL of `origin`, which the scratch clone is made from. */ origin?: string; /** Why the consumer is left untouched this run, if it is. */ skipped?: string; } -/** The branch a consumer is updated on; undefined for a repo without a marker, and for one that has not crossed over, whose markers say nothing. */ -export function expectedBranch(repo: Directory): Consumer['expected'] { - if (!repo.declaration || repo.uncrossed) return undefined; - if (isOperations(repo)) return 'main'; - return repo.config?.answers.publishes_packages === true ? 'main' : 'develop'; -} +/** Whether the version lands on origin's default branch: the repo has crossed over to the markers. */ +const landsOnDefault = (repo: Directory): boolean => repo.declaration !== undefined && !repo.uncrossed; /** A consumer of the repo `dir`, named relative to `root`, before its origin is read. */ -const consumerOf = (root: Directory, dir: Directory): Consumer => { - const expected = expectedBranch(dir); - return { - path: dir.path, - rel: relative(root.path, dir.path) || '.', - branch: expected ?? dir.git?.branch ?? 'main', - expected, - }; -}; +const consumerOf = (root: Directory, dir: Directory): Consumer & { onDefault: boolean } => ({ + path: dir.path, + rel: relative(root.path, dir.path) || '.', + branch: dir.git?.branch ?? 'main', + onDefault: landsOnDefault(dir), +}); + +/** The default branch origin says, or why it cannot be told. */ +async function defaultBranch(ctx: Context, cwd: string): Promise<{ branch: string } | { why: string }> { + let said: string; + try { + said = await ctx.read('git', ['ls-remote', '--symref', 'origin', 'HEAD'], { cwd }); + } catch { + return { why: 'origin did not answer when asked for its default branch; check the access to it, then re-run' }; + } + const branch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(said)?.[1]; + return branch + ? { branch } + : { + why: "origin's HEAD names no existing branch, so it has no default branch; set the default branch on the forge, then re-run", + }; +} -/** Each consumer's origin, which the scratch clone is made from; one without is skipped. */ -async function withOrigins(ctx: Context, consumers: Consumer[]): Promise { - for (const c of consumers) { +/** Each consumer's origin, which the scratch clone is made from, and the default branch it lands on; one without either is skipped. */ +async function withOrigins(ctx: Context, consumers: (Consumer & { onDefault: boolean })[]): Promise { + const found: Consumer[] = []; + for (const { onDefault, ...c } of consumers) { const origin = (await ctx.read('git', ['remote', 'get-url', 'origin'], { cwd: c.path }).catch(() => '')).trim(); if (origin === '') c.skipped = 'no origin remote'; - else c.origin = origin; + else { + c.origin = origin; + if (onDefault) { + const answer = await defaultBranch(ctx, c.path); + if ('branch' in answer) c.branch = answer.branch; + else c.skipped = answer.why; + } + } + found.push(c); } - return consumers; + return found; } /** * The repos under a scanned workspace (`overview` with git facets) that take a * version, in tree order: each git repo whose root marker names a version or * lists templates, or which carries a marker and tracks an answers file at its - * root. A repo without an origin is skipped. + * root. A repo without an origin, or whose origin does not say a default + * branch, is skipped. */ export async function findRepos(ctx: Context, root: Directory): Promise { - const found: Consumer[] = []; + const found: (Consumer & { onDefault: boolean })[] = []; const visit = (dir: Directory) => { const marked = dir.config?.version !== undefined || dir.config?.templates !== undefined; if (dir.git && (marked || (dir.uncrossed && hasMarker(dir)))) found.push(consumerOf(root, dir)); diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index 15c289ce..94fc980f 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -1,9 +1,10 @@ -// deploy: brings every stack of a checkout that has a record in an -// environment onto the host the record names (§ 6 PLX-Delivery), through the -// stack playbook, plexus.platform.stack, whose header says what it does on -// the host. Every change on a host is the playbook's: this verb finds, -// renders, resolves, runs ansible-playbook and reports, and holds no rollback -// and no health logic of its own. In order: +// deploy: brings every stack of a checkout that has an environment's file onto +// the host the file names (§ 6 PLX-Delivery), through the stack playbook, +// plexus.platform.stack, whose header says what it does on the host. Every +// change on a host is the playbook's: this verb finds, renders, resolves, runs +// ansible-playbook and reports, and holds no rollback and no health logic of +// its own. It reads the checkout and nothing else of the repo's tenant: no +// second repo, no inventory. In order: // // 1. The stacks, from the checkout (`loadStacks`, stacks.ts). A checkout // with a problem the loader reports is refused with the loader's words, @@ -12,11 +13,12 @@ // stack is refused, for a deploy that deploys nothing is no success, // and the refusal names every compose file inside an app, where stacks // lived before. -// 2. The records, from the inventory given (deployTargets.ts): a stack's -// record is the one whose `name` is the stack's and whose `environment` -// is the one deployed, and its file's plexus_deploy_target, -// ssh://@
[:], is where the stack goes. Where no -// stack has a record, the run ends here: the summary names each stack, +// 2. The environment's files: a stack's file is `.yaml` in its +// directory (environments.ts), and its `host` is where the stack goes. A +// file with a problem refuses the run, with every problem of every +// stack's file for this environment, before any host or registry is +// reached; the files of other environments are not read for it. Where no +// stack has the file, the run ends here: the summary names each stack, // and the verb fails, for nothing was deployed; it needs no Ansible. // 3. The rendering: each compose.yaml with ${PLEXUS_TAG}, bare or with an // error message, set to the commit (given, else the checkout's HEAD), @@ -47,18 +49,22 @@ // looks), refuses the run, naming what to install; a check that takes // more than two minutes is stopped and refuses the run, saying so. Which // version of the collection is installed is not checked. -// 5. The runs, one per stack with a record, all at once: -// ansible-playbook -i
, [-u ] [-e ansible_port=] -// --ssh-common-args '-o StrictHostKeyChecking=accept-new' -// -e stack_name= -e stack_environment= -// -e stack_compose_file= [--check --diff] +// 5. The runs, one per stack with the file, all at once: +// ansible-playbook --ssh-common-args '-o StrictHostKeyChecking=accept-new' +// -e '{"stack_name": , "stack_environment_file": , +// "stack_compose_file": }' [--check --diff] // [] plexus.platform.stack -// in the run's directory, so that no ansible.cfg of the checkout is read, -// with stdin from /dev/null and the default callback printing its results -// as JSON. A run's output, both streams in one, is held until it ends and -// then written as one block under `── - → ──`, -// so no two runs' lines meet. A run that takes more than an hour is -// stopped and fails. +// with no inventory, user or port, and the variables as one JSON object, +// since Ansible splits `key=value` words on whitespace and a path may +// hold some: the playbook takes the host from the +// file, and the environment's name from its name; it resolves the file's +// `op://` pointers where it runs, with the `op` there (§ 1 PLX-Secrets). +// The run is in the run's directory, so that no ansible.cfg of the +// checkout is read, with stdin from /dev/null and the default callback +// printing its results as JSON. A run's output, both streams in one, is +// held until it ends and then written as one block under +// `── - → ──`, so no two runs' lines meet. A +// run that takes more than an hour is stopped and fails. // 6. The summary, one line per stack of the checkout, by name: // ✓ -: deployed | unchanged | would deploy // ✗ -: rolled back: | failed: @@ -67,18 +73,20 @@ // `. The exit code decides over the text: a run whose // last line is a success and whose exit is not 0 is `✗ …: failed: // ansible-playbook exited , though its last line says `. A -// stack whose record sits in a file without a -// plexus_deploy_target is `✗ …: its record in names no -// plexus_deploy_target`, and one without a record `- …: no record in -// ; not deployed`. A stack's failure stops no other's run; +// stack without the environment's file is `- …: no .yaml; +// not deployed`. A stack's failure stops no other's run; // the verb fails when any line is ✗. The directory of the run is removed. // // What a run needs where it runs: Docker with buildx, logged in to every // registry an app's image is in (for the digests); ansible-playbook on the // PATH and the collection plexus.platform where Ansible looks, which brings // community.docker at the version its galaxy.yml names (for any stack with a -// record); and SSH access as the user of each target, whose host key is taken -// on first contact (accept-new) into the known_hosts of whoever runs it. +// file); SSH access to each file's host as the user it names, else the default user the stack playbook's header names, whose host key +// is taken on first contact (accept-new) into the known_hosts of whoever runs +// it; and, where an environment has secrets, `op` on the PATH, signed in or +// with OP_SERVICE_ACCOUNT_TOKEN, which the playbook reads them with. A person +// runs the same verb from a checkout with their own session of the vault. +// In CI (GITHUB_ACTIONS), a run whose files list secrets and that has no OP_SERVICE_ACCOUNT_TOKEN is refused before any host is reached, naming the repository secret DEPLOY_VAULT_TOKEN. // // Every process the verb starts runs in a process group of its own, with a // limit: two minutes for a read (a digest, the syntax check), an hour for a @@ -96,27 +104,19 @@ // run is kept and named, so that each command printed runs as it stands; // without `--check --diff` it is the deploy. // -// plx deploy --environment staging --inventory ../operations/inventory -// plx deploy --inventory operations/inventory # in a job, the environment from the branch -// plx -n deploy -e production --inventory inventory # the playbook's --check --diff -// plx deploy -e staging --inventory inv -- -e stack_wait_timeout=180 +// plx deploy --environment staging +// plx deploy # in a job, the environment from the branch +// plx -n deploy -e production # the playbook's --check --diff +// plx deploy -e staging -- -e stack_wait_timeout=180 import { rmSync } from 'node:fs'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, relative } from 'node:path'; import { type Document, isAlias, isMap, isScalar, isSeq, parseDocument, visit } from 'yaml'; import { COMMIT_SHA_PLACEHOLDER, parseCompose } from './compose.ts'; import type { Context } from './context.ts'; -import { - type DeployLeg, - deployLegs, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, - type Untargeted, -} from './deployTargets.ts'; import { write } from './effects.ts'; +import type { Environment } from './environments.ts'; import { detailOf, ExecError, onInterrupt, render, TimeoutError } from './io.ts'; import { APPS_DIR } from './model.ts'; import { isFile, loadStacks, type Stack, type StackProblem } from './stacks.ts'; @@ -124,8 +124,6 @@ import { UsageError } from './version.ts'; export interface DeployOptions { environment: string; - /** The operations repo's inventory directory, which the records are read from. */ - inventory: string; /** The commit whose images are deployed; default the checkout's HEAD, read only where a stack needs it. */ commit?: string; /** The checkout; default the cwd. */ @@ -144,14 +142,13 @@ export type DeployOutcome = | 'rolled back' | 'failed' | 'interrupted' - | 'no target' - | 'no record'; + | 'no file'; export interface StackOutcome { stack: string; environment: string; - /** The record's plexus_deploy_target, where it has one. */ - target?: string; + /** The `host` of the stack's file for the environment, as written. */ + host?: string; outcome: DeployOutcome; ok: boolean; /** The summary line without its mark: `-: …`. */ @@ -202,24 +199,32 @@ const ANSIBLE_ENV = { ANSIBLE_NOCOLOR: '1', }; +/** One stack's deploy: its name, the environment's file and the `host` that names. */ +interface Leg { + stack: string; + file: string; + host: string; +} + export async function deploy(ctx: Context, options: DeployOptions): Promise { const { environment } = options; const dir = options.dir ?? '.'; const repo = await loadStacks(ctx, dir); refuseProblems(repo.problems); if (repo.stacks.length === 0) throw new Error(await noStack(ctx, repo.root)); - const files = await readInventory(ctx, options.inventory); - const names = repo.stacks.map((s) => s.name); - const { legs, untargeted } = deployLegs( - targetsIn(selectDeployTargets(files), environment), - names, - recordsWithoutTarget(files, environment), + const named = repo.stacks.map((s) => ({ stack: s, file: s.environments.find((e) => e.name === environment) })); + refuseFiles(repo.root, named, environment); + refuseMissingToken(repo.root, named); + refuseTemplated([repo.root, ...named.flatMap(({ file }) => (file ? [file.file] : [])), tmpdir()]); + const legs = named.flatMap(({ stack, file }): Leg[] => + file ? [{ stack: stack.name, file: file.file, host: file.host as string }] : [], ); - const everyStack = (outcomes: StackOutcome[]) => withTheRest(outcomes, untargeted, names, environment); + const names = repo.stacks.map((s) => s.name); + const everyStack = (outcomes: StackOutcome[]) => withTheRest(outcomes, names, environment); if (legs.length === 0) { const outcomes = everyStack([]); report(ctx, outcomes); - if (untargeted.length === 0) ctx.done(`no stack has a record in ${environment}: nothing was deployed`, false); + ctx.done(`no stack has a ${environment}.yaml: nothing was deployed`, false); return { environment, stacks: outcomes, ok: false }; } @@ -232,7 +237,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise repo.stacks.find((s) => s.name === name) as Stack; - const rendered = await Promise.all(legs.map(async (leg) => renderStack(ctx, stackOf(leg.app), commitOf))); + const rendered = await Promise.all(legs.map(async (leg) => renderStack(ctx, stackOf(leg.stack), commitOf))); const unresolved = rendered.flatMap((r) => ('unresolved' in r ? r.unresolved : [])); if (unresolved.length > 0) throw new Error(`${unresolved.join('\n')}\nno stack was deployed`); @@ -245,7 +250,7 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise { - const running = legs.filter((leg) => !ran.some((o) => o.stack === leg.app)); + const running = legs.filter((leg) => !ran.some((o) => o.stack === leg.stack)); if (ctx.dryRun) kept(); else rmSync(scratch, { recursive: true, force: true }); report(ctx, everyStack([...ran, ...running.map((leg) => interrupted(leg, environment, started))])); @@ -270,24 +275,19 @@ export async function deploy(ctx: Context, options: DeployOptions): Promise noTarget(u, environment))]; +function withTheRest(ran: StackOutcome[], names: string[], environment: string): StackOutcome[] { + const outcomes = [...ran]; for (const name of names) if (!outcomes.some((o) => o.stack === name)) outcomes.push({ stack: name, environment, - outcome: 'no record', + outcome: 'no file', ok: true, - line: `${name}-${environment}: no record in ${environment}; not deployed`, + line: `${name}-${environment}: no ${environment}.yaml; not deployed`, }); return outcomes.sort((a, b) => a.stack.localeCompare(b.stack)); } @@ -295,29 +295,20 @@ function withTheRest( /** The summary: one line per stack. */ function report(ctx: Context, outcomes: StackOutcome[]): void { for (const o of outcomes) - if (o.outcome === 'no record') ctx.say(`- ${o.line}`); + if (o.outcome === 'no file') ctx.say(`- ${o.line}`); else ctx.done(o.line, o.ok); } /** A stack whose run was under way, or had not begun, when a signal ended plx. */ -const interrupted = (leg: DeployLeg, environment: string, started: boolean): StackOutcome => ({ - stack: leg.app, +const interrupted = (leg: Leg, environment: string, started: boolean): StackOutcome => ({ + stack: leg.stack, environment, - target: leg.host, + host: leg.host, outcome: 'interrupted', ok: false, line: started - ? `${leg.app}-${environment}: interrupted: plx was stopped while the playbook ran, which may have left the host mid-deploy` - : `${leg.app}-${environment}: interrupted: plx was stopped before the playbook ran; no host was reached`, -}); - -/** A stack whose record names no target: a failure that names the file. */ -const noTarget = ({ app: stack, files }: Untargeted, environment: string): StackOutcome => ({ - stack, - environment, - outcome: 'no target', - ok: false, - line: `${stack}-${environment}: its record in ${files.join(' and ')} names no plexus_deploy_target`, + ? `${leg.stack}-${environment}: interrupted: plx was stopped while the playbook ran, which may have left the host mid-deploy` + : `${leg.stack}-${environment}: interrupted: plx was stopped before the playbook ran; no host was reached`, }); /** @@ -337,6 +328,52 @@ async function noStack(ctx: Context, root: string): Promise { return lines.join('\n'); } +/** + * The problems of every stack's file for the environment, each under the + * file's path in the repo, as one refusal; the files of other environments + * are not asked. + */ +function refuseFiles( + root: string, + named: { stack: Stack; file: Environment | undefined }[], + environment: string, +): void { + const lines = named.flatMap(({ stack, file }) => + (file?.problems ?? []).map((problem) => `${relative(root, stack.dir)}/${problem}`), + ); + if (lines.length > 0) + throw new UsageError(`${lines.join('\n')}\nno stack was deployed into ${environment}; plx doctor reports the same`); +} + +/** + * Ansible templates a path it is given that holds `{{` or `{%`, on the deployer, so that the file it looks for is + * not the one named: a checkout, a file or the scratch directory with either in its path is refused. + */ +function refuseTemplated(paths: string[]): void { + const bad = paths.filter((path) => /\{[{%]/.test(path)); + if (bad.length > 0) + throw new UsageError( + `${bad.join(', ')} holds \`{{\` or \`{%\`, which Ansible would template on this machine, so the playbook would read another path: move the checkout, or set TMPDIR elsewhere; nothing ran`, + ); +} + +/** + * In CI, where the playbook resolves pointers with the repository's secret + * `DEPLOY_VAULT_TOKEN` as OP_SERVICE_ACCOUNT_TOKEN, a run with pointers and + * no token is refused here, naming the secret, since op's own error does not. + * A person at a checkout has a session of their own, and is not asked. + */ +function refuseMissingToken(root: string, named: { stack: Stack; file: Environment | undefined }[]): void { + if (process.env.GITHUB_ACTIONS !== 'true' || process.env.OP_SERVICE_ACCOUNT_TOKEN) return; + const files = named.flatMap(({ stack, file }) => + file && Object.keys(file.secrets).length > 0 ? [`${relative(root, stack.dir)}/${file.name}.yaml`] : [], + ); + if (files.length > 0) + throw new UsageError( + `${files.join(', ')} list secrets, and the job has no token to read them with: the repository secret DEPLOY_VAULT_TOKEN is missing or empty; no host was reached`, + ); +} + /** The loader's problems, but an app no stack uses, as one refusal. */ function refuseProblems(problems: StackProblem[]): void { const blocking = problems.filter((p) => p.code !== 'unused-app'); @@ -493,59 +530,37 @@ async function checkAnsible(ctx: Context, scratch: string, version = '@
[:], as ansible-playbook's arguments. */ -function hostArguments(target: string): string[] { - const match = /^(?:ssh:\/\/)?(?:([^@/]+)@)?(\[[^\]]+\]|[^:/@]+)(?::(\d+))?\/?$/.exec(target); - if (!match) throw new UsageError(`plexus_deploy_target ${target}: not of the form ssh://@
[:]`); - const [, user, address = '', port] = match; - return [ - '-i', - `${address.replace(/^\[(.*)\]$/, '$1')},`, - ...(user ? ['-u', user] : []), - ...(port ? ['-e', `ansible_port=${port}`] : []), - ]; -} - /** One stack's run of the playbook: its block of output, written when it ends, and what it came to. */ async function runStack( ctx: Context, options: DeployOptions, - leg: DeployLeg, + leg: Leg, rendered: string, scratch: string, ): Promise { const { environment } = options; - const stack = leg.app; + const { stack } = leg; const project = `${stack}-${environment}`; const failed = (why: string): StackOutcome => ({ stack, environment, - target: leg.host, + host: leg.host, outcome: 'failed', ok: false, line: `${project}: failed: ${why}`, }); - let args: string[]; - try { - args = hostArguments(leg.host); - } catch (error) { - return failed((error as Error).message); - } const file = join(scratch, `${project}.compose.yaml`); await ctx.stage(write(file, rendered)); - args.push( + const args = [ '--ssh-common-args', '-o StrictHostKeyChecking=accept-new', + // One JSON object: Ansible splits `key=value` words on whitespace, which a path of a checkout may hold. '-e', - `stack_name=${stack}`, - '-e', - `stack_environment=${environment}`, - '-e', - `stack_compose_file=${file}`, + JSON.stringify({ stack_name: stack, stack_environment_file: leg.file, stack_compose_file: file }), ...(ctx.dryRun ? ['--check', '--diff'] : []), ...(options.ansible ?? []), PLAYBOOK, - ); + ]; let output: string; let code = 0; try { @@ -580,7 +595,7 @@ async function runStack( ?.trim(); return failed(`ansible-playbook exited ${code}${why ? `: ${why}` : ''}`); } - return { stack, environment, target: leg.host, outcome: known[1], ok: known[2], line: `${project}: ${result}` }; + return { stack, environment, host: leg.host, outcome: known[1], ok: known[2], line: `${project}: ${result}` }; } /** A full commit hash, SHA-1 or SHA-256, in lower case. */ diff --git a/packages/lib/src/deployTargets.test.ts b/packages/lib/src/deployTargets.test.ts index 39179494..0aeb671d 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -1,142 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { Context } from './context.ts'; -import { - deployLegs, - ENVIRONMENT_BRANCHES, - environmentOf, - parseInventoryFile, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, -} from './deployTargets.ts'; -import { fakeIo } from './testing/fakeIo.ts'; - -const hostA = `--- -plexus_deploy_target: "ssh://deploy@host-a.example:22" -plexus_apps: - - name: beszel - source: plexus-ms-tenant/platform - port: 3011 - - name: 'pocket-id' - port: 3012 -other_key: x -`; - -test('parseInventoryFile reads the target, the app names and their environments, production by default', () => { - assert.deepEqual(parseInventoryFile('inventory/host_vars/host-a.yml', hostA), { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a.example:22', - apps: [ - { app: 'beszel', environment: 'production' }, - { app: 'pocket-id', environment: 'production' }, - ], - }); - assert.deepEqual( - parseInventoryFile( - 's.yml', - 'plexus_deploy_target: ssh://s\nplexus_apps:\n - name: website\n environment: staging\n', - ).apps, - [{ app: 'website', environment: 'staging' }], - ); - assert.deepEqual(parseInventoryFile('g.yml', 'ansible_user: root\n'), { path: 'g.yml', target: undefined, apps: [] }); - assert.deepEqual(parseInventoryFile('e.yml', ''), { path: 'e.yml', target: undefined, apps: [] }); -}); - -const prod = (app: string) => ({ app, environment: 'production' }); - -test('selectDeployTargets maps the deployments of files with a target, sorted, and skips files without one', () => { - const map = selectDeployTargets([ - { path: 'inventory/host_vars/host-b.yml', target: 'ssh://deploy@host-b', apps: [prod('website')] }, - { path: 'inventory/group_vars/all.yml', apps: [prod('beszel')] }, - { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a', - apps: [prod('beszel'), prod('pocket-id')], - }, - ]); - assert.deepEqual(Object.entries(map), [ - ['beszel', { production: 'ssh://deploy@host-a' }], - ['pocket-id', { production: 'ssh://deploy@host-a' }], - ['website', { production: 'ssh://deploy@host-b' }], - ]); -}); - -test('one app, two environments: two records, on one VM or on two, and targetsIn picks one environment', () => { - const map = selectDeployTargets([ - { - path: 'inventory/host_vars/host-a.yml', - target: 'ssh://deploy@host-a', - apps: [prod('website'), { app: 'website', environment: 'staging' }], - }, - { - path: 'inventory/host_vars/host-b.yml', - target: 'ssh://deploy@host-b', - apps: [{ app: 'my-app', environment: 'staging' }], - }, - { path: 'inventory/host_vars/host-c.yml', target: 'ssh://deploy@host-c', apps: [prod('my-app')] }, - ]); - assert.deepEqual(map, { - 'my-app': { production: 'ssh://deploy@host-c', staging: 'ssh://deploy@host-b' }, - website: { production: 'ssh://deploy@host-a', staging: 'ssh://deploy@host-a' }, - }); - assert.deepEqual(targetsIn(map, 'staging'), { 'my-app': 'ssh://deploy@host-b', website: 'ssh://deploy@host-a' }); - assert.deepEqual(targetsIn(map, 'preview'), {}); -}); - -test('an app declared with a target in two files for the same environment is an error that names both', () => { - assert.throws( - () => - selectDeployTargets([ - { path: 'inventory/host_vars/host-a.yml', target: 'a', apps: [prod('beszel')] }, - { path: 'inventory/group_vars/apphosts.yml', target: 'b', apps: [prod('beszel')] }, - ]), - /"beszel" in production.*inventory\/group_vars\/apphosts\.yml and inventory\/host_vars\/host-a\.yml/, - ); -}); - -test('deployLegs: a leg per app of the repo with a target, sorted; the rest are named, and foreign records start nothing', () => { - const targets = { beszel: 'ssh://plexus@host-c', website: 'ssh://plexus@host-a' }; - assert.deepEqual(deployLegs(targets, ['pocket-id', 'beszel']), { - legs: [{ app: 'beszel', host: 'ssh://plexus@host-c' }], - untargeted: [], - without: ['pocket-id'], - }); - assert.deepEqual(deployLegs(targets, []), { legs: [], untargeted: [], without: [] }); -}); - -test('recordsWithoutTarget: the records of an environment in files without a target, unless another file gives one', () => { - const files = [ - { path: 'inventory/host_vars/vm103.yml', apps: [prod('pocket-id'), { app: 'website', environment: 'staging' }] }, - { path: 'inventory/group_vars/all.yml', apps: [prod('pocket-id'), prod('beszel')] }, - { path: 'inventory/host_vars/host-a.yml', target: 'ssh://deploy@host-a', apps: [prod('beszel')] }, - ]; - assert.deepEqual(recordsWithoutTarget(files, 'production'), { - 'pocket-id': ['inventory/group_vars/all.yml', 'inventory/host_vars/vm103.yml'], - }); - assert.deepEqual(recordsWithoutTarget(files, 'staging'), { website: ['inventory/host_vars/vm103.yml'] }); -}); - -test('an app of the repo with a record and no target is neither a leg nor without, with its file', async () => { - const io = fakeIo({ - inv: { - host_vars: { - 'vm103.yml': 'plexus_apps:\n - name: pocket-id\n port: 3012\n', - 'vm104.yml': 'plexus_deploy_target: ssh://plexus@vm104\nplexus_apps: [{name: beszel}]\n', - }, - }, - }); - const files = await readInventory(new Context({}, io), '/inv'); - const { legs, untargeted, without } = deployLegs( - targetsIn(selectDeployTargets(files), 'production'), - ['pocket-id', 'beszel', 'unrecorded'], - recordsWithoutTarget(files, 'production'), - ); - assert.deepEqual(legs, [{ app: 'beszel', host: 'ssh://plexus@vm104' }]); - assert.deepEqual(without, ['unrecorded']); - assert.deepEqual(untargeted, [{ app: 'pocket-id', files: ['/inv/host_vars/vm103.yml'] }]); -}); +import { ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { assert.equal(environmentOf('push', 'main'), 'production'); diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index fb6fc491..5551a7d3 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -1,33 +1,6 @@ -// deploy targets: where the deploy verb reaches each stack an operations -// repo's records name (§ 3 PLX-Platform), read from the repo's inventory. -// -// An inventory file, host_vars for a VM or group_vars for a group, carries -// `plexus_deploy_target` (ssh://@
[:]) and the -// `plexus_apps` records it hosts, each with a `name` and an optional -// `environment` (`production` when absent). `selectDeployTargets` maps every -// deployment, an app in an environment, of a file that names a target to that -// target. A deployment whose file carries no target is left out of the map, -// so the app has no target in that environment, and `plx deploy` deploys -// nothing for it. `deployLegs` takes the names a repo deploys, its stacks' -// (a record's `name` is a stack's), and is stricter: a stack whose record in -// the environment sits in a file without a target is a failure that names -// the stack and the file, since the repo means to deploy it and nothing -// would; a stack with no record in the environment at all gets no leg. The -// same name may have one record per environment, on the same VM or on two; -// the same name in the same environment declared in two files that both name -// a target has no one place to deploy to, and that is an error, never a pick. -// -// `environmentOf` is the one place that says which environment a branch deploys -// into, for `plx` and `plx-ci`. -import { join } from 'node:path'; -import { parse } from 'yaml'; -import type { Context } from './context.ts'; -import { UsageError } from './version.ts'; - -const VARS_DIRS = ['group_vars', 'host_vars']; - -/** The environment a record without one is in. */ -export const DEFAULT_ENVIRONMENT = 'production'; +// The branches that deploy and the environment each deploys into (§ 3 PLX-Delivery): `environmentOf` is the +// one place that says it, for `plx` and `plx-ci`; `ENVIRONMENT_BRANCHES` is the list it applies and a refusal names. +// Where a stack goes is not here: it is the `host` of the stack's environment file (environments.ts). /** * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the @@ -44,148 +17,4 @@ export function environmentOf(event: string, ref: string, given = ''): string { } /** The branches that deploy, each into its environment: the rule `environmentOf` applies, and the list a refusal names. */ -export const ENVIRONMENT_BRANCHES: Readonly> = { main: DEFAULT_ENVIRONMENT, develop: 'staging' }; - -/** App name → environment → deploy target. */ -export type DeployTargets = Record>; - -/** App name → deploy target, for one environment. */ -export type EnvironmentTargets = Record; - -export interface Deployment { - app: string; - environment: string; -} - -export interface InventoryFile { - /** The file's path, for the error that names it. */ - path: string; - target?: string; - apps: Deployment[]; -} - -/** The keys the verb reads from an inventory file's text; anything else is ignored. */ -export function parseInventoryFile(path: string, text: string): InventoryFile { - const data: unknown = parse(text); - const vars = data !== null && typeof data === 'object' ? (data as Record) : {}; - const target = typeof vars.plexus_deploy_target === 'string' ? vars.plexus_deploy_target : undefined; - const records = Array.isArray(vars.plexus_apps) ? vars.plexus_apps : []; - const apps = records.flatMap((r): Deployment[] => { - if (r === null || typeof r !== 'object') return []; - const { name, environment } = r as { name?: unknown; environment?: unknown }; - if (typeof name !== 'string') return []; - return [{ app: name, environment: typeof environment === 'string' ? environment : DEFAULT_ENVIRONMENT }]; - }); - return { path, target, apps }; -} - -/** The map from the files read: deterministic, and loud about a deployment with two targets. */ -export function selectDeployTargets(files: InventoryFile[]): DeployTargets { - const targets: DeployTargets = {}; - const declaredIn: Record = {}; - for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { - if (file.target === undefined) continue; - for (const { app, environment } of file.apps) { - const key = `${app}@${environment}`; - if (key in declaredIn) - throw new Error( - `app "${app}" in ${environment} is declared with a deploy target in both ${declaredIn[key]} and ${file.path}`, - ); - const envs = targets[app] ?? {}; - envs[environment] = file.target; - targets[app] = envs; - declaredIn[key] = file.path; - } - } - return Object.fromEntries( - Object.entries(targets) - .sort(([a], [b]) => a.localeCompare(b)) - .map(([app, envs]) => [app, Object.fromEntries(Object.entries(envs).sort(([a], [b]) => a.localeCompare(b)))]), - ); -} - -/** The flat map of one environment: the apps that have a deployment there, and their targets. */ -export function targetsIn(targets: DeployTargets, environment: string): EnvironmentTargets { - const flat: EnvironmentTargets = {}; - for (const [app, envs] of Object.entries(targets)) { - const target = envs[environment]; - if (target !== undefined) flat[app] = target; - } - return flat; -} - -/** One deploy: an app and where it deploys. */ -export interface DeployLeg { - app: string; - host: string; -} - -/** - * App → the files that hold its record in the environment and name no - * target, for the apps that have no target there from any other file. - */ -export function recordsWithoutTarget(files: InventoryFile[], environment: string): Record { - const targeted = targetsIn(selectDeployTargets(files), environment); - const found: Record = {}; - for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { - if (file.target !== undefined) continue; - for (const d of file.apps) { - if (d.environment !== environment || d.app in targeted) continue; - const paths = found[d.app] ?? []; - if (!paths.includes(file.path)) paths.push(file.path); - found[d.app] = paths; - } - } - return found; -} - -/** An app a repo holds whose record in the environment names no target, and the files that hold the record. */ -export interface Untargeted { - app: string; - files: string[]; -} - -/** - * The deploys of the apps a repo holds itself, in one environment: a leg per - * app with a target there; `untargeted`, the apps with a record there whose - * file names no target, which the caller refuses; and `without`, the apps - * with no record there at all, which have no deployment in it. So the - * inventory's records of apps built elsewhere start nothing here. - */ -export function deployLegs( - targets: EnvironmentTargets, - apps: string[], - recordsWithout: Record = {}, -): { legs: DeployLeg[]; untargeted: Untargeted[]; without: string[] } { - const legs: DeployLeg[] = []; - const untargeted: Untargeted[] = []; - const without: string[] = []; - for (const app of [...apps].sort()) { - const host = targets[app]; - const files = recordsWithout[app]; - if (host !== undefined) legs.push({ app, host }); - else if (files !== undefined) untargeted.push({ app, files }); - else without.push(app); - } - return { legs, untargeted, without }; -} - -/** Read every group_vars and host_vars file under the inventory directory. */ -export async function readInventory(ctx: Context, inventory: string): Promise { - const files: InventoryFile[] = []; - let found = false; - for (const sub of VARS_DIRS) { - const dir = join(inventory, sub); - const entries = await ctx.readDir(dir).catch(() => undefined); - if (entries === undefined) continue; - found = true; - for (const e of entries) { - if (e.directory || !/\.ya?ml$/.test(e.name)) continue; - const path = join(dir, e.name); - files.push(parseInventoryFile(path, await ctx.readFile(path))); - } - } - if (!found && (await ctx.readDir(inventory).catch(() => undefined)) === undefined) - throw new UsageError(`no inventory directory at ${inventory}`); - return files; -} +export const ENVIRONMENT_BRANCHES: Readonly> = { main: 'production', develop: 'staging' }; diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 6758d3b1..645064f5 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -6,6 +6,7 @@ import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli import { type Compose, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts, type StackFacts } from './doctor.ts'; +import type { Environment } from './environments.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import type { MarkerConfig } from './marker.ts'; import { unitsOf } from './model.ts'; @@ -13,6 +14,7 @@ import { overview } from './overview.ts'; import type { MarkerSite } from './sites.ts'; import { type Bundled, strayKeys } from './siteTemplates.ts'; import { parseImage, type RepoStacks, type Stack, type StackProblem } from './stacks.ts'; +import { bundledIndex } from './standardIndex.ts'; import { templatesRoot } from './templatesRoot.ts'; import { type FakeExec, fakeIo, link, type Tree, UNREADABLE } from './testing/fakeIo.ts'; import { UsageError } from './version.ts'; @@ -24,7 +26,7 @@ function namesChecked(text: string): string[] { const name = new RegExp(`\`(${REQUIREMENT_NAME})\``, 'g'); return text .split('\n') - .filter((line) => line.startsWith('`plx doctor` checks')) + .filter((line) => line.startsWith('`plx doctor` checks') || line.startsWith('It checks')) .flatMap((line) => [...line.matchAll(name)].map((m) => m[1] ?? '')); } @@ -79,6 +81,7 @@ const loaded = (over: Partial = {}): Stack => ({ dev: false, apps: [{ service: 'web', app: 'shop' }], pinned: [], + environments: [], ...over, }); const stacksOf = (over: Partial = {}): RepoStacks => ({ @@ -156,6 +159,7 @@ const stack = (profile: string | undefined, over: Partial = {}, devi repoApps: ['shop'], registries: ['ghcr.io/acme'], problems: [], + environments: [], packageJsons: { shop: { packageJson: { scripts: { seed: 'tsx seed.ts' } } } }, ...over, }; @@ -201,6 +205,22 @@ const onStack = (d?: string[]) => stack(profile, { compose: { services }, ...over }, d); +/** An environment file as the loader returns it. */ +const envFile = (name: string, over: Partial = {}): Environment => ({ + name, + file: `/r/stack/${name}.yaml`, + host: '192.0.2.1', + target: { address: '192.0.2.1' }, + hostname: 'shop.example.com', + env: {}, + secrets: {}, + refused: { env: [], secrets: [] }, + invalid: [], + unread: false, + problems: [], + ...over, +}); + const problem = (code: StackProblem['code'], message: string): StackProblem => ({ code, message, stack: 'shop' }); /** For every check: a unit that fails it and nothing else, and what it says. */ @@ -270,7 +290,7 @@ const FAILING: Record Facts; problem: unit: onStack('stateless', { web: web({ env_file: ['.env', '.env.secret'] }) }), problem: /^service `web`: \.env\.secret is loaded, but not marked `required: false`$/, }, - 'PLX-Stack/NoCommittedValues': { + 'PLX-Stack/NoCommittedSecrets': { unit: (deviations = []) => repo({ tracked: ['stack/.env.secret'], @@ -278,6 +298,28 @@ const FAILING: Record Facts; problem: }), problem: /^the source repo tracks `stack\/\.env\.secret`$/, }, + 'PLX-Stack/EnvironmentFile': { + unit: (d) => + stack('stateless', { environments: [envFile('staging', { problems: ['staging.yaml: unknown key `port`'] })] }, d), + problem: /^staging\.yaml: unknown key `port`$/, + }, + 'PLX-Stack/EnvironmentParity': { + unit: (d) => + stack('stateless', { environments: [envFile('production', { env: { A: 'x' } }), envFile('staging')] }, d), + problem: /^staging\.yaml lists no `A` under `env`, which production\.yaml does$/, + }, + 'PLX-Stack/EnvironmentCoverage': { + unit: (d) => + stack( + 'stateless', + { + compose: { ...STATELESS, document: { services: { web: { environment: { A: '${MODE}' } } } } }, + environments: [envFile('staging')], + }, + d, + ), + problem: /^compose\.yaml requires `MODE`, which staging\.yaml does not list under `env`$/, + }, 'PLX-Stack/SinglePort': { unit: onStack('stateless', { web: web({ @@ -290,6 +332,12 @@ const FAILING: Record Facts; problem: unit: onStack('stateless', { web: web(), cache: { image: 'valkey:8', labels: tenant, ports: ['6379'] } }), problem: /^service `cache` publishes `6379` beyond 127\.0\.0\.1$/, }, + 'PLX-Stack/HostnamePort': { + unit: (d) => + stack('stateless', { environments: [envFile('production'), envFile('staging', { hostname: undefined })] }, d), + problem: + /^`hostname` is set in production\.yaml and left out of staging\.yaml; a stack's environment files all set it or none does$/, + }, 'PLX-Stack/Healthcheck': { unit: onStack('stateless', { web: web({ healthcheck: { test: ['NONE'] } }) }), problem: /^service `web` declares no healthcheck with a test of its own$/, @@ -364,6 +412,18 @@ test('a deviation that names no requirement fails, whether a reason is given or ); }); +test('a deviation under the old name of a requirement that was renamed as it moved names the new name', () => { + const old = ['PLX-App', 'NoCommittedValues'].join('/'); + for (const unit of [app({}, [old]), stack('stateless', {}, [old])]) + assert.deepEqual(findings(unit), [ + { + requirement: old, + problem: + 'listed under `deviations`, but no requirement has this name: it moved to `PLX-Stack/NoCommittedSecrets`', + }, + ]); +}); + test('a deviation under the old name of a requirement that moved to PLX-Stack is unknown, and names the new one', () => { // Joined at run time, as above. const moved = (rest: string) => ['PLX-App', rest].join('/'); @@ -468,10 +528,10 @@ test('a stack name that is no project name is a finding of the repo, of no requi assert.deepEqual(findings(repo({ stacks })), [{ problem: 'stacks/Up: `Up` is no Compose project name' }]); }); -test('PLX-Stack/NoCommittedValues: every tracked .env is a finding of the repo, and only a repo with a stack is bound', () => { +test('PLX-Stack/NoCommittedSecrets: every tracked .env is a finding of the repo, and only a repo with a stack is bound', () => { const tracked = ['.env', 'apps/a/.env.secret', 'stack/.env', 'apps/bb/.env.example', 'docs/.envrc']; assert.deepEqual( - named(repo({ tracked }), 'PLX-Stack/NoCommittedValues').map((f) => f.problem), + named(repo({ tracked }), 'PLX-Stack/NoCommittedSecrets').map((f) => f.problem), [ 'the source repo tracks `.env`', 'the source repo tracks `apps/a/.env.secret`', @@ -485,7 +545,7 @@ test('PLX-Stack/NoCommittedValues: every tracked .env is a finding of the repo, stacks: stacksOf({ stacks: [], problems: [{ code: 'no-repo-name', message: 'x' }] }), }); assert.deepEqual( - named(unnamed, 'PLX-Stack/NoCommittedValues').map((f) => f.problem), + named(unnamed, 'PLX-Stack/NoCommittedSecrets').map((f) => f.problem), ['the source repo tracks `stack/.env`'], 'a stack that cannot be named is a stack', ); @@ -1843,9 +1903,9 @@ test('PLX-Stack/AppInStack: of two apps, only the one no stack runs is reported' ); }); -test('PLX-Stack/NoCommittedValues: a tracked .env is reported beside a repo name that is missing', async () => { +test('PLX-Stack/NoCommittedSecrets: a tracked .env is reported beside a repo name that is missing', async () => { const { text } = await webReport((web) => (web['PLEXUS.md'] = MARKER), ['stack/.env']); - assert.deepEqual(text('.', 'PLX-Stack/NoCommittedValues'), ['the source repo tracks `stack/.env`']); + assert.deepEqual(text('.', 'PLX-Stack/NoCommittedSecrets'), ['the source repo tracks `stack/.env`']); assert.equal(text('.').includes(NO_NAME), true); }); @@ -2338,3 +2398,431 @@ test('a root marker that lists no templates is checked for keys where a nested m { problem: UNKNOWN_ROOT('stray') }, ]); }); + +// --- environment files --------------------------------------------------------- + +const FROM_ENV = ` web: + image: ghcr.io/acme/site:\${PLEXUS_TAG:?set} +${SITE_SERVICES} ports: ["127.0.0.1:\${PLEXUS_LOOPBACK_PORT:?set}:3000"] + healthcheck: { test: [CMD, "true"] } + environment: + MODE: \${MODE} + SENTRY: \${SENTRY_DSN:-} + REGION: \${REGION:-eu} + SHA: \${PLEXUS_COMMIT_SHA:-} + PROJECT: \${COMPOSE_PROJECT_NAME} + ESCAPED: $\${NOT_A_VARIABLE} +`; +const PRODUCTION = + 'host: 192.0.2.1\nhostname: shop.example.com\nenv:\n MODE: production\nsecrets:\n API_TOKEN: op://acme/shop/token\n'; +const STAGING = + 'host: 192.0.2.2\nhostname: staging.shop.example.com\nenv:\n MODE: staging\nsecrets:\n API_TOKEN: op://acme/shop-staging/token\n'; + +/** What the stack's doctor unit finds that belongs to no requirement, over a stack with these files. */ +async function environmentFindings(files: Tree) { + const { of } = await webReport((web) => withStack(web, files)); + return of('stack') + .filter((f) => ENVIRONMENT_REQUIREMENTS.includes(f.requirement ?? '')) + .map((f) => f.problem); +} +const ENVIRONMENT_REQUIREMENTS = [ + 'PLX-Stack/EnvironmentFile', + 'PLX-Stack/EnvironmentParity', + 'PLX-Stack/EnvironmentCoverage', + 'PLX-Stack/HostnamePort', +]; +const environmentFiles = (over: Tree = {}): Tree => ({ + 'compose.yaml': compose(FROM_ENV), + 'production.yaml': PRODUCTION, + 'staging.yaml': STAGING, + ...over, +}); + +test('a stack of two environments that list the same names, cover the compose file and agree on the port passes', async () => { + const { of } = await webReport((web) => withStack(web, environmentFiles())); + assert.deepEqual(of('stack'), []); +}); + +test('a stack without environment files is held to none of the environment checks', async () => { + assert.deepEqual(await environmentFindings({ 'compose.yaml': compose(FROM_ENV) }), []); +}); + +test('an environment file with an unknown key, no host, a secret that is no pointer or a name that is no word fails', async () => { + const cases: [string, string, RegExp][] = [ + ['staging', `${STAGING}port: 1\n`, /staging\.yaml: unknown key `port`/], + ['staging', STAGING.replace('host: 192.0.2.2\n', ''), /staging\.yaml: has no `host`/], + [ + 'staging', + STAGING.replace('op://acme/shop-staging/token', 'plain'), + /staging\.yaml: `secrets` `API_TOKEN` is no `op:\/\/` pointer/, + ], + ['pre-prod', STAGING, /pre-prod\.yaml: `pre-prod` is no environment name; a name is one lowercase word/], + ['Staging', STAGING, /Staging\.yaml: `Staging` is no environment name/], + ]; + for (const [name, text, problem] of cases) { + const files = environmentFiles(name === 'staging' ? { 'staging.yaml': text } : { [`${name}.yaml`]: text }); + const found = (await environmentFindings(files)).filter((p) => problem.test(p)); + assert.equal(found.length, 1, `${name}: ${text}`); + } +}); + +test('environment files that list different names under env or under secrets fail, naming the file and the name', async () => { + const env = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(' MODE: staging\n', ' MODE: staging\n EXTRA: x\n') }), + ); + assert.deepEqual(env, ['production.yaml lists no `EXTRA` under `env`, which staging.yaml does'].sort()); + const secrets = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} OTHER: op://acme/shop/other\n` }), + ); + assert.deepEqual(secrets, ['production.yaml lists no `OTHER` under `secrets`, which staging.yaml does'].sort()); +}); + +test("a variable the compose file requires that an environment lists nowhere fails; the platform's variables and defaults are exempt", async () => { + const missing = await environmentFindings( + environmentFiles({ + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + }), + ); + assert.deepEqual(missing.sort(), [ + 'compose.yaml requires `MODE`, which production.yaml does not list under `env`', + 'compose.yaml requires `MODE`, which staging.yaml does not list under `env`', + ]); + const alone = await environmentFindings( + environmentFiles({ + 'compose.yaml': compose(FROM_ENV.replace('${MODE}', '${PLEXUS_TAG}')), + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + }), + ); + assert.deepEqual(alone, []); +}); + +test('a variable the compose file requires and an environment lists only under secrets is not covered: compose fills it from .env', async () => { + const swapped = environmentFiles({ + 'production.yaml': + 'host: 192.0.2.1\nhostname: shop.example.com\nsecrets:\n API_TOKEN: op://a/b/c\n MODE: op://a/b/mode\n', + 'staging.yaml': STAGING, + }); + const found = await environmentFindings(swapped); + assert.ok( + found.includes( + 'compose.yaml requires `MODE`, which production.yaml lists under `secrets` only; a secret is not interpolated: a service reads it from its environment, which `env_file` fills, so interpolate no secret', + ), + found.join('\n'), + ); + assert.ok(!found.some((p) => p.includes('list it under `env`')), 'never to commit a secret as a plain value'); +}); + +test('PLX-Stack/HostnamePort: the environment files of a stack all set hostname or all leave it out, said once', async () => { + const mixed = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('hostname: staging.shop.example.com\n', '') }), + ); + assert.deepEqual(mixed, [ + "`hostname` is set in production.yaml and left out of staging.yaml; a stack's environment files all set it or none does", + ]); + const none = await environmentFindings( + environmentFiles({ 'production.yaml': NO_HOSTNAME(PRODUCTION), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual(none, []); +}); + +/** The variables the compose file requires, as production.yaml is told, over the compose file `text`. */ +async function requiredBy(text: string): Promise { + const found = await environmentFindings(environmentFiles({ 'compose.yaml': text })); + return found.flatMap((p) => /^compose\.yaml requires `(\w+)`, which production\.yaml/.exec(p)?.[1] ?? []).sort(); +} +const ENV_ONLY = FROM_ENV.replace(/ {6}MODE: .*\n/, ''); + +test('every value of the compose file is read for the variables it requires, as compose reads it: top-level volumes, networks, x- fields and lists, not keys', async () => { + const extra = ` extra: + image: postgres:16 + command: ["run", "\${IN_LIST}"] + environment: + BARE: $BARE_VARIABLE + labels: + "\${IN_KEY}": value +x-note: \${IN_X_FIELD} +volumes: + data: + name: \${IN_VOLUME} +networks: + back: + name: \${IN_NETWORK} +`; + const needed = await requiredBy(compose(ENV_ONLY.replace(/ {4}environment:\n$/, '')) + extra); + assert.deepEqual(needed, ['BARE_VARIABLE', 'IN_LIST', 'IN_NETWORK', 'IN_VOLUME', 'IN_X_FIELD']); +}); + +test('a variable with a default or an alternative is not required, in any of the four forms; one with an error message is', async () => { + const extra = ` extra: + image: postgres:16 + environment: + A: \${DEFAULT_DASH-x} + B: \${DEFAULT_COLON_DASH:-x} + C: \${ALT_PLUS+x} + D: \${ALT_COLON_PLUS:+x} + E: \${MESSAGE:?say} + F: \${MESSAGE_PLAIN?say} + G: \${PLAIN} +`; + const needed = await requiredBy(compose(ENV_ONLY.replace(/ {4}environment:\n$/, '')) + extra); + assert.deepEqual(needed, ['MESSAGE', 'MESSAGE_PLAIN', 'PLAIN']); +}); + +test('one bad value in an environment file is one finding: no `lists no` line follows from it', async () => { + const cases: [string, string, string][] = [ + ['an empty file', '', 'staging.yaml: is empty; it needs a `host`'], + ['no YAML', 'host: [\n', 'staging.yaml: not valid YAML: '], + ['no map', '- a\n', 'staging.yaml: is not a map of `host`, `hostname`, `env` and `secrets`'], + [ + 'an env value that is no string', + STAGING.replace('MODE: staging', 'MODE: 3'), + 'staging.yaml: `env` `MODE` is not a string; quote it', + ], + [ + 'a null env value', + STAGING.replace('MODE: staging', 'MODE:'), + 'staging.yaml: `env` `MODE` is not a string; quote it', + ], + [ + 'a secret that is no string', + STAGING.replace('op://acme/shop-staging/token', '3'), + 'staging.yaml: `secrets` `API_TOKEN` is no `op://` pointer', + ], + ]; + for (const [what, text, expected] of cases) { + const found = await environmentFindings(environmentFiles({ 'staging.yaml': text })); + assert.equal(found.length, 1, `${what}: ${found.join('\n')}`); + assert.ok(found[0]?.startsWith(expected), `${what}: ${found[0]}`); + } +}); + +test('a name under both env and secrets, and a name the platform supplies, are findings of the file', async () => { + const both = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} MODE: op://acme/shop/mode\n` }), + ); + assert.ok(both.includes('staging.yaml: `MODE` is listed under both `env` and `secrets`'), both.join('\n')); + const platform = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_TAG: x\n') }), + ); + assert.ok( + platform.includes('staging.yaml: `PLEXUS_TAG` is supplied by the platform; remove it'), + platform.join('\n'), + ); +}); + +test('a `.yml` file in a stack directory is a finding of the stack', async () => { + const found = await environmentFindings(environmentFiles({ 'preview.yml': 'host: 192.0.2.3\n' })); + assert.deepEqual(found, ['preview.yml: name it preview.yaml']); +}); + +test('an environment that could not be read is left out of the comparisons with the others', async () => { + const found = await environmentFindings(environmentFiles({ 'staging.yaml': '' })); + assert.equal(found.length, 1, found.join('\n')); +}); + +/** The stack's findings over a compose file and environment files. */ +async function stackFindings(files: Tree) { + const { of } = await webReport((web) => withStack(web, files)); + return of('stack'); +} +const NO_PORT = FROM_ENV.replace(/ {4}ports: .*\n/, ''); +const NO_HOSTNAME = (text: string) => text.replace(/hostname: .*\n/, ''); + +test('PLX-Stack/SinglePort: with environment files that all lack a hostname a stack binds no port and passes, once', async () => { + const found = await stackFindings( + environmentFiles({ + 'compose.yaml': compose(NO_PORT), + 'production.yaml': NO_HOSTNAME(PRODUCTION), + 'staging.yaml': NO_HOSTNAME(STAGING), + }), + ); + assert.deepEqual(found, []); +}); + +test('PLX-Stack/SinglePort: without environment files a stack still binds exactly one port', async () => { + const found = await stackFindings({ 'compose.yaml': compose(NO_PORT) }); + assert.deepEqual( + found.map((f) => [f.requirement, f.problem]), + [['PLX-Stack/SinglePort', 'no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']], + ); +}); + +test('PLX-Stack/SinglePort: a stack whose environments have a hostname and binds no port fails once, by SinglePort alone', async () => { + const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(NO_PORT) })); + assert.deepEqual( + found.map((f) => [f.requirement, f.problem]), + [ + [ + 'PLX-Stack/SinglePort', + 'no service binds `PLEXUS_LOOPBACK_PORT`, which the environments with a `hostname` need', + ], + ], + ); +}); + +test('PLX-Stack/SinglePort: a stack whose environments have no hostname and binds the port fails once, by SinglePort alone', async () => { + const found = await stackFindings( + environmentFiles({ 'production.yaml': NO_HOSTNAME(PRODUCTION), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual( + found.map((f) => [f.requirement, f.problem]), + [ + [ + 'PLX-Stack/SinglePort', + 'service `web` binds `PLEXUS_LOOPBACK_PORT`, but no environment of the stack has a `hostname`', + ], + ], + ); +}); + +test('PLX-Stack/SinglePort: with environment files a stack that binds two port mappings fails once, by SinglePort', async () => { + const twice = FROM_ENV.replace(/( {4}ports: )(.*)\n/, '$1[$2, "127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set}:3001"]\n'); + const found = await stackFindings(environmentFiles({ 'compose.yaml': compose(twice) })); + const single = found.filter((f) => f.requirement === 'PLX-Stack/SinglePort'); + assert.equal(single.length, 1, found.map((f) => f.problem).join('\n')); + assert.equal(found.length, 1); +}); + +test('a name the platform supplies, or listed under both maps, is not also reported as missing from the other files', async () => { + const platform = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_TAG: x\n') }), + ); + assert.deepEqual(platform, ['staging.yaml: `PLEXUS_TAG` is supplied by the platform; remove it']); + const both = await environmentFindings( + environmentFiles({ 'staging.yaml': `${STAGING} MODE: op://acme/shop/mode\n` }), + ); + assert.deepEqual(both, ['staging.yaml: `MODE` is listed under both `env` and `secrets`']); +}); + +test('a malformed host is one finding of the file', async () => { + const found = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('192.0.2.2', 'ssh://192.0.2.2') }), + ); + assert.equal(found.length, 1); + assert.match(found[0] ?? '', /^staging\.yaml: `host` is not `\[user@\]address\[:port\]`/); +}); + +test('the findings on environment files cite their requirements, and a deviation of the stack silences each', async () => { + const cases: [string, Tree, string][] = [ + ['PLX-Stack/EnvironmentFile', environmentFiles({ 'staging.yaml': `${STAGING}port: 1\n` }), 'unknown key'], + ['PLX-Stack/EnvironmentFile', environmentFiles({ 'preview.yml': 'host: 192.0.2.3\n' }), 'name it preview.yaml'], + [ + 'PLX-Stack/EnvironmentFile', + environmentFiles({ 'staging.yaml': STAGING.replace('192.0.2.2', 'ssh://x') }), + '`host` is not', + ], + [ + 'PLX-Stack/EnvironmentParity', + environmentFiles({ 'staging.yaml': STAGING.replace(' MODE: staging\n', '') }), + 'lists no `MODE`', + ], + [ + 'PLX-Stack/EnvironmentCoverage', + environmentFiles({ + 'staging.yaml': STAGING.replace(' MODE: staging\n', ''), + 'production.yaml': PRODUCTION.replace(' MODE: production\n', ''), + }), + 'requires `MODE`', + ], + [ + 'PLX-Stack/HostnamePort', + environmentFiles({ 'staging.yaml': NO_HOSTNAME(STAGING) }), + '`hostname` is set in production.yaml', + ], + ]; + for (const [name, files, text] of cases) { + const { of } = await webReport((web) => withStack(web, files)); + const found = of('stack').filter((f) => f.requirement === name); + assert.ok( + found.some((f) => f.problem.includes(text)), + `${name}: ${text}`, + ); + const silenced = await webReport((web) => { + withStack(web, files); + (web.stack as Tree)['PLEXUS.md'] = + `---\nprofile: stateless\ndeviations: [${name}]\n---\n\n- \`${name}\`: because.\n`; + }); + assert.deepEqual( + silenced.of('stack').filter((f) => f.requirement === name && !f.problem.startsWith('listed under')), + [], + name, + ); + } +}); + +test('one fault, one finding: env that is no map, an empty hostname, and hostnames that differ', async () => { + const noMap = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/env:\n {2}MODE: staging\n/, 'env: [a]\n') }), + ); + assert.equal(noMap.length, 1, noMap.join('\n')); + assert.match(noMap[0] ?? '', /^staging\.yaml: `env` is not a map/); + const noSecretsMap = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/secrets:\n.*\n/, 'secrets: x\n') }), + ); + assert.equal(noSecretsMap.length, 1, noSecretsMap.join('\n')); + const empty = await stackFindings( + environmentFiles({ 'staging.yaml': STAGING.replace(/hostname: .*\n/, 'hostname: ""\n') }), + ); + assert.deepEqual( + empty.map((f) => [f.requirement, f.problem]), + [['PLX-Stack/EnvironmentFile', 'staging.yaml: `hostname` is not a non-empty string']], + ); + const mixed = await stackFindings( + environmentFiles({ 'compose.yaml': compose(NO_PORT), 'staging.yaml': NO_HOSTNAME(STAGING) }), + ); + assert.deepEqual( + mixed.map((f) => f.requirement), + ['PLX-Stack/HostnamePort'], + ); +}); + +test('a cyclic alias in compose.yaml is reported as a compose file that cannot be read, and doctor survives it', async () => { + const { of } = await webReport((web) => + withStack(web, { + 'compose.yaml': `x-a: &a\n self: *a\nservices:\n web:\n image: ghcr.io/acme/site:\${PLEXUS_TAG:?set}\n labels: *a\n`, + }), + ); + const found = of('stack').filter((f) => f.requirement === 'PLX-Stack/Compose'); + assert.equal(found.length, 1); + assert.match(found[0]?.problem ?? '', /aliases form a cycle/); +}); + +test('a deviation under a requirement the standard removed is told so, and the index no longer names it', () => { + // Joined at run time, as a removed name must not read as a citation of the compendium's. + const removed = [['PLX-Stack', 'PathPrefix'].join('/'), ['PLX-Ingress', 'PrefixInRecord'].join('/')]; + for (const name of removed) { + assert.equal(bundledIndex().citable.includes(name), false, `${name} is in the index`); + // Also with an index that still names it, as an earlier version's does. + for (const index of [KNOWN, new Set([...KNOWN, name])]) + assert.deepEqual(diagnose([stack('stateless', {}, [name])], index).units[0]?.findings, [ + { + requirement: name, + problem: + 'listed under `deviations`, but this requirement was removed from the standard: the deviation can go', + }, + ]); + } +}); + +test('a deviation under a name released in an earlier version is told what it is now', () => { + // Joined at run time, as the old name must not read as a citation of the compendium's. + const old = ['PLX-Stack', 'NoCommittedValues'].join('/'); + const stale = new Set([...KNOWN, old]); + const found = diagnose([stack('stateless', {}, [old])], stale).units[0]?.findings; + assert.deepEqual(found, [ + { + requirement: old, + problem: 'listed under `deviations`, but no requirement has this name: it is now `PLX-Stack/NoCommittedSecrets`', + }, + ]); + // The old name silences nothing: the check of the new name still runs. + const tracked = repo({ + tracked: ['stack/.env'], + marker: { declaration: { deviations: [old], body: reasoned([old]) } }, + }); + assert.ok( + diagnose([tracked], stale).units[0]?.findings.some((f) => f.requirement === 'PLX-Stack/NoCommittedSecrets'), + ); +}); diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index a22e5fd9..24ac3f01 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -42,6 +42,11 @@ // one per file, whatever the marker lists; it names no requirement, and // nothing excludes a file from it. // +// What a stack's environment files meet is four requirements (`environmentFile`, +// `environmentParity`, `environmentCoverage`, `hostnamePort`) and the +// stack's port the one of PLX-Stack/SinglePort, in its three cases; a stack +// without environment files meets the four as it is. +// // Also of no requirement, and no deviation silences it: a repo with `stack/` // whose root marker has no `repo` key, which names it (stacks.ts, `no-repo-name`). // @@ -102,6 +107,7 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; +import { type Environment, PLATFORM_VARIABLES, requiredVariables } from './environments.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, parseMarker, reasonGiven } from './marker.ts'; @@ -202,6 +208,8 @@ export interface StackFacts { registries: string[]; /** The loader's problems with this stack. */ problems: StackProblem[]; + /** Its environments, as the loader reads them. */ + environments: Environment[]; /** The `package.json` of each app the stack runs, by app name; an app without one has no entry. */ packageJsons: Record; } @@ -354,7 +362,7 @@ function imageRef(compose: Compose, stack: StackFacts): string[] { } /** A tracked `.env` or `.env.secret` of a repo that has a stack. */ -function noCommittedValues(repo: RepoFacts): string[] { +function noCommittedSecrets(repo: RepoFacts): string[] { // A stack the loader could not name (`no-repo-name`) is a stack all the same. const unnamed = repo.stacks?.problems.some((p) => p.code === 'no-repo-name'); if ((repo.stacks?.stacks.length ?? 0) === 0 && !unnamed) return []; @@ -363,12 +371,35 @@ function noCommittedValues(repo: RepoFacts): string[] { .map((f) => `the source repo tracks \`${f}\``); } -function singlePort(compose: Compose): string[] { +/** + * The stack's port, in three cases. A stack whose environments have a + * `hostname` binds the loopback variable in exactly one port mapping; one + * whose environments have none binds it in none; one without environment + * files binds it in exactly one. An environment that could not be read has no + * known hostname and is left out; where none could be read, the stack is held + * to the first case, and where the hostnames differ, `hostnamePort` reports it + * and this check says nothing of the stack. + */ +function singlePort(compose: Compose, stack: StackFacts): string[] { const binders = Object.entries(compose.services) .map(([name, service]) => [name, portsOf(service).filter(bindsLoopbackVar).length] as const) .filter(([, bound]) => bound > 0); const mappings = binders.reduce((sum, [, bound]) => sum + bound, 0); - if (binders.length === 0) return ['no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port']; + const read = hostnameKnown(stack); + const hostnames = read.filter((e) => e.hostname !== undefined).length; + if (hostnames > 0 && hostnames < read.length) return []; + if (read.length > 0 && hostnames === 0) { + const [first] = binders; + return first + ? [`service \`${first[0]}\` binds \`PLEXUS_LOOPBACK_PORT\`, but no environment of the stack has a \`hostname\``] + : []; + } + if (binders.length === 0) + return [ + hostnames > 0 + ? 'no service binds `PLEXUS_LOOPBACK_PORT`, which the environments with a `hostname` need' + : 'no service binds `PLEXUS_LOOPBACK_PORT`: the stack serves no port', + ]; if (mappings === 1) return []; const names = binders.map(([name]) => `\`${name}\``).join(', '); const who = binders.length === 1 ? `the service ${names} binds` : `the services ${names} bind`; @@ -491,15 +522,100 @@ export const CHECKS: Readonly> 'PLX-Stack/ImageRef': { binds: 'stack', check: onCompose(imageRef) }, 'PLX-Stack/TenantLabel': { binds: 'stack', check: onCompose(tenantLabel) }, 'PLX-Stack/EnvFileLoad': { binds: 'stack', check: onCompose(envFileLoad) }, - 'PLX-Stack/NoCommittedValues': { binds: 'repo', check: noCommittedValues }, + 'PLX-Stack/NoCommittedSecrets': { binds: 'repo', check: noCommittedSecrets }, + 'PLX-Stack/EnvironmentFile': { binds: 'stack', check: environmentFile }, + 'PLX-Stack/EnvironmentParity': { binds: 'stack', check: environmentParity }, + 'PLX-Stack/EnvironmentCoverage': { binds: 'stack', check: onCompose(environmentCoverage) }, 'PLX-Stack/SinglePort': { binds: 'stack', check: onCompose(singlePort) }, 'PLX-Stack/LoopbackPort': { binds: 'stack', check: onCompose(loopbackPort) }, + 'PLX-Stack/HostnamePort': { binds: 'stack', check: hostnamePort }, 'PLX-Stack/Healthcheck': { binds: 'stack', check: onCompose(healthcheck) }, 'PLX-Stack/Stateless/NoState': { binds: 'stack', profile: 'stateless', check: onCompose(noState) }, 'PLX-Stack/Stateful/MigrateService': { binds: 'stack', profile: 'stateful', check: onCompose(migrateService) }, 'PLX-Stack/Stateful/Seed': { binds: 'stack', profile: 'stateful', check: seed }, }; +/** + * PLX-Stack/EnvironmentFile: each environment file is usable, its keys, the + * form of `host`, strings under `env`, pointers under `secrets`, its name, no + * name in both maps and none the platform supplies (the loader's `problems`, + * one line per bad value), and no `.yml` stands for one. + */ +function environmentFile(stack: StackFacts): string[] { + return [ + ...stack.problems.filter((p) => p.code === 'bad-environment-file').map((p) => p.message), + ...stack.environments.flatMap((e) => e.problems), + ]; +} + +/** The names an environment lists under `env` or `secrets`, whose value may have been refused. */ +const listed = (e: Environment, key: 'env' | 'secrets') => [...Object.keys(e[key]), ...e.refused[key]]; + +/** The environments of which something is known: a file that could not be read at all is left out of every comparison, and a part of one whose value is unusable (`invalid`) out of the comparison of that part. */ +const readEnvironments = (stack: StackFacts): Environment[] => stack.environments.filter((e) => !e.unread); + +/** + * PLX-Stack/EnvironmentParity: the files list the same names under `env` and + * under `secrets`, one line for each name an environment lacks, naming the + * first that has it. A name the platform supplies, or one listed under both + * maps, has its finding in EnvironmentFile already. + */ +function environmentParity(stack: StackFacts): string[] { + const read = readEnvironments(stack); + const doubled = new Set([ + ...PLATFORM_VARIABLES, + ...read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n))), + ]); + const problems: string[] = []; + for (const key of ['env', 'secrets'] as const) { + const of = read.filter((e) => !e.invalid.includes(key)); + for (const name of new Set(of.flatMap((e) => listed(e, key)))) { + const holder = of.find((e) => listed(e, key).includes(name)); + for (const e of of) + if (holder && !doubled.has(name) && !listed(e, key).includes(name)) + problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); + } + } + return problems; +} + +/** + * PLX-Stack/EnvironmentCoverage: every variable the compose file interpolates + * in a value (`requiredVariables`, keys not read), but for the platform's + * (`PLATFORM_VARIABLES`), is listed under `env` of each environment. Compose + * fills `${…}` from `.env` alone, so a name only under `secrets` is not + * covered. + */ +function environmentCoverage(compose: Compose, stack: StackFacts): string[] { + return requiredVariables(compose) + .filter((v) => !PLATFORM_VARIABLES.includes(v)) + .flatMap((variable) => + readEnvironments(stack) + .filter((e) => !e.invalid.includes('env') && !listed(e, 'env').includes(variable)) + .map((e) => + variable in e.secrets + ? `compose.yaml requires \`${variable}\`, which ${e.name}.yaml lists under \`secrets\` only; a secret is not interpolated: a service reads it from its environment, which \`env_file\` fills, so interpolate no secret` + : `compose.yaml requires \`${variable}\`, which ${e.name}.yaml does not list under \`env\``, + ), + ); +} + +/** The environments whose `hostname`, set or left out, is known: its value is usable. */ +const hostnameKnown = (stack: StackFacts): Environment[] => + readEnvironments(stack).filter((e) => !e.invalid.includes('hostname')); + +/** PLX-Stack/HostnamePort: the files all set `hostname` or all leave it out. */ +function hostnamePort(stack: StackFacts): string[] { + const read = hostnameKnown(stack); + const set = read.filter((e) => e.hostname !== undefined).map((e) => `${e.name}.yaml`); + const out = read.filter((e) => e.hostname === undefined).map((e) => `${e.name}.yaml`); + return set.length > 0 && out.length > 0 + ? [ + `\`hostname\` is set in ${set.join(', ')} and left out of ${out.join(', ')}; a stack's environment files all set it or none does`, + ] + : []; +} + /** * What the markers as configuration must meet (sites.ts): the root's `version` * is the `plx` pin's, no other marker has one, and no key is answered in two @@ -567,12 +683,10 @@ const MOVED_TO_STACK = new Set([ 'ComposeDelivery', 'EnvFiles', 'EnvFileLoad', - 'NoCommittedValues', 'ReservedPrefix', 'ImageRef', 'SinglePort', 'LoopbackPort', - 'PathPrefix', 'Healthcheck', 'Stateless/NoState', 'Stateful/BackupLabel', @@ -586,9 +700,33 @@ const MOVED_TO_STACK = new Set([ 'Stateful/Seed', ]); +/** What a requirement that was renamed as it moved is called now. */ +const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; + +/** Requirements the standard removed, by module and suffix: a deviation under one of them can go, whatever an index of an earlier version says. */ +const REMOVED: Readonly>> = { + 'PLX-Stack': new Set(['PathPrefix']), + 'PLX-Ingress': new Set(['PrefixInRecord']), +}; + +/** Whether the standard removed the requirement `name`. */ +function removed(name: string): boolean { + const slash = name.indexOf('/'); + const module = name.slice(0, slash); + return slash > 0 && Object.hasOwn(REMOVED, module) && (REMOVED[module]?.has(name.slice(slash + 1)) ?? false); +} + +/** What a released `PLX-Stack/…` name is called now, where it was renamed; the `PLX-App/…` form is `movedTo`'s. */ +function renamedInStack(name: string): string | undefined { + const rest = name.startsWith('PLX-Stack/') ? name.slice('PLX-Stack/'.length) : undefined; + return rest !== undefined && rest in RENAMED_ON_MOVE ? `PLX-Stack/${RENAMED_ON_MOVE[rest]}` : undefined; +} + function movedTo(name: string): string | undefined { const rest = name.startsWith('PLX-App/') ? name.slice('PLX-App/'.length) : undefined; - return rest !== undefined && MOVED_TO_STACK.has(rest) ? `PLX-Stack/${rest}` : undefined; + if (rest === undefined) return undefined; + if (rest in RENAMED_ON_MOVE) return `PLX-Stack/${RENAMED_ON_MOVE[rest]}`; + return MOVED_TO_STACK.has(rest) ? `PLX-Stack/${rest}` : undefined; } function versionOfRoot(repo: RepoFacts): string[] { @@ -668,6 +806,16 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it moved to \`${moved}\``, }); + else if (renamedInStack(name)) + findings.push({ + requirement: name, + problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, + }); + else if (removed(name)) + findings.push({ + requirement: name, + problem: 'listed under `deviations`, but this requirement was removed from the standard: the deviation can go', + }); else if (!known.has(name)) findings.push({ requirement: name, problem: 'listed under `deviations`, but no requirement has this name' }); else if (!reasonGiven(declaration?.body ?? '', name)) @@ -891,6 +1039,7 @@ async function readStack(ctx: Context, repo: RepoFacts, stack: Stack, base: stri repoApps: loaded?.apps ?? [], registries: loaded?.prefixes ?? [], problems: (loaded?.problems ?? []).filter((p) => p.stack === stack.name), + environments: stack.environments, packageJsons, }; } diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts new file mode 100644 index 00000000..85dc613b --- /dev/null +++ b/packages/lib/src/environments.ts @@ -0,0 +1,253 @@ +// The environments of a stack, and the variables the platform supplies: what +// the loader (stacks.ts) reads of a stack's directory beyond its compose file, +// and the one list `plx doctor` holds environment files and compose files +// against. The stack playbook and the deploy verb will read environment files +// through the loader and take the list from here; nothing outside `lib` reads +// it yet. +// +// An environment is one stack on one host with its full configuration, and its +// configuration is a file in the stack's directory named after it: +// `production.yaml` is the environment `production`. The loader (stacks.ts, +// which knows the names of the compose files and has read the directory) +// hands over the file names; a name is one lowercase word, letters only, and +// no name has a meaning: no code compares one with a literal. The file is a +// YAML map with exactly four keys: +// host the machine as an SSH destination, `[user@]address[:port]`, as in +// `deploy@192.0.2.10:2222`; required. As checked: the user, where +// given, starts with a letter, a digit or `_` and holds letters, +// digits, `.`, `_` and `-` (so never an ssh option); the address is +// a DNS name (labels of letters, digits and `-`, none starting or +// ending with `-`, separated by single dots, no trailing dot), or an +// IPv4 address (`net.isIP`; a name with the shape of one that is +// none is refused), or an IPv6 address (`net.isIP`), bare, or in +// brackets, which it needs where a port follows and which hold +// nothing else; the port is a number from 1 to 65535. It is +// returned as written (`host`) and parsed (`target`: the address +// without brackets, the user and the port where given, absent where +// not; the default user and port are the connecting side's to name, +// not this file's) +// hostname the public name the proxy serves, a non-empty string; optional, +// and without it the environment gets no loopback port and no route +// env a map of names to strings; absent reads as empty. A value that +// is no string (a number, a boolean, null, a map, a list) is +// refused, not converted: the stack playbook reads the same file +// with another YAML parser, and only a string reads the same in both +// secrets a map of names to `op://` pointers, strings; absent reads as empty; +// a string that is no pointer is returned and is a problem +// No name stands in both maps, and none is one `PLATFORM_VARIABLES` lists: the +// platform supplies those, so no file does. +// `readEnvironments` returns one `Environment` per file in the order of their +// names, and never throws: whatever makes a file unusable is a line of its +// `problems` that names the file, one line per bad value, and the values it +// could read are returned all the same, so that every problem is found in one +// run. A name whose value was refused is in `refused`, so that it still counts +// as listed and its own problem is the only one. A file that could not be +// read at all (unreadable, empty, not YAML, no map) is `unread`: nothing of +// it is known, and it is held to no comparison. +// +// `requiredVariables` lists the variables a compose file needs its +// environment to give: those it interpolates without a default (`${NAME}`, +// `$NAME`, `${NAME:?message}`, `${NAME?message}`), not the ones with a +// default or an alternative (`${NAME:-x}`, `${NAME-x}`, `${NAME:+x}`, +// `${NAME+x}`); `$$` is compose's escape and no variable. It reads every +// value of the document, as compose does (services, top-level `volumes` and +// `networks`, `x-` fields, lists), and no key. Compose fills them from `.env`, +// that is from `env`, and never from `.env.secret`. +import { isIP } from 'node:net'; +import { join } from 'node:path'; +import { parse } from 'yaml'; +import { type Compose, isMapping, yamlError } from './compose.ts'; +import type { Context } from './context.ts'; + +/** The variables the platform and the deployer supply to a stack, which no environment file lists: the project name and the loopback port in `.env`, the tag and the commit at deploy time. */ +export const PLATFORM_VARIABLES: readonly string[] = [ + 'COMPOSE_PROJECT_NAME', + 'PLEXUS_LOOPBACK_PORT', + 'PLEXUS_TAG', + 'PLEXUS_COMMIT_SHA', +]; + +/** An SSH destination, parsed. */ +export interface SshTarget { + address: string; + user?: string; + port?: number; +} + +/** The form of `host`, shown in the finding. */ +const HOST_FORM = '`[user@]address[:port]`, as in `deploy@192.0.2.10:2222`'; + +/** What a user name is: it never starts with `-`, which ssh would read as an option. */ +const USER = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/; + +/** What a DNS label is: letters, digits and `-`, not starting or ending with `-`. */ +const LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/; + +/** The address of a `host` that is none of IPv6: an IPv4 address (`net.isIP`) or a DNS name, and a name never has the shape of an IPv4 address. */ +function addressProblem(address: string): string | undefined { + if (isIP(address) === 4) return undefined; + if (/^[0-9.]+$/.test(address)) return 'it has the shape of an IPv4 address and is none'; + return address.split('.').every((label) => LABEL.test(label)) ? undefined : 'it is no DNS name, IPv4 or IPv6 address'; +} + +/** A `host` parsed, or why it is no SSH destination. The grammar is in the header. */ +export function parseHost(host: string): SshTarget | string { + const at = host.lastIndexOf('@'); + const user = at < 0 ? undefined : host.slice(0, at); + const rest = host.slice(at + 1); + if (user !== undefined && !USER.test(user)) return 'the user is no user name'; + let address = rest; + let port: string | undefined; + if (rest.startsWith('[')) { + const close = rest.indexOf(']'); + if (close < 0) return 'a bracket is not closed'; + address = rest.slice(1, close); + const after = rest.slice(close + 1); + if (after !== '' && !after.startsWith(':')) return 'only a port may follow the closing bracket'; + if (after !== '') port = after.slice(1); + if (isIP(address) !== 6) return 'what the brackets hold is no IPv6 address'; + } else if (rest.split(':').length > 2) { + if (isIP(rest) !== 6) return 'it is no IPv6 address, which is bracketed where a port follows'; + } else { + [address = '', port] = rest.split(':'); + const problem = addressProblem(address); + if (problem) return `the address ${problem}`; + } + if (port !== undefined && !(/^[0-9]+$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) + return 'the port is not a number from 1 to 65535'; + return { address, ...(user === undefined ? {} : { user }), ...(port === undefined ? {} : { port: Number(port) }) }; +} + +/** One stack on one host, as its file states it. */ +export interface Environment { + /** The file's name without `.yaml`. */ + name: string; + /** The file, absolute. */ + file: string; + /** The `host` as written; absent where there is none or it is malformed. */ + host?: string; + /** The `host` parsed: the user and the port only where it gives them. */ + target?: SshTarget; + hostname?: string; + env: Record; + /** Names to `op://` pointers. */ + secrets: Record; + /** The names under `env` and under `secrets` whose value was refused: listed, with no value. */ + refused: { env: string[]; secrets: string[] }; + /** The parts of the file whose value is unusable as a whole (`hostname` empty or no string, `env` or `secrets` no map): nothing is known of them, so no comparison reads them. */ + invalid: ('hostname' | 'env' | 'secrets')[]; + /** The file could not be read as a map at all. */ + unread: boolean; + /** What makes the file unusable, one line each, each naming the file. */ + problems: string[]; +} + +/** What an environment's name is: one lowercase word. */ +const ENVIRONMENT_NAME = /^[a-z]+$/; + +const KEYS = ['host', 'hostname', 'env', 'secrets']; + +/** The environments in the files `names` (`.yaml`) of the directory `dir`, by name. */ +export async function readEnvironments(ctx: Context, dir: string, names: string[]): Promise { + const environments: Environment[] = []; + for (const file of [...names].sort()) environments.push(await readEnvironment(ctx, dir, file)); + return environments; +} + +async function readEnvironment(ctx: Context, dir: string, label: string): Promise { + const name = label.slice(0, -'.yaml'.length); + const environment: Environment = { + name, + file: join(dir, label), + env: {}, + secrets: {}, + refused: { env: [], secrets: [] }, + invalid: [], + unread: false, + problems: [], + }; + const problem = (text: string) => environment.problems.push(`${label}: ${text}`); + if (!ENVIRONMENT_NAME.test(name)) + problem(`\`${name}\` is no environment name; a name is one lowercase word (letters only, no \`-\`)`); + const unread = (text: string): Environment => { + problem(text); + environment.unread = true; + return environment; + }; + let text: string; + try { + text = await ctx.readFile(environment.file); + } catch (error) { + return unread(`could not be read: ${(error as Error).message}`); + } + let doc: unknown; + try { + doc = parse(text); + } catch (error) { + return unread(yamlError(error)); + } + if (doc === null || doc === undefined) return unread('is empty; it needs a `host`'); + if (!isMapping(doc)) return unread('is not a map of `host`, `hostname`, `env` and `secrets`'); + for (const key of Object.keys(doc).filter((k) => !KEYS.includes(k))) + problem(`unknown key \`${key}\`; the keys are ${KEYS.map((k) => `\`${k}\``).join(', ')}`); + if (doc.host === undefined) problem("has no `host`, the machine's address"); + if (doc.host !== undefined) { + const target = typeof doc.host === 'string' && doc.host !== '' ? parseHost(doc.host) : undefined; + if (target === undefined) problem('`host` is not a non-empty string'); + else if (typeof target === 'string') problem(`\`host\` is not ${HOST_FORM}: ${target}`); + else { + environment.host = doc.host as string; + environment.target = target; + } + } + if (doc.hostname !== undefined) { + if (typeof doc.hostname === 'string' && doc.hostname !== '') environment.hostname = doc.hostname; + else { + problem('`hostname` is not a non-empty string'); + environment.invalid.push('hostname'); + } + } + for (const key of ['env', 'secrets'] as const) { + const map = doc[key]; + if (map === undefined || map === null) continue; + if (!isMapping(map)) { + problem(`\`${key}\` is not a map of names to values`); + environment.invalid.push(key); + continue; + } + for (const [variable, value] of Object.entries(map)) { + if (typeof value === 'string') environment[key][variable] = value; + else environment.refused[key].push(variable); + if (key === 'env' && typeof value !== 'string') problem(`\`env\` \`${variable}\` is not a string; quote it`); + if (key === 'secrets' && !(typeof value === 'string' && value.startsWith('op://'))) + problem(`\`secrets\` \`${variable}\` is no \`op://\` pointer`); + } + } + const listed = (key: 'env' | 'secrets') => [...Object.keys(environment[key]), ...environment.refused[key]]; + for (const variable of new Set([...listed('env'), ...listed('secrets')])) { + if (listed('env').includes(variable) && listed('secrets').includes(variable)) + problem(`\`${variable}\` is listed under both \`env\` and \`secrets\``); + else if (PLATFORM_VARIABLES.includes(variable)) problem(`\`${variable}\` is supplied by the platform; remove it`); + } + return environment; +} + +/** A variable of a string: `$NAME`, or `${NAME` with what follows it up to the brace. */ +const REFERENCE = /(\$+)(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\})/g; + +/** The variables a compose file interpolates without a default, in the order found, once each. */ +export function requiredVariables(compose: Compose): string[] { + const found = new Set(); + const visit = (value: unknown): void => { + if (typeof value === 'string') { + for (const [, dollars, bare, braced, rest] of value.matchAll(REFERENCE)) { + if ((dollars?.length ?? 0) % 2 === 0) continue; + if (bare !== undefined) found.add(bare); + else if (braced !== undefined && !/^:?[-+]/.test(rest ?? '')) found.add(braced); + } + } else if (Array.isArray(value)) value.forEach(visit); + else if (isMapping(value)) for (const child of Object.values(value)) visit(child); + }; + visit(compose.document); + return [...found]; +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 7cd5da7f..d2797a77 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -30,7 +30,7 @@ export { } from './changeset.ts'; export { type Compose, declaresHealthcheck, type Mapping, parseCompose } from './compose.ts'; export { filesWithConflictMarkers, hasConflictMarkers, hasUnmergedEntries } from './conflicts.ts'; -export { type Consumer, expectedBranch, findRepos } from './consumers.ts'; +export { type Consumer, findRepos } from './consumers.ts'; export { Context, type Options } from './context.ts'; export { type DeployOptions, @@ -42,23 +42,7 @@ export { renderCommitSha, type StackOutcome, } from './deploy.ts'; -export { - DEFAULT_ENVIRONMENT, - type DeployLeg, - type Deployment, - type DeployTargets, - deployLegs, - ENVIRONMENT_BRANCHES, - type EnvironmentTargets, - environmentOf, - type InventoryFile, - parseInventoryFile, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, - type Untargeted, -} from './deployTargets.ts'; +export { ENVIRONMENT_BRANCHES, environmentOf } from './deployTargets.ts'; export { type AppFacts, CHECKS, @@ -77,6 +61,14 @@ export { } from './doctor.ts'; export { body, describe, type Plan, run, type Step, write } from './effects.ts'; export { envFlag } from './envFlag.ts'; +export { + type Environment, + PLATFORM_VARIABLES, + parseHost, + readEnvironments, + requiredVariables, + type SshTarget, +} from './environments.ts'; export { frontmatterField, setFrontmatterField } from './frontmatter.ts'; export { type DirEntry, @@ -122,7 +114,6 @@ export { type GitFacet, isNotable, isOperations, - isOperationsRepo, type Kind, shortRemote, type Unit, diff --git a/packages/lib/src/model.ts b/packages/lib/src/model.ts index 29078aff..291ec028 100644 --- a/packages/lib/src/model.ts +++ b/packages/lib/src/model.ts @@ -89,21 +89,6 @@ export const listsOperations = (config?: MarkerConfig): boolean => /** The operations repo is the one whose root marker lists the operations template. */ export const isOperations = (dir: Directory): boolean => listsOperations(dir.config); -/** - * Whether the checkout at `dir` is an operations repo: its root marker lists - * the operations template. A marker that is absent or cannot be read as - * configuration makes it none, as the overview has it. - */ -export async function isOperationsRepo(ctx: Context, dir = '.'): Promise { - const text = await ctx.readFile(join(dir, MARKER_FILE)).catch(() => undefined); - if (text === undefined) return false; - try { - return listsOperations(parseMarkerConfig(text)); - } catch { - return false; - } -} - /** * Every unit of a scanned tree, in tree order, as overview labels them. What * a unit is follows from where it is (§ 1.3 PLX), never from what its marker diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 3fcbf9eb..a2f95eb3 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -409,7 +409,7 @@ test('a repo from repo-turbo with updates beside it, an app from app-nextjs and ]); const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); - assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml']); + assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); assert.match(text(target, 'stack/PLEXUS.md'), /^---\ntemplates: \[stack\]\nprofile: stateless\n---\n\n/); assert.match( text(target, 'stack/compose.yaml'), diff --git a/packages/lib/src/operationsPipeline.test.ts b/packages/lib/src/operationsPipeline.test.ts index aa695f9b..44a7ae9f 100644 --- a/packages/lib/src/operationsPipeline.test.ts +++ b/packages/lib/src/operationsPipeline.test.ts @@ -150,17 +150,28 @@ test('deploy.yml keeps its triggers and its permissions, and can be started by h /** The version the render of the next tests is at. */ const VERSION = '7.8.9'; -test('setup of the job deploy follows the checkout, runs in its root, and alone is handed the service account token', async () => { - const { workflow } = (await operations()).deploy; - const steps = workflow.jobs.deploy?.steps ?? []; - assert.match(steps[0]?.uses ?? '', /^actions\/checkout@/); - const setup = steps.find((step) => step.id === 'setup'); - assert.equal(setup?.['working-directory'], undefined); - assert.deepEqual(setup?.env, { - GITHUB_TOKEN: '${{ github.token }}', - OP_SERVICE_ACCOUNT_TOKEN: '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', - }); - for (const step of steps) if (step !== setup) assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, undefined, what(step)); +/** The repository secrets of a deploy: the key it reaches the hosts with, and the read-only token of the vault of the stacks' secrets. */ +const DEPLOY_KEY = '${{ secrets.DEPLOY_SSH_KEY }}'; +const DEPLOY_TOKEN = '${{ secrets.DEPLOY_VAULT_TOKEN }}'; +/** The verb of the job deploy: the Connect server of a slot reads another vault, so the verb's `op` never sees it. */ +const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production'; + +test('setup of the job deploy follows the checkout, runs in its root, and is handed the deploy key and, to join the overlay, the CI vault’s token; the verb alone holds the deploy token', async () => { + for (const ci_overlay of ['none', 'netbird']) { + const { workflow } = (await operations({ ci_overlay })).deploy; + const steps = workflow.jobs.deploy?.steps ?? []; + assert.match(steps[0]?.uses ?? '', /^actions\/checkout@/); + const setup = steps.find((step) => step.id === 'setup'); + assert.equal(setup?.['working-directory'], undefined); + assert.deepEqual(setup?.env, { + GITHUB_TOKEN: '${{ github.token }}', + DEPLOY_SSH_KEY: DEPLOY_KEY, + ...(ci_overlay === 'netbird' ? { OP_SERVICE_ACCOUNT_TOKEN: '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}' } : {}), + }); + for (const step of steps) + if (step !== setup) + assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, step.run === VERB ? DEPLOY_TOKEN : undefined, what(step)); + } assert.equal( (await operations()).on_commit.text.includes('OP_SERVICE_ACCOUNT_TOKEN'), false, @@ -168,7 +179,7 @@ test('setup of the job deploy follows the checkout, runs in its root, and alone ); }); -test('the job deploy is the checkout, mise without an install, the install of plx and plx-ci, setup, Ansible, and the verb with the repo’s own inventory', async () => { +test('the job deploy is the checkout, mise without an install, the install of plx and plx-ci, setup, Ansible, and the verb', async () => { for (const answers of SHAPES) { const result = await renderBundled(['repo-operations'], { tenant: 'acme', ...answers }, VERSION); const deploy = (parse(textOf(result, '.github/workflows/deploy.yml')) as Workflow).jobs.deploy; @@ -182,7 +193,7 @@ test('the job deploy is the checkout, mise without an install, the install of pl `mise use -g node@24 ${tool('cli')} ${tool('cli-ci')}`, `plx-ci setup deploy --overlay ${answers.ci_overlay}`, ...ansibleSteps(VERSION), - 'plx deploy --environment production --inventory inventory', + VERB, ...leave, ], JSON.stringify(answers), @@ -191,7 +202,11 @@ test('the job deploy is the checkout, mise without an install, the install of pl for (const i of [4, 5]) assert.equal(deploy?.steps?.[i]?.['working-directory'], '${{ runner.temp }}'); assert.deepEqual([deploy?.steps?.[4]?.env, deploy?.steps?.[5]?.env], [SHIMS, COLLECTIONS]); // The input reaches the tool through the environment, where plx reads it by its value: a push has none. - assert.deepEqual(deploy?.steps?.[6]?.env, { ...COLLECTIONS, PLX_DRY_RUN: '${{ inputs.dry_run }}' }); + assert.deepEqual(deploy?.steps?.[6]?.env, { + ...COLLECTIONS, + PLX_DRY_RUN: '${{ inputs.dry_run }}', + OP_SERVICE_ACCOUNT_TOKEN: DEPLOY_TOKEN, + }); } }); @@ -269,6 +284,8 @@ test('a step of an operations repo’s workflows is one command or one pinned ac '${{ runner.temp }}', '${{ github.token }}', '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', + DEPLOY_KEY, + DEPLOY_TOKEN, '${{ inputs.dry_run }}', "${{ always() && steps.setup.outputs.joined == 'true' }}", ]); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 902261fb..53269cf2 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -159,7 +159,13 @@ test('an app repo’s three workflows each hold the job repo in full: checkout, } }); -test('on_push deploys after the job repo, in a job of its own: checkout, mise, setup, the operations repo, Ansible, plx deploy', async () => { +/** The repository secrets of a deploy: the key it reaches the hosts with, and the read-only token of the vault of the stacks' secrets. */ +const DEPLOY_KEY = '${{ secrets.DEPLOY_SSH_KEY }}'; +const DEPLOY_TOKEN = '${{ secrets.DEPLOY_VAULT_TOKEN }}'; +/** The verb in the job deploy: the Connect server of a slot reads another vault, so the verb's `op` never sees it. */ +const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy'; + +test('on_push deploys after the job repo, in a job of its own: checkout, mise, setup, Ansible, plx deploy, and no other repo is checked out', async () => { for (const answers of SHAPES) { const deploy = (await appRepo(answers)).on_push.workflow.jobs.deploy; assert.deepEqual(needsOf(deploy), ['repo']); @@ -168,24 +174,40 @@ test('on_push deploys after the job repo, in a job of its own: checkout, mise, s 'jdx/mise-action', `mise use -g node@24 'npm:@plexus-ms/cli[allow_low_downloads=true]@${CURRENT}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@${CURRENT}'`, 'plx-ci setup deploy --overlay none', - 'actions/checkout', ...ansibleSteps(CURRENT), - 'plx deploy --inventory operations/inventory', + VERB, ]); // Ansible is installed outside the checkout, as plx is, and the collection where the verb's Ansible looks. - const [plx, ansible, collection, verb] = [2, 5, 6, 7].map((i) => deploy?.steps?.[i]); + const [plx, ansible, collection, verb] = [2, 4, 5, 6].map((i) => deploy?.steps?.[i]); for (const step of [plx, ansible, collection]) assert.equal(step?.['working-directory'], '${{ runner.temp }}'); - assert.deepEqual([plx?.env, ansible?.env, collection?.env, verb?.env], [SHIMS, SHIMS, COLLECTIONS, COLLECTIONS]); + assert.deepEqual( + [plx?.env, ansible?.env, collection?.env, verb?.env], + [SHIMS, SHIMS, COLLECTIONS, { ...COLLECTIONS, OP_SERVICE_ACCOUNT_TOKEN: DEPLOY_TOKEN }], + ); assert.equal(deploy?.steps?.[3]?.id, 'setup'); - // The tenant's operations repo, with the token that setup minted for it alone. - assert.deepEqual(deploy?.steps?.[4]?.with, { - repository: '${{ github.repository_owner }}/operations', - token: '${{ steps.setup.outputs.operations-token }}', - path: 'operations', - }); + // The deploy key is a repository secret handed to setup, which holds it in an agent. + assert.equal(deploy?.steps?.[3]?.env?.DEPLOY_SSH_KEY, DEPLOY_KEY); + assert.equal((deploy?.steps ?? []).filter((s) => s.uses?.startsWith('actions/checkout')).length, 1); + assert.doesNotMatch(JSON.stringify(deploy), /operations/); } }); +test('the vault of the stacks’ secrets is read with the deploy token, which only the step of plx deploy holds; setup holds the CI vault’s token only to join the overlay', async () => { + for (const ci_service_account of [true, false]) + for (const ci_overlay of ['none', 'netbird']) { + const text = (await appRepo({ ci_service_account, ci_overlay })).on_push; + const deploy = text.workflow.jobs.deploy; + const setup = deploy?.steps?.find((s) => s.id === 'setup'); + const ci = ci_service_account && ci_overlay === 'netbird' ? '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}' : undefined; + assert.equal(setup?.env?.OP_SERVICE_ACCOUNT_TOKEN, ci, JSON.stringify({ ci_service_account, ci_overlay })); + for (const step of deploy?.steps ?? []) + if (step.id !== 'setup') + assert.equal(step.env?.OP_SERVICE_ACCOUNT_TOKEN, step.run === VERB ? DEPLOY_TOKEN : undefined, what(step)); + // No job but the deploy holds either repository secret of the deploy. + assert.doesNotMatch(JSON.stringify(text.workflow.jobs.repo), /DEPLOY_/); + } +}); + test('the job repo asks for a repo slot under byom and the job deploy for a delivery slot, both for the forge’s runner under github', async () => { for (const ci_strategy of STRATEGIES) { const workflows = await appRepo({ ci_strategy }); @@ -260,11 +282,19 @@ test('setup alone is handed the service account token where the repo answers ci_ for (const job of Object.values(handed[name].workflow.jobs)) for (const step of job.steps ?? []) { const token = step.env?.OP_SERVICE_ACCOUNT_TOKEN; - if (step.id === 'setup') assert.equal(token, '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', name); + if (step.id === 'setup' && job === handed[name].workflow.jobs.repo) + assert.equal(token, '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', name); + else if (step.run === VERB) assert.equal(token, DEPLOY_TOKEN, name); else assert.equal(token, undefined, `${name}: ${what(step)}`); } const unhanded = await appRepo({ ci_strategy, ci_service_account: false }); - for (const name of APP) assert.doesNotMatch(unhanded[name].text, /service.account|OP_SERVICE/i, name); + // The deploy token is the verb's own, and not the CI vault's. + for (const name of APP) + assert.doesNotMatch( + unhanded[name].text.replace(/^ *OP_SERVICE_ACCOUNT_TOKEN: .*DEPLOY_VAULT_TOKEN.*$/m, ''), + /service.account|OP_SERVICE/i, + name, + ); } }); @@ -418,8 +448,8 @@ test('a step of an app repo’s workflows is one command, and the only expressio '${{ github.token }}', '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', '${{ steps.setup.outputs.server-actions-key }}', - '${{ steps.setup.outputs.operations-token }}', - '${{ github.repository_owner }}', + DEPLOY_KEY, + DEPLOY_TOKEN, '${{ github.run_attempt }}', "${{ failure() && steps.e2e.conclusion == 'failure' }}", "${{ always() && steps.setup.outputs.joined == 'true' }}", diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index d93ca004..dae485e7 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -127,6 +127,8 @@ test('the marker is written once, and without frontmatter, which plx writes', as assert.match(textOf(result, 'PLEXUS.md'), /^- The operations repo of `acme`/); // Third-party software is stacks of no app, as plx deploy reads them; nothing is under apps/. assert.match(textOf(result, 'PLEXUS.md'), /`stacks\/\/`.*`stack\/`/); + assert.match(textOf(result, 'PLEXUS.md'), /plx deploy --environment `.*a file for that environment/); + assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /--inventory/); assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /apps\//); // And what a person adds to the compose file plx new gives such a stack, so that plx doctor passes. for (const needed of [ diff --git a/packages/lib/src/stack.test.ts b/packages/lib/src/stack.test.ts index fc79141b..b33ec640 100644 --- a/packages/lib/src/stack.test.ts +++ b/packages/lib/src/stack.test.ts @@ -16,11 +16,14 @@ const servicesOf = async (answers: Record = {}) => { const TAGGED = (app: string) => `ghcr.io/acme/${app}:\${PLEXUS_TAG:?set by the deploy}`; const LOOPBACK = '127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:3000'; -test('a stack is its compose file and its marker, both its own from birth, with nothing run at birth', async () => { +test('a stack is its compose file, its marker and a file for each environment the branches deploy, all its own from birth, with nothing run at birth', async () => { const result = await render(); assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml']); - for (const [path, origin] of result.files) assert.equal(origin.policy, 'born-once', path); + assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); + // The compose file and the marker are never re-synced; an environment's file is written at a birth alone, so that an + // update adds none to a stack that was born before the template had it. + for (const [path, origin] of result.files) + assert.equal(origin.policy, path.endsWith('.yaml') && path !== 'compose.yaml' ? 'birth-only' : 'born-once', path); assert.deepEqual(result.birth, []); }); @@ -124,13 +127,40 @@ test('an app is named as its directory under apps/ may be, once', async () => { } }); -test('the compose file says it was generated once and is the stack’s own', async () => { +test('the compose file and the environment files say they were generated once and are the stack’s own', async () => { const lines = generatedFrom(await render()); assert.deepEqual( lines.map(([path]) => path), - ['compose.yaml'], + ['compose.yaml', 'production.yaml', 'staging.yaml'], ); - assert.match(lines[0]?.[1] ?? '', /^# Generated from plexus-ms\/tooling, templates\/stack, once:/); + for (const [, line] of lines) assert.match(line, /^# Generated from plexus-ms\/tooling, templates\/stack, once:/); +}); + +/** An environment's file as the template renders it, parsed. */ +const environmentOf = async (name: string, answers: Record = {}) => + parse(textOf(await render(answers), `${name}.yaml`)) as Record; + +test('an environment file names the four keys: the host to replace, a hostname for the first app, no values and no secrets yet', async () => { + for (const [name, hostname] of [ + ['production', 'shop.example.com'], + ['staging', 'shop.staging.example.com'], + ] as const) + assert.deepEqual(await environmentOf(name), { host: 'host.example.com', hostname, env: {}, secrets: {} }, name); + // The first of several apps publishes the port, so it names the stack's hostname. + assert.equal((await environmentOf('staging', { apps: 'admin,shop' })).hostname, 'admin.staging.example.com'); +}); + +test('a stack of no app has no hostname to name, for it has no port: its environment files hold the host alone', async () => { + const result = await renderBundled(['stack'], { tenant: 'acme' }); + for (const name of ['production', 'staging']) + assert.deepEqual(parse(textOf(result, `${name}.yaml`)), { host: 'host.example.com', env: {}, secrets: {} }, name); +}); + +test('the marker says where an environment’s host, hostname, values and secrets go, and that a new environment is a new file', async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + assert.match(marker, /`production\.yaml`/); + assert.match(marker, /`host`/); + assert.match(marker, /`op:\/\/`/); }); test('the marker has no frontmatter, which plx writes, and says how an app joins and how a second stack comes', async () => { diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index cf9d390d..5fba8bbd 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context } from './context.ts'; import { loadStacks } from './stacks.ts'; -import { fakeIo, type Tree } from './testing/fakeIo.ts'; +import { fakeIo, link, type Tree } from './testing/fakeIo.ts'; const compose = (image = 'ghcr.io/acme/shop:${PLEXUS_TAG}') => `services:\n web:\n image: ${image}\n`; const marker = (profile = 'stateless') => `---\nprofile: ${profile}\n---\n\nA stack.\n`; @@ -398,3 +398,300 @@ test("the package's index exports the loader and no longer the special service n assert.equal(typeof index.loadStacks, 'function'); assert.equal('APP_SERVICE' in index, false); }); + +// --- environments -------------------------------------------------------------- + +/** The environments of the one stack of a repo whose stack/ holds `files`. */ +const environmentsOf = async (files: Tree) => { + const repo = await load({ stack: { 'compose.yaml': compose(), ...files }, apps: { shop: dockerfile } }); + return repo.stacks[0]?.environments ?? []; +}; + +test("a stack's environments are its `.yaml` files but the compose files, by name, parsed into host, hostname, env and secrets", async () => { + const environments = await environmentsOf({ + 'staging.yaml': 'host: 192.0.2.2\nenv:\n MODE: staging\n RETRIES: "3"\n DEBUG: "true"\n', + 'production.yaml': + 'host: 192.0.2.1\nhostname: shop.example.com\nenv:\n MODE: production\nsecrets:\n TOKEN: op://acme/shop/token\n', + 'compose.dev.yaml': 'services: {}\n', + 'PLEXUS.md': marker(), + 'notes.txt': 'x', + }); + assert.deepEqual(environments, [ + { + name: 'production', + file: '/work/shop/stack/production.yaml', + host: '192.0.2.1', + target: { address: '192.0.2.1' }, + hostname: 'shop.example.com', + env: { MODE: 'production' }, + secrets: { TOKEN: 'op://acme/shop/token' }, + refused: { env: [], secrets: [] }, + invalid: [], + unread: false, + problems: [], + }, + { + name: 'staging', + file: '/work/shop/stack/staging.yaml', + host: '192.0.2.2', + target: { address: '192.0.2.2' }, + env: { MODE: 'staging', RETRIES: '3', DEBUG: 'true' }, + secrets: {}, + refused: { env: [], secrets: [] }, + invalid: [], + unread: false, + problems: [], + }, + ]); +}); + +test('a stack without environment files has no environments, and the loader reports no problem', async () => { + const repo = await load({ stack: { 'compose.yaml': compose() }, apps: { shop: dockerfile } }); + assert.deepEqual(repo.stacks[0]?.environments, []); + assert.deepEqual(repo.problems, []); +}); + +test('each stack of several has the environments of its own directory', async () => { + const repo = await load({ + apps: { shop: dockerfile }, + stacks: { + a: { 'compose.yaml': compose(), 'staging.yaml': 'host: 192.0.2.1\n' }, + b: { 'compose.yaml': compose('postgres:16'), 'production.yaml': 'host: 192.0.2.2\n' }, + }, + }); + assert.deepEqual( + repo.stacks.map((s) => s.environments.map((e) => e.name)), + [['staging'], ['production']], + ); +}); + +test('a directory named like an environment file is no environment', async () => { + assert.deepEqual(await environmentsOf({ 'staging.yaml': { 'host.yaml': 'x' } }), []); +}); + +test('an environment file that cannot be used says why in its own problems, one line per bad value, and is still returned', async () => { + const cases: [string, string, RegExp][] = [ + ['staging', 'host: 192.0.2.1\nport: 1\n', /staging\.yaml: unknown key `port`/], + ['staging', 'hostname: shop.example.com\n', /staging\.yaml: has no `host`/], + ['staging', 'host: ""\n', /staging\.yaml: `host` is not a non-empty string/], + ['staging', 'host: 3\n', /`host` is not a non-empty string/], + ['staging', 'host: 192.0.2.1\nhostname: 3\n', /`hostname` is not a non-empty string/], + ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n', /`secrets` `TOKEN` is no `op:\/\/` pointer/], + ['staging', 'host: 192.0.2.1\nsecrets:\n TOKEN: 3\n', /`secrets` `TOKEN` is no `op:\/\/` pointer/], + ['staging', 'host: 192.0.2.1\nenv: [a]\n', /`env` is not a map/], + ['staging', 'host: 192.0.2.1\nsecrets: x\n', /`secrets` is not a map/], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n A: x\nsecrets:\n A: op://a/b/c\n', + /`A` is listed under both `env` and `secrets`/, + ], + ['staging', 'host: 192.0.2.1\nenv:\n PLEXUS_TAG: x\n', /`PLEXUS_TAG` is supplied by the platform; remove it/], + [ + 'staging', + 'host: 192.0.2.1\nsecrets:\n PLEXUS_COMMIT_SHA: op://a/b/c\n', + /`PLEXUS_COMMIT_SHA` is supplied by the platform/, + ], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n COMPOSE_PROJECT_NAME: x\n', + /`COMPOSE_PROJECT_NAME` is supplied by the platform/, + ], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n PLEXUS_LOOPBACK_PORT: x\n', + /`PLEXUS_LOOPBACK_PORT` is supplied by the platform/, + ], + ['Staging', 'host: 192.0.2.1\n', /one lowercase word/], + ['pre-prod', 'host: 192.0.2.1\n', /one lowercase word/], + ['stage2', 'host: 192.0.2.1\n', /one lowercase word/], + ['a.b', 'host: 192.0.2.1\n', /one lowercase word/], + ]; + for (const [name, text, problem] of cases) { + const [environment, ...rest] = await environmentsOf({ [`${name}.yaml`]: text }); + assert.equal(rest.length, 0, text); + assert.equal(environment?.name, name, text); + assert.equal(environment?.problems.length, 1, `${text}: ${environment?.problems.join('; ')}`); + assert.match(environment?.problems[0] ?? '', problem, text); + assert.match(environment?.problems[0] ?? '', new RegExp(`^${name.replace('.', '\\.')}\\.yaml: `)); + } +}); + +test('a value under env that is no string is refused, naming the file and the key and saying to quote it, and its name stays listed', async () => { + for (const value of ['3', 'true', '~', '{a: 1}', '[a]', '1.0']) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: 192.0.2.1\nenv:\n KEY: ${value}\n` }); + assert.deepEqual(environment?.problems, ['staging.yaml: `env` `KEY` is not a string; quote it'], value); + assert.deepEqual(environment?.env, {}, value); + assert.deepEqual(environment?.refused, { env: ['KEY'], secrets: [] }, value); + assert.equal(environment?.unread, false); + } +}); + +test('a secret that is no pointer is still listed under its name, so that only its own problem is reported; a non-string one is refused but listed', async () => { + const [plain] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: plain\n' }); + assert.deepEqual(plain?.secrets, { TOKEN: 'plain' }); + assert.equal(plain?.problems.length, 1); + const [number] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\nsecrets:\n TOKEN: 3\n' }); + assert.deepEqual(number?.secrets, {}); + assert.deepEqual(number?.refused, { env: [], secrets: ['TOKEN'] }); + assert.equal(number?.problems.length, 1); +}); + +test('a file that is empty, not YAML, no map or unreadable is unread, with one problem of its own and no host problem on top', async () => { + const cases: [string | ReturnType, RegExp][] = [ + ['', /^staging\.yaml: is empty; it needs a `host`$/], + ['# nothing\n', /^staging\.yaml: is empty/], + ['host: [\n', /^staging\.yaml: not valid YAML: /], + ['- a\n', /^staging\.yaml: is not a map of `host`/], + ['x', /^staging\.yaml: is not a map of `host`/], + [link('/work/nothing'), /^staging\.yaml: could not be read: ENOENT/], + ]; + for (const [text, problem] of cases) { + const [environment, ...rest] = await environmentsOf({ 'staging.yaml': text }); + assert.equal(rest.length, 0); + assert.equal(environment?.unread, true, String(text)); + assert.equal(environment?.problems.length, 1, `${text}: ${environment?.problems.join('; ')}`); + assert.match(environment?.problems[0] ?? '', problem, String(text)); + } +}); + +test('a `.yml` file in a stack directory is a problem of the stack, naming the file it should be, and no environment', async () => { + const repo = await load({ + stack: { 'compose.yaml': compose(), 'production.yml': 'host: 192.0.2.1\n', 'compose.dev.yml': 'services: {}\n' }, + apps: { shop: dockerfile }, + }); + assert.deepEqual(repo.stacks[0]?.environments, []); + assert.deepEqual(codes(repo), ['bad-environment-file', 'bad-environment-file']); + assert.deepEqual(repo.problems.map((p) => p.message).sort(), [ + 'compose.dev.yml: name it compose.dev.yaml', + 'production.yml: name it production.yaml', + ]); + assert.equal(repo.problems[0]?.stack, 'shop'); +}); + +/** The environment a `host` value gives, written as a YAML scalar by JSON, which quotes whatever it holds. */ +const withHost = async (host: string) => + (await environmentsOf({ 'staging.yaml': `host: ${JSON.stringify(host)}\n` }))[0]; + +test('`host` is an SSH destination, `[user@]address[:port]`, returned as written and parsed, absence being absence', async () => { + const cases: [string, Record][] = [ + ['192.0.2.1', { address: '192.0.2.1' }], + ['shop.example.com', { address: 'shop.example.com' }], + ['localhost', { address: 'localhost' }], + ['a-b.c-d.example.com', { address: 'a-b.c-d.example.com' }], + ['192.0.2.1:22', { address: '192.0.2.1', port: 22 }], + ['255.255.255.255', { address: '255.255.255.255' }], + ['deploy@192.0.2.10:2222', { address: '192.0.2.10', user: 'deploy', port: 2222 }], + ['deploy@shop.example.com', { address: 'shop.example.com', user: 'deploy' }], + ['de.ploy_1@shop.example.com:1', { address: 'shop.example.com', user: 'de.ploy_1', port: 1 }], + ['2001:db8::1', { address: '2001:db8::1' }], + ['::1', { address: '::1' }], + ['deploy@2001:db8::1', { address: '2001:db8::1', user: 'deploy' }], + ['[2001:db8::1]', { address: '2001:db8::1' }], + ['[2001:db8::1]:2222', { address: '2001:db8::1', port: 2222 }], + ['deploy@[2001:db8::1]:65535', { address: '2001:db8::1', user: 'deploy', port: 65535 }], + ]; + for (const [host, target] of cases) { + const environment = await withHost(host); + assert.deepEqual(environment?.problems, [], host); + assert.equal(environment?.host, host); + assert.deepEqual(environment?.target, target, host); + } +}); + +test('a `host` that is no SSH destination is one problem naming the file and showing the form, and no host', async () => { + const bad = [ + // ssh options, in each position + '-Jevil.example.com', + '-oProxyCommand=x@h', + '-u@host', + 'u@-h', + 'u@-h:22', + 'u@[-::1]', + '-', + '.', + '-a.example.com', + 'a-.example.com', + 'a.-b.example.com', + // names and numbers + '999.999.999.999', + '1.2.3', + '1.2.3.4.5', + '01.2.3.256', + 'a..b', + 'host.', + '.host', + // ports + '192.0.2.1:', + ':22', + '192.0.2.1:0', + '192.0.2.1:65536', + '192.0.2.1:ab', + '192.0.2.1:-1', + '192.0.2.1:22:33', + // user + '@192.0.2.1', + 'deploy@', + 'a@b@c', + 'de ploy@192.0.2.1', + // brackets + '[:]', + '[]', + '[2001:db8::1', + '[2001:db8::1]x', + '[2001:db8::1]:', + '[2001:db8::1]:ab', + '[192.0.2.1]', + '[shop.example.com]:22', + '2001:db8::1]', + // characters no name has + '192.0.2.1 ', + '192.0.2.1 x', + 'a b', + 'h;reboot', + 'u;x@h', + '$(id)', + 'h$(id).example.com', + '`id`', + '"x', + "'x", + 'ssh://192.0.2.1', + '192.0.2.1/path', + 'h\\n', + ]; + for (const host of bad) { + const environment = await withHost(host); + assert.equal(environment?.problems.length, 1, host); + assert.match( + environment?.problems[0] ?? '', + /^staging\.yaml: `host` is not `\[user@\]address\[:port\]`.*deploy@192\.0\.2\.10:2222/, + host, + ); + assert.equal(environment?.host, undefined, host); + assert.equal(environment?.target, undefined, host); + } +}); + +test('a value that makes part of a file unusable is named in `invalid`, so that the comparisons leave that part out', async () => { + const cases: [string, string][] = [ + ['hostname: ""\n', 'hostname'], + ['hostname: 3\n', 'hostname'], + ['env: [a]\n', 'env'], + ['secrets: x\n', 'secrets'], + ]; + for (const [text, key] of cases) { + const [environment] = await environmentsOf({ 'staging.yaml': `host: 192.0.2.1\n${text}` }); + assert.deepEqual(environment?.invalid, [key], text); + assert.equal(environment?.problems.length, 1, text); + } + const [fine] = await environmentsOf({ 'staging.yaml': 'host: 192.0.2.1\n' }); + assert.deepEqual(fine?.invalid, []); +}); + +test('a compose file whose aliases form a cycle is a bad compose file, which compose refuses too', async () => { + const repo = await load({ + stack: { 'compose.yaml': 'x-a: &a\n self: *a\nservices:\n web:\n image: ghcr.io/acme/shop:${PLEXUS_TAG}\n' }, + apps: { shop: dockerfile }, + }); + assert.ok(codes(repo).includes('bad-compose')); + assert.match(repo.problems.find((p) => p.code === 'bad-compose')?.message ?? '', /aliases form a cycle/); +}); diff --git a/packages/lib/src/stacks.ts b/packages/lib/src/stacks.ts index 56e8bccb..f00d0b3f 100644 --- a/packages/lib/src/stacks.ts +++ b/packages/lib/src/stacks.ts @@ -7,8 +7,9 @@ // has the repo's name, or several at `stacks//compose.yaml`, each named // after its directory. No compose file of a stack lives at the repo's root or // inside an app. A stack's directory may hold `compose.dev.yaml`, which is -// reported (`dev`) and never read, and a `PLEXUS.md`, whose frontmatter is -// returned as `marker`. An app is a directory under `apps/` that holds a +// reported (`dev`) and never read, a `PLEXUS.md`, whose frontmatter is +// returned as `marker`, and one `.yaml` per environment, returned as +// `environments` (environments.ts states the file's shape). An app is a directory under `apps/` that holds a // `Dockerfile`. // // The repo's name is the `repo` key (REPO_KEY) of its root `PLEXUS.md`, a non-empty @@ -45,6 +46,8 @@ // (lowercase letters, digits, `-` and `_`, starting // with a letter or digit) // bad-compose a `compose.yaml` that is not YAML compose can read +// bad-environment-file a `.yml` in a stack's directory, which is no +// environment file; the problem says to name it `.yaml` // unused-app an app that no stack uses // unknown-app a service whose image carries the tag variable and // names no app, or whose pinned image is in a registry @@ -54,10 +57,15 @@ import { join, relative, resolve } from 'node:path'; import { type Compose, parseCompose } from './compose.ts'; import type { Context } from './context.ts'; +import { type Environment, readEnvironments } from './environments.ts'; import { MARKER_FILE, splitFrontmatter } from './marker.ts'; import { APPS_DIR } from './model.ts'; import { isDirectory } from './overview.ts'; +/** The names of a stack's compose files: the one the deploy reads, and the one a developer runs locally. */ +export const COMPOSE_FILE = 'compose.yaml'; +export const DEV_COMPOSE_FILE = 'compose.dev.yaml'; + /** The key of the root marker that names the repo; a key of the marker's own, no question of a template. */ export const REPO_KEY = 'repo'; @@ -93,6 +101,8 @@ export interface Stack { apps: StackApp[]; /** The services that run an image pinned literally, in the file's order. */ pinned: StackPin[]; + /** Its environments, by name: the `.yaml` files of the directory (environments.ts). */ + environments: Environment[]; } /** What a repo's stacks are and what is wrong with how they are laid out. */ @@ -116,6 +126,7 @@ export type StackProblemCode = | 'no-compose' | 'bad-name' | 'bad-compose' + | 'bad-environment-file' | 'unused-app' | 'unknown-app'; @@ -203,9 +214,17 @@ async function stackAt( apps: string[], problems: StackProblem[], ): Promise { - const entries = new Set((await ctx.readDir(dir)).map((e) => e.name)); + const listing = await ctx.readDir(dir); + const entries = new Set(listing.map((e) => e.name)); + const files = listing.filter((e) => !e.directory).map((e) => e.name); + for (const file of files.filter((f) => f.endsWith('.yml'))) + problems.push({ + code: 'bad-environment-file', + message: `${file}: name it ${file.slice(0, -'.yml'.length)}.yaml`, + stack: name, + }); const marker = entries.has(MARKER_FILE) ? await readMarker(ctx, join(dir, MARKER_FILE)) : undefined; - const file = join(dir, 'compose.yaml'); + const file = join(dir, COMPOSE_FILE); const used: Pick = { apps: [], pinned: [] }; let images: Image[] = []; const text = await ctx.readFile(file).catch(() => undefined); @@ -225,9 +244,14 @@ async function stackAt( name, dir, compose: file, - dev: entries.has('compose.dev.yaml'), + dev: entries.has(DEV_COMPOSE_FILE), ...(marker === undefined ? {} : { marker }), ...used, + environments: await readEnvironments( + ctx, + dir, + files.filter((f) => f.endsWith('.yaml') && f !== COMPOSE_FILE && f !== DEV_COMPOSE_FILE), + ), }; return { stack, images, hasCompose: text !== undefined }; } diff --git a/packages/lib/src/standard-index.json b/packages/lib/src/standard-index.json index 915ff2bb..428bc4b4 100644 --- a/packages/lib/src/standard-index.json +++ b/packages/lib/src/standard-index.json @@ -152,7 +152,6 @@ "PLX-Stack/ReservedPrefix", "PLX-Stack/SinglePort", "PLX-Stack/LoopbackPort", - "PLX-Stack/PathPrefix", "PLX-Stack/Healthcheck", "PLX-Stack/HostDirectory", "PLX-Stack/ComposeDelivery", @@ -219,7 +218,6 @@ "§ 3 PLX-Infrastructure", "§ 1 PLX-Ingress", "§ 2 PLX-Ingress", - "PLX-Ingress/PrefixInRecord", "PLX-Ingress/OneStackPerPrefix", "§ 1 PLX-JS", "§ 2 PLX-JS", @@ -249,6 +247,12 @@ "PLX-Updates/LocalConfig", "PLX-Updates/UpdateBot", "PLX-Updates/FromTemplates", - "PLX-Updates/Interval" + "PLX-Updates/Interval", + "PLX-Stack/NoCommittedSecrets", + "PLX-Stack/EnvironmentFile", + "PLX-Stack/EnvironmentParity", + "PLX-Stack/EnvironmentCoverage", + "PLX-Stack/HostnamePort", + "PLX-Stack/PreparedHost" ] } diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 267b89c4..ae495645 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -20,9 +20,15 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Stack/Layout` and `PLX-Stack/AppInStack`; of `PLX-Stack/Compose` that every stack has its `compose.yaml`; of `PLX-Stack/ImageRef` that every image naming an app of the repo has that form, with or without an error message, and every other image holds no interpolation; and of `PLX-Stack/TenantLabel` that every service carries a `plexus.tenant` label with a value, not that the value is the tenant's slug. -`plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedValues` that the repo tracks no `.env` and no `.env.secret`. +`plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedSecrets` that the repo tracks no `.env` and no `.env.secret`. -`plx doctor` checks of `PLX-Stack/SinglePort` that exactly one service binds `PLEXUS_LOOPBACK_PORT`, in exactly one port mapping, not that it speaks plain HTTP, and checks `PLX-Stack/LoopbackPort`. +It checks `PLX-Stack/EnvironmentFile`, of `host` its form and not that the host answers, refusing a number or a boolean under `env` with the advice to quote it, and checks `PLX-Stack/EnvironmentParity`. + +It checks of `PLX-Stack/EnvironmentCoverage` that every variable interpolated in a value of the compose file is listed under `env` of every environment file; it reads no key of the compose file, and not how a secret reaches a container. + +`plx doctor` checks of `PLX-Stack/SinglePort` that a stack whose environments have a `hostname` binds `PLEXUS_LOOPBACK_PORT` in exactly one port mapping, a stack whose environments have none binds it in none, and a stack without environment files binds it in exactly one, not that the service speaks plain HTTP. + +It checks `PLX-Stack/LoopbackPort` and `PLX-Stack/HostnamePort`. `plx doctor` checks of `PLX-Stack/Healthcheck` that each of those services declares a `healthcheck` with a test of its own that is not disabled. diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index 5fe9a229..bd9fc053 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -17,9 +17,9 @@ // (`gh api repos/plexus-ms/compendium/releases`): their numbers are the steps, // and their dates are what the interval is measured against. // -// The repo is judged by what origin has on the branch the version lands on -// (consumers.ts), never by the checkout, which may be behind it or on a branch -// of its own. Its markers there are its configuration (sites.ts): the root +// The repo is judged by what origin has on the branch the version lands on, its +// default branch (consumers.ts), never by the checkout, which may be behind it +// or on a branch of its own. Its markers there are its configuration (sites.ts): the root // marker's `version` is the version the repo is on, and refusing a downgrade, // the interval and readiness all read it. A repo that still tracks a copier // answers file there has not crossed over to the markers, and is refused with diff --git a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja b/templates/repo-operations/files/.github/workflows/deploy.yml.jinja index 012031f2..f3f14990 100644 --- a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/deploy.yml.jinja @@ -43,10 +43,12 @@ jobs: env: MISE_SYSTEM_SHIMS_DIR: ${{ runner.temp }}/mise-system-shims run: mise use -g node@24 'npm:@plexus-ms/cli[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' + # Setup holds the deploy key, a repository secret, in an agent, and reads the vault of the CI only to join the overlay. - id: setup env: GITHUB_TOKEN: ${{ github.token }} - OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}{% endraw %}{% if ci_overlay == 'netbird' %}{% raw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup deploy --overlay {% endraw %}{{ ci_overlay }}{% raw %} # Ansible, at the major the collection is tested with, and the collection plexus.platform at the Plexus version of # the plx above, which plx deploy runs the stack playbook of, with the community.docker its galaxy.yml names where @@ -59,10 +61,13 @@ jobs: env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections run: ansible-galaxy collection install 'git+https://github.com/plexus-ms/tooling.git#/ansible/platform/,{% endraw %}{{ _plexus_version }}{% raw %}' + # The stack playbook resolves the stacks' secrets with the read-only token of the tenant's vault, the repository + # secret DEPLOY_VAULT_TOKEN, which this step alone holds; the Connect server of a slot reads another vault. - env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.DEPLOY_VAULT_TOKEN }} PLX_DRY_RUN: ${{ inputs.dry_run }} - run: plx deploy --environment production --inventory inventory{% endraw %} + run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production{% endraw %} {%- if ci_overlay == 'netbird' %}{% raw %} - if: ${{ always() && steps.setup.outputs.joined == 'true' }} run: sudo netbird down || true{% endraw %} diff --git a/templates/repo-operations/files/PLEXUS.md.jinja b/templates/repo-operations/files/PLEXUS.md.jinja index 60f8dcfd..8396c2e7 100644 --- a/templates/repo-operations/files/PLEXUS.md.jinja +++ b/templates/repo-operations/files/PLEXUS.md.jinja @@ -1,7 +1,7 @@ -- The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory they run on, and the third-party software it operates, as stacks of no app: each at `stacks//`, or at `stack/` where there is one, created by `plx new` from the template `stack`, with a marker of its own. +- The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory of the hosts they run on, and the third-party software it operates, as stacks of no app: each at `stacks//`, or at `stack/` where there is one, created by `plx new` from the template `stack`, with a marker of its own. - `plx new stacks/ stack` gives a stack of third-party software a compose file of `services: {}` (`plx new stack stack` for the one stack of a repo that has one, which also needs `repo` in this marker, the repo's name). For `plx doctor` to pass, add its services, each with its image pinned and the label `plexus.tenant: {{ tenant }}`. The service that serves it publishes `127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:`, as the one port of the stack, declares a healthcheck, and loads under `env_file` both `.env` and `.env.secret`, the latter with `required: false`. -- `plx deploy --environment --inventory inventory` deploys every stack with a record in that environment; the workflow `deploy` does it into production. +- `plx deploy --environment ` deploys every stack that has a file for that environment, to the host the file names; the workflow `deploy` does it into production. - `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}; `mise :check` checks the repo and `mise :test` runs check first. - The Plexus version the repo is on is the `version` of this marker, and its `plx` pin in `mise.toml` follows it, the collections in `requirements.yml` pinned to the same. diff --git a/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja b/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja index 55c0feb9..f0d954db 100644 --- a/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja +++ b/templates/repo-operations/files/inventory/group_vars/platform.yml.jinja @@ -1,12 +1,7 @@ # Generated from plexus-ms/tooling, templates/repo-operations. -# What the hosts that run this tenant's apps get; their apps are per host, in host_vars (§ 3 PLX-Platform). +# What the hosts that run this tenant's stacks get; a stack's environment, its host among it, is a file of the stack (§ 3 PLX-Stack). plexus_deploy_user: plexus -plexus_deploy_root: /opt/stacks - -plexus_up: true - -plexus_apps: [] plexus_deploy_pubkey: "{% raw %}{{ lookup('env', 'DEPLOY_PUBKEY') | default('', true) }}{% endraw %}" plexus_ghcr_user: "{% raw %}{{ lookup('env', 'GHCR_USER') | default('', true) }}{% endraw %}" diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index 9b199397..4d885e5c 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -25,10 +25,10 @@ terraform = "1" # the runner hosts' root, ci/ # hk is absent on a CI runner whose mise installs only the tools a job names. postinstall = "if command -v hk >/dev/null; then hk install --mise; fi" -# A layer's verb passes what follows `--` to ansible-playbook: `mise platform -- --tags apps --limit vm101`. +# A layer's verb passes what follows `--` to ansible-playbook: `mise platform -- --tags caddy --limit vm101`. [tasks.platform] depends = ["collections"] -description = "The platform layer on the app hosts (PLX-Platform): host baseline, deploy user, ingress, secrets, apps; --tags for a part" +description = "The platform layer on the app hosts (PLX-Platform): host baseline, deploy user, ingress, registry login; --tags for a part" run = './ansible-playbookw platform.yml' {% if infrastructure -%} diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 9cf753f8..c45b2569 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -52,7 +52,7 @@ questions: ci_overlay: type: str - help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the inventory names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" + help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the host of each environment file names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" choices: - none - netbird diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 14c6ea60..184aca16 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -148,16 +148,13 @@ jobs: env: MISE_SYSTEM_SHIMS_DIR: ${{ runner.temp }}/mise-system-shims run: mise use -g node@{% endraw %}{{ node_version }}{% raw %} 'npm:@plexus-ms/cli[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' 'npm:@plexus-ms/cli-ci[allow_low_downloads=true]@{% endraw %}{{ _plexus_version }}{% raw %}' + # Setup holds the deploy key, a repository secret, in an agent, and reads the vault of the CI only to join the overlay. - id: setup env: - GITHUB_TOKEN: ${{ github.token }}{% endraw %}{% if ci_service_account %}{% raw %} + GITHUB_TOKEN: ${{ github.token }} + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}{% endraw %}{% if ci_service_account and ci_overlay == 'netbird' %}{% raw %} OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %} run: plx-ci setup deploy --overlay {{ ci_overlay }}{% raw %} - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: ${{ github.repository_owner }}/operations - token: ${{ steps.setup.outputs.operations-token }} - path: operations # Ansible, at the major the collection is tested with, and the collection plexus.platform at the Plexus version of # the plx above, which plx deploy runs the stack playbook of, with the community.docker its galaxy.yml names where # Ansible's own is older: installed outside the checkout as plx is, the collection where the verb's Ansible looks. @@ -169,9 +166,12 @@ jobs: env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections run: ansible-galaxy collection install 'git+https://github.com/plexus-ms/tooling.git#/ansible/platform/,{% endraw %}{{ _plexus_version }}{% raw %}' + # The stack playbook resolves the stacks' secrets with the read-only token of the tenant's vault, the repository + # secret DEPLOY_VAULT_TOKEN, which this step alone holds; the Connect server of a slot reads another vault. - env: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections - run: plx deploy --inventory operations/inventory{% endraw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.DEPLOY_VAULT_TOKEN }} + run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy{% endraw %} {%- if ci_overlay == 'netbird' %}{% raw %} - if: ${{ always() && steps.setup.outputs.joined == 'true' }} run: sudo netbird down || true{% endraw %} diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 03ffe30d..7c6a1426 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -74,7 +74,7 @@ questions: ci_overlay: type: str - help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the inventory names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" + help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the host of each environment file names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" choices: - none - netbird diff --git a/templates/stack/files/PLEXUS.md.jinja b/templates/stack/files/PLEXUS.md.jinja index 7bbb5ac1..9a0a36a5 100644 --- a/templates/stack/files/PLEXUS.md.jinja +++ b/templates/stack/files/PLEXUS.md.jinja @@ -4,6 +4,9 @@ - Born with no app of the repo, its compose file holds `services: {}`, which `plx doctor` reports until the services of the software it runs are written. {%- endif %} - An app joins it by a service whose image is `//:${PLEXUS_TAG:?set by the deploy}`, which loads `.env` and `.env.secret` (optional) and declares a healthcheck; one service of the stack publishes `PLEXUS_LOOPBACK_PORT`. +- Each environment is a file beside the compose file, named after it: `production.yaml` and `staging.yaml` are born with the stack, and a further environment is a further file. + Its `host` is where it deploys, `[user@]address[:port]`, and replacing the placeholder is the first thing to do; its `hostname` is the public name the proxy serves, which the service that publishes the loopback port needs. + Its `env` holds the plain values the compose file reads, and its `secrets` the same kind of names as `op://` pointers, which the deploy resolves; every environment lists the same names. - A second stack in the repo moves `stack/` to `stacks//` and is created beside it with `plx new stacks/ stack -a apps=`. {%- if profile == 'stateful' %} - Its `migrate` service runs the migration on the image of the app that carries it, whose marker answers `migrates: true`, before every deploy brings the stack up; software the tenant does not build that migrates itself lists `PLX-Stack/Stateful/MigrateService` under `deviations` instead. diff --git a/templates/stack/files/production.yaml.jinja b/templates/stack/files/production.yaml.jinja new file mode 100644 index 00000000..963c80dd --- /dev/null +++ b/templates/stack/files/production.yaml.jinja @@ -0,0 +1,9 @@ +{%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} +# Generated from plexus-ms/tooling, templates/stack, once: the environment `production` of this stack (PLX-Stack), its own from then on. +# Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. +host: host.example.com +{%- if names %} +hostname: {{ names[0] }}.example.com +{%- endif %} +env: {} +secrets: {} diff --git a/templates/stack/files/staging.yaml.jinja b/templates/stack/files/staging.yaml.jinja new file mode 100644 index 00000000..2bd1dd7d --- /dev/null +++ b/templates/stack/files/staging.yaml.jinja @@ -0,0 +1,9 @@ +{%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} +# Generated from plexus-ms/tooling, templates/stack, once: the environment `staging` of this stack (PLX-Stack), its own from then on. +# Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. +host: host.example.com +{%- if names %} +hostname: {{ names[0] }}.staging.example.com +{%- endif %} +env: {} +secrets: {} diff --git a/templates/stack/template.yml b/templates/stack/template.yml index d679d0f3..d97f5e98 100644 --- a/templates/stack/template.yml +++ b/templates/stack/template.yml @@ -1,5 +1,6 @@ # One stack (PLX-Stack), rendered at stack/ in a repo with one stack and at stacks// in a repo with several: -# its compose file and its marker. Its name is its directory's, or at stack/ the repo's, so no question asks it. +# its compose file, its marker and the file of each environment the branches deploy today. +# Its name is its directory's, or at stack/ the repo's, so no question asks it. name: stack # The enclosing repo's answer; whoever renders the stack passes it. @@ -46,7 +47,11 @@ questions: ghcr.io/acme: lowercase letters, digits, ., _, - and :, in two or more parts parted by /{% endif %} policies: - # Both files are the stack's own from birth and never re-synced: the services of the compose file are the - # person's, the marker's body is the stack's prose, and its frontmatter is plx's. + # Every file is the stack's own from birth and never re-synced: the services of the compose file are the + # person's, the marker's body is the stack's prose, its frontmatter is plx's, and an environment's file holds the + # person's host, values and pointers. An update never adds an environment's file to a stack that was born without + # it: the files are birth-only. PLEXUS.md.jinja: born-once compose.yaml.jinja: born-once + production.yaml.jinja: birth-only + staging.yaml.jinja: birth-only diff --git a/tests/all-roles.yml b/tests/all-roles.yml index 3158898c..f4b55397 100644 --- a/tests/all-roles.yml +++ b/tests/all-roles.yml @@ -20,9 +20,7 @@ - plexus.infrastructure.haproxy - plexus.infrastructure.pbs - plexus.infrastructure.proxmox - - plexus.platform.apps - plexus.platform.caddy - plexus.platform.deploy_user - plexus.platform.ingress - - plexus.platform.secrets - plexus.platform.stack diff --git a/tests/host-image.sh b/tests/host-image.sh new file mode 100644 index 00000000..3091101b --- /dev/null +++ b/tests/host-image.sh @@ -0,0 +1,44 @@ +# Sourced by the tests of plexus.platform's two playbooks (platform-playbook.sh, +# stack-playbook.sh): the image of a host they run the playbooks against, a +# container of this machine's Docker daemon. Debian with systemd, sudo, curl +# and Python with PyYAML; Caddy's binary and unit as its package installs them, +# without a site, so that it listens on nothing but its admin endpoint until +# the platform playbook configures it; and Docker's CLI with its compose +# plugin, which a test without a daemon for the host replaces by a stand-in. +# +# host_image : builds it, its output in $work/build; fails where debian:13, +# caddy:2, docker:29-cli or Debian's packages are not to be had. +host_image() { + mkdir -p "$work/image" + cat >"$work/image/Dockerfile" <<'EOF' +FROM caddy:2 AS caddy +FROM docker:29-cli AS docker +FROM debian:13 +RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ + systemd systemd-sysv python3 python3-yaml sudo curl >/dev/null && rm -rf /var/lib/apt/lists/* +COPY --from=caddy /usr/bin/caddy /usr/bin/caddy +COPY --from=docker /usr/local/bin/docker /usr/local/bin/docker +COPY --from=docker /usr/local/libexec/docker/cli-plugins/docker-compose /usr/local/libexec/docker/cli-plugins/docker-compose +COPY caddy.service /etc/systemd/system/caddy.service +RUN useradd --system --home-dir /var/lib/caddy --create-home --shell /usr/sbin/nologin caddy \ + && mkdir /etc/caddy && printf '# The package default, without its site.\n' >/etc/caddy/Caddyfile \ + && systemctl enable caddy +CMD ["sh", "-c", "mount -o remount,rw /sys/fs/cgroup && exec /sbin/init"] +EOF + # The unit of Caddy's Debian package, without its sandboxing. + cat >"$work/image/caddy.service" <<'EOF' +[Unit] +Description=Caddy +After=network.target +[Service] +Type=notify +User=caddy +Group=caddy +ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile +ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force +TimeoutStopSec=5s +[Install] +WantedBy=multi-user.target +EOF + docker build -q -t "$1" "$work/image" >"$work/build" 2>&1 +} diff --git a/tests/platform-playbook.sh b/tests/platform-playbook.sh new file mode 100755 index 00000000..90af74b8 --- /dev/null +++ b/tests/platform-playbook.sh @@ -0,0 +1,316 @@ +#!/usr/bin/env bash +# The platform playbook (plexus.platform.playbook) against hosts that are +# containers of this machine's Docker daemon (the image of host-image.sh), +# reached by Ansible's docker connection. It runs the platform layer's roles +# (--tags platform) but caddy, whose apt repository would need the network on +# every run, and reads users, directories, sudo rules, the proxy's routes as +# curl on the host gets them, and the files of a deployment. A host's `docker` +# is a stand-in that records its arguments, so that a run that starts or +# re-creates nothing can be seen to: the hosts have no Docker daemon of their +# own. +# +# Run by `mise test` (its task test-ansible), beside the stack playbook's +# test. It needs a Docker daemon that lets a container run systemd (the +# capability SYS_ADMIN, AppArmor unconfined, a cgroup namespace of its own), +# and the network once for debian:13, caddy:2, docker:29-cli and Debian's +# packages; where either is missing, it says so and passes. Every container +# and image it creates is named plxplatform-…, publishes no port, and is +# removed when it ends, whether a case failed or not. +set -euo pipefail +cd "$(dirname "$0")/.." + +if ! docker info >/dev/null 2>&1; then + echo "platform-playbook: no Docker daemon reachable; skipped" + exit 0 +fi + +run=plxplatform-$$ +work=$(mktemp -d) + +cleanup() { + docker ps -a --format '{{.Names}}' | grep "^$run" | xargs -r docker rm -f -v >/dev/null || true + docker image rm "$run:host" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT +trap 'exit 130' INT TERM HUP + +fail() { + echo "✗ $case: $*" >&2 + [ ! -f "$work/out" ] || sed 's/^/ /' "$work/out" >&2 + exit 1 +} + +# The host's image (host-image.sh), with a stand-in for docker mounted over +# its CLI in every host. +. tests/host-image.sh +printf '#!/bin/sh\necho "$*" >>/var/log/docker-calls\n' >"$work/docker" +chmod +x "$work/docker" +if ! host_image "$run:host"; then + echo "platform-playbook: the host's image could not be built (debian:13, caddy:2, docker:29-cli or Debian's packages not to be had); skipped" + sed 's/^/ /' "$work/build" + exit 0 +fi + +# host : a host started from the image, booted, with its inventory at +# $work/.yml; the name is the container's, $run-. +host() { + docker run -d --name "$run-$1" --hostname "$1" --cgroupns=private --cap-add SYS_ADMIN \ + --security-opt apparmor=unconfined --tmpfs /run --tmpfs /run/lock -e container=docker \ + -v "$work/docker:/usr/local/bin/docker:ro" "$run:host" >/dev/null + if ! timeout 60 docker exec "$run-$1" systemctl is-system-running --wait >/dev/null 2>&1 && + ! docker exec "$run-$1" systemctl is-active -q caddy 2>/dev/null; then + echo "platform-playbook: systemd does not boot in a container on this Docker daemon; skipped" + exit 0 + fi + cat >"$work/$1.yml" < [arguments]: one run of the platform layer on the host, or of the +# roles $tags names; its exit code in $status, its output in $work/out. +play() { + status=0 + timeout 600 ansible-playbook -i "$work/$1.yml" --tags "${tags:-platform}" --skip-tags caddy "${@:2}" \ + plexus.platform.playbook "$work/out" 2>&1 || status=$? +} + +# on : a command on the host as root; as : as that user. +on() { docker exec "$run-$1" "${@:2}"; } +as() { docker exec -u "$1" "$run-$2" "${@:3}"; } +# get : the status and body of a request the proxy serves on the host. +get() { on "$1" curl -s -m 5 -w ' %{http_code}' -H "Host: $2" "http://127.0.0.1$3" || true; } +# backend : a service on 127.0.0.1: of the host that answers / and /healthz with . +backend() { + on "$1" sh -c "mkdir -p /srv/$2 && printf %s '$3' >/srv/$2/index.html && cp /srv/$2/index.html /srv/$2/healthz" + on "$1" systemd-run -q --unit "backend-$2" python3 -m http.server -b 127.0.0.1 -d "/srv/$2" "$2" + for _ in $(seq 50); do on "$1" curl -s -o /dev/null "http://127.0.0.1:$2/" && return; sleep 0.1; done +} +# snapshot : every file below the paths with owner, mode, size, time and content. +snapshot() { + on "$1" sh -c 'find "$@" -exec stat -c "%n %U:%G %a %s %Y" {} + | sort; find "$@" -type f -exec sha256sum {} + | sort' - "${@:2}" +} + +# fragment : a route fragment, written by the deploy user as the stack playbook writes one. +fragment() { printf '%s\n' "$3" | docker exec -i -u plexus "$run-$1" sh -c "cat >/etc/caddy/stacks/$2"; } + +case='a dry run on a fresh host, before the proxy is installed' +host fresh +# The caddy role, which installs the binary, changes nothing in a dry run. +on fresh mv /usr/bin/caddy /usr/bin/caddy.away +play fresh --check +[ "$status" = 0 ] || fail "exit code $status" +on fresh mv /usr/bin/caddy.away /usr/bin/caddy +echo "✓ $case" + +case='a fresh host' +play fresh +[ "$status" = 0 ] || fail "exit code $status" +! grep -q '"msg": "plexus_apps is no longer read' "$work/out" || fail "a message about plexus_apps" +[ "$(on fresh stat -c '%U:%G %a' /opt/stacks)" = 'plexus:plexus 750' ] || fail "/opt/stacks is not the deploy user's" +as plexus fresh sh -c 'mkdir /opt/stacks/probe && rmdir /opt/stacks/probe' || fail "the deploy user cannot write /opt/stacks" +on fresh test ! -e /etc/caddy/apps.caddy || fail "apps.caddy was written" +fragment fresh shop-staging.caddy 'http://shop.example.com { + respond "from a fragment" +}' +on fresh systemctl reload caddy || fail "the proxy does not reload with a fragment" +[ "$(get fresh shop.example.com /)" = 'from a fragment 200' ] || fail "the fragment's route is not served" +play fresh +[ "$status" = 0 ] || fail "exit code $status, second run" +grep -q '^fresh *: ok=[0-9]* *changed=0 ' "$work/out" || fail "a second run changed something" +echo "✓ $case" + +case='the one sudo rule of the deploy user' +fragment fresh shop-staging.caddy 'http://shop.example.com { + respond "reloaded by the deploy user" +}' +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the deploy user cannot reload the proxy" +[ "$(get fresh shop.example.com /)" = 'reloaded by the deploy user 200' ] || fail "the reload did not take the fragment" +[ "$(as plexus fresh sudo -n -l | grep -c '^ *(')" = 1 ] || fail "the deploy user has more than one rule: $(as plexus fresh sudo -n -l)" +denied() { ! as plexus fresh sudo -n -l "$@" >/dev/null 2>&1 || fail "the deploy user may run sudo $*"; } +denied /usr/bin/systemctl restart caddy +denied /usr/bin/systemctl reload caddy.service +denied /usr/bin/systemctl reload ssh +denied /usr/bin/systemctl reload caddy ssh +denied -u caddy /usr/bin/systemctl reload caddy +denied /bin/sh +on fresh visudo -c >/dev/null || fail "visudo -c finds an error in the host's sudo rules" +echo "✓ $case" + +case="a stack's route: to its port, /healthz refused, a maintenance page while nothing answers" +# A fragment names the hostname and the loopback port, and imports the rest +# from the root configuration: the stack playbook writes no more than that. +backend fresh 20001 'shop staging' +fragment fresh shop-staging.caddy 'http://shop.example.com { + import stack 20001 +}' +fragment fresh shop-preview.caddy 'http://preview.shop.example.com { + import stack 20002 +}' +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload" +[ "$(get fresh shop.example.com /)" = 'shop staging 200' ] || fail "the route does not reach the stack: $(get fresh shop.example.com /)" +[ "$(on fresh curl -s -m 5 http://127.0.0.1:20001/healthz)" = 'shop staging' ] || fail "the stack does not answer /healthz itself" +[ "$(get fresh shop.example.com /healthz)" = ' 403' ] || fail "/healthz is not refused: $(get fresh shop.example.com /healthz)" +[[ $(get fresh preview.shop.example.com /) == *'Back in a minute'*' 503' ]] || fail "no maintenance page where nothing answers" +echo "✓ $case" + +case='a proxy configuration that is invalid on disk' +# Two fragments serve one hostname; the root Caddyfile does not change. +fragment fresh shop-twice.caddy 'http://shop.example.com { + import stack 20001 +}' +# refused: the run failed with what Caddy says, and the play after the +# platform's, the lock-down, still ran on the host. Of that play the container +# runs only its facts (the test runs the platform layer alone), which show +# that the host was not dropped from it. +refused() { + [ "$status" != 0 ] || fail "exit code 0" + grep -q '"msg": "[^"]*ambiguous site definition: http://shop.example.com' "$work/out" || fail "the run does not say what Caddy says" + sed -n '/^PLAY \[Lock down the platform hosts\]/,/^PLAY /p' "$work/out" | grep -q '^ok: \[fresh\]' || + fail "the lock-down play did not run on the host" +} +play fresh +refused +# The same where the root changes: its own validation reads the fragments too. +root=$(on fresh sha256sum /etc/caddy/Caddyfile) +play fresh -e ingress_maintenance_title=Gone +refused +[ "$(on fresh sha256sum /etc/caddy/Caddyfile)" = "$root" ] || fail "the root Caddyfile was replaced" +as plexus fresh rm /etc/caddy/stacks/shop-twice.caddy +play fresh +[ "$status" = 0 ] || fail "exit code $status once the configuration is valid again" +echo "✓ $case" + +case='an invalid sudo rule or root configuration does not land' +before=$(snapshot fresh /etc/sudoers.d /etc/caddy/Caddyfile) +# failed : the run failed at the task of ingress named , which refused what it would have written. +failed() { + [ "$status" != 0 ] || fail "exit code 0" + grep -A2 "^TASK \[plexus.platform.ingress : $1" "$work/out" | grep -q 'failed to validate' || fail "'$1' did not refuse it" +} +tags=ingress play fresh -e '{"plexus_deploy_user": "ex ample"}' +failed 'Let the deploy user reload the proxy' +play fresh -e '{"ingress_trusted_proxies": ["not-a-cidr"]}' +failed 'Write the root Caddyfile' +[ "$(snapshot fresh /etc/sudoers.d /etc/caddy/Caddyfile)" = "$before" ] || fail "a sudo rule or the root Caddyfile changed" +on fresh visudo -c >/dev/null || fail "visudo -c finds an error in the host's sudo rules" +as plexus fresh sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload" +[ "$(get fresh shop.example.com /)" = 'shop staging 200' ] || fail "the route is no longer served" +echo "✓ $case" + +case='a deploy root set to another path' +play fresh -e plexus_deploy_root=/srv/stacks +[ "$status" = 0 ] || fail "exit code $status" +message=$(sed -n 's/^ *"msg": "\(plexus_deploy_root is no longer read.*\)"$/\1/p' "$work/out") +[ -n "$message" ] || fail "no message that plexus_deploy_root is no longer read" +for point in '/opt/stacks on every host' 'under /srv/stacks is not seen by the stack playbook'; do + grep -qF -- "$point" <<<"$message" || fail "the message does not say: $point" +done +on fresh test ! -e /srv/stacks || fail "/srv/stacks was created" +# The value the operations template renders. +play fresh -e plexus_deploy_root=/opt/stacks +[ "$status" = 0 ] || fail "exit code $status" +! grep -q '"msg": "plexus_deploy_root is no longer read' "$work/out" || fail "a message for /opt/stacks" +echo "✓ $case" + +case='a host that carries deployments of an earlier version' +host migrated +# As the earlier platform playbook left it: the deployment's directory with its +# files, the routes rendered from the records into apps.caddy, the root +# configuration importing them, and the deployment answering on its port. +on migrated useradd --create-home --shell /bin/bash plexus +on migrated sh -c 'mkdir -p /opt/stacks/shop-production && cd /opt/stacks/shop-production && + printf "COMPOSE_PROJECT_NAME=shop-production\nPLEXUS_LOOPBACK_PORT=3001\nSHOP_URL=https://shop.example.com\n" >.env && + printf "DB_PASSWORD=secret\n" >.env.secret && + printf "services:\n web:\n image: ghcr.io/acme/shop@sha256:%064d\n" 2 >compose.yaml && + printf "services:\n web:\n image: ghcr.io/acme/shop@sha256:%064d\n" 1 >compose.yaml.prev && + chown -R plexus:plexus . && chmod 0750 . && chmod 0640 .env compose.yaml compose.yaml.prev && chmod 0600 .env.secret' +cat >"$work/apps.caddy" <<'EOF' +# Managed by Ansible (plexus.platform.ingress) — one route per app record on this host. +http://shop.example.com { + encode zstd gzip + # shop (production) + + handle { + respond /healthz 403 + reverse_proxy 127.0.0.1:3001 + } +} +EOF +docker cp -q "$work/apps.caddy" "$run-migrated:/etc/caddy/apps.caddy" +on migrated sh -c 'printf "# Managed by Ansible (plexus.platform.ingress).\nimport apps.caddy\n" >/etc/caddy/Caddyfile && systemctl restart caddy' +backend migrated 3001 'shop production' +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the fixture's route does not answer" +# Group variables the operations template renders, and the records the earlier +# version read, with a value that differs from the .env in place and a secret: +# a run that still read them would rewrite both. +cat >>"$work/migrated.yml" <<'EOF' + plexus_up: true + plexus_ghcr_user: "" + plexus_ghcr_token: "" + plexus_apps: + - name: shop + environment: production + host: shop.example.com + loopback_port: 3001 + env: { SHOP_URL: https://www.example.com } + secrets: { DB_PASSWORD: op://acme/shop/db } +EOF +before=$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy) +play migrated +[ "$status" = 0 ] || fail "exit code $status" +message=$(sed -n 's/^ *"msg": "\(plexus_apps is no longer read.*\)"$/\1/p' "$work/out") +[ -n "$message" ] || fail "no message that plexus_apps is no longer read" +# What the host no longer gets from the records, and what it keeps: each point +# by words that only it has. +for point in 'values, secrets, port or route reaches no host' 'rotated secret re-creates no container' \ + 'new record gets no directory' 'keeps running, and keeps deploying'; do + grep -qF -- "$point" <<<"$message" || fail "the message does not say: $point" +done +[ "$(snapshot migrated /opt/stacks/shop-production /etc/caddy/apps.caddy)" = "$before" ] || fail "a deployment's file or apps.caddy changed" +[ -z "$(on migrated cat /var/log/docker-calls 2>/dev/null)" ] || fail "docker was run: $(on migrated cat /var/log/docker-calls)" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers" +on migrated systemctl reload caddy || fail "the proxy does not reload" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the deployment's route no longer answers after a reload" +echo "✓ $case" + +case='a host in migration: the old routes beside the fragments' +# A stack's environment gets a fragment while the old routes are still there. +backend migrated 20001 'shop staging' +fragment migrated shop-staging.caddy 'http://staging.shop.example.com { + import stack 20001 +}' +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload with a fragment beside the old routes" +[ "$(get migrated staging.shop.example.com /)" = 'shop staging 200' ] || fail "the fragment's route is not served" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the old route is no longer served" +# A fragment for a hostname the old routes still serve: the proxy refuses the +# configuration and goes on serving the old route. +backend migrated 20002 'shop production, by its fragment' +fragment migrated shop-production.caddy 'http://shop.example.com { + import stack 20002 +}' +! as plexus migrated sudo -n /usr/bin/systemctl reload caddy 2>/dev/null || fail "the proxy took one hostname twice" +[ "$(get migrated shop.example.com /)" = 'shop production 200' ] || fail "the old route is no longer served after a refused reload" +# The person's step: the hostname's block out of apps.caddy; the next reload +# moves the hostname to its fragment. +on migrated sed -i '/^http:\/\/shop\.example\.com {$/,/^}$/d' /etc/caddy/apps.caddy +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once the old route is out" +[ "$(get migrated shop.example.com /)" = 'shop production, by its fragment 200' ] || fail "the hostname did not move to its fragment" +# Once every route has its fragment, apps.caddy goes; reloads go on working, +# before and after the next run of the platform playbook. +on migrated rm /etc/caddy/apps.caddy +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once apps.caddy is gone" +play migrated +[ "$status" = 0 ] || fail "exit code $status" +on migrated test ! -e /etc/caddy/apps.caddy || fail "apps.caddy was written" +as plexus migrated sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload after the platform playbook" +[ "$(get migrated shop.example.com /)" = 'shop production, by its fragment 200' ] || fail "the route is not served" +[ "$(get migrated staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route is not served" +echo "✓ $case" diff --git a/tests/stack-playbook.sh b/tests/stack-playbook.sh index b5844a79..c06fcc58 100755 --- a/tests/stack-playbook.sh +++ b/tests/stack-playbook.sh @@ -1,17 +1,31 @@ #!/usr/bin/env bash # The stack playbook (plexus.platform.stack) against the Docker daemon of this -# machine: ansible-playbook on localhost with a local connection, a scratch -# directory in place of /opt/stacks, and a stack of two images built here -# (web and worker, busybox with a line or two) and a service `migrate`, every -# image pinned by digest from a throwaway registry on 127.0.0.1. Each case -# runs the playbook as `plx deploy` would and reads its last line, the -# containers and the files in the environment's directory. +# machine, in two parts. The first runs ansible-playbook with a local +# connection, a scratch directory in place of /opt/stacks, and environments +# without a hostname, for a stack of two images built here (web and worker, +# busybox with a line or two) and a service `migrate`, every image pinned by +# digest from a throwaway registry on 127.0.0.1. The second runs it against a +# host the platform playbook prepared, for environments with a hostname: their +# ports, their routes and the proxy. Each case runs the playbook as `plx +# deploy` would, with an environment's file, and reads its last line, the +# containers and the files in the environment's directory. The vault's CLI is +# a stand-in on the PATH that reads $work/vault. +# +# The prepared host is a container of the image of host-image.sh, booted with +# systemd, in this machine's network, so that its proxy reaches the loopback +# ports the stack's containers publish here, and with this daemon's socket, +# through which the deploy user's Compose starts them. Its proxy listens on +# 127.0.0.1 alone, on ports of the run's own, and issues certificates from its +# own CA; the environments take their ports from ten free ports of the run's +# own. # # Run by `mise test` (its task test-ansible), on every push by the hook and # in CI: it tests the playbook beside its source and needs no build, which is # `test`'s and not `e2e`'s (§ 3 PLX-Repo). It needs a Docker daemon, and the # network once for busybox:1.37 and registry:2; where no daemon answers, or -# an image is neither here nor to be pulled, it says so and passes. +# an image is neither here nor to be pulled, it says so and passes. The second +# part needs what platform-playbook.sh needs, and the daemon's socket at +# /var/run/docker.sock; where it cannot run, it says so and passes. # Everything it creates is named plxstack-… (the registry's image # references carry 127.0.0.1:/ before it), publishes on 127.0.0.1 only, # and is removed when it ends, whether a case failed or not. @@ -35,9 +49,10 @@ done run=plxstack-$$ work=$(mktemp -d) stacks=$work/stacks +mkdir -p "$stacks" "$work/env" "$work/vault" "$work/bin" # Every container, network, volume and image of this run, the registry's -# among them, whatever happened. +# and the prepared host's among them, whatever happened. cleanup() { docker ps -a --format '{{.Names}}' | grep "^$run" | xargs -r docker rm -f -v >/dev/null || true docker network ls --format '{{.Name}}' | grep "^$run" | xargs -r docker network rm >/dev/null || true @@ -45,6 +60,7 @@ cleanup() { # By reference, never by id: a run beside this one may have built the same image. docker image ls --digests --format '{{.Repository}}:{{.Tag}} {{.Repository}}@{{.Digest}}' | grep "/$run-" | tr ' ' '\n' | grep -v '$' | xargs -r docker image rm >/dev/null 2>&1 || true + docker image rm "$run:host" >/dev/null 2>&1 || true rm -rf "$work" } trap cleanup EXIT @@ -56,6 +72,21 @@ fail() { exit 1 } +# The vault's CLI as the playbook calls it: `op read --no-newline op://` +# prints the file $work/vault/ as it is; a path ending in /locked waits, +# as op does for an unlock nobody answers. +cat >"$work/bin/op" <<'EOF' +#!/bin/sh +[ "$1 $2" = 'read --no-newline' ] || { echo "op: the stand-in reads, with --no-newline, and does not $*" >&2; exit 2; } +case $3 in */locked) exec sleep 599 ;; esac +[ -f "$VAULT/${3#op://}" ] || { echo "[ERROR] could not read secret '$3': no such item" >&2; exit 1; } +cat "$VAULT/${3#op://}" +EOF +chmod +x "$work/bin/op" +export VAULT=$work/vault PATH=$work/bin:$PATH +# secret : the value the vault holds at the pointer. +secret() { mkdir -p "$(dirname "$VAULT/${1#op://}")" && printf '%s' "$2" >"$VAULT/${1#op://}"; } + # The registry the images are pinned from, its storage an anonymous volume. docker run -d --rm --name "$run-registry" -p 127.0.0.1::5000 registry:2 >/dev/null port=$(docker port "$run-registry" 5000/tcp | head -1 | sed 's/.*://') @@ -81,10 +112,10 @@ worker=$(image worker:v1 "$worker_dockerfile") # compose [migrate's shell command]: the stack's rendered compose # file. migrate adds a line to /data/migrated in the shared volume; web turns # healthy once there is one, and never where its image says it is broken or -# its environment HEALTH=bad (it loads .env); worker has no healthcheck. -# $web_more and $migrate_more are lines added to the two services. Without -# them nothing orders migrate or puts it behind a profile, the shape that makes -# a plain `up --wait` fail. +# its environment HEALTH=bad (it loads .env and .env.secret); worker has no +# healthcheck and loads neither. $web_more and $migrate_more are lines added +# to the two services. Without them nothing orders migrate or puts it behind +# a profile, the shape that makes a plain `up --wait` fail. compose() { cat <: its directory and .env, as the platform playbook lays them out. +# environment […]: the environment's file, $work/env/.yaml, +# its host this machine, and the lines given after `host`. environment() { - mkdir -p "$stacks/$run-shop-$1" - printf 'COMPOSE_PROJECT_NAME=%s\n' "$run-shop-$1" >"$stacks/$run-shop-$1/.env" + { echo 'host: localhost'; printf '%s\n' "${@:2}"; } >"$work/env/$1.yaml" } # deploy [arguments]: one run of the playbook, for -# the stack $stack (default $run-shop); its exit code in $status, its last -# line in $line. +# the stack $stack (default $run-shop) and the environment's file $envfile +# (default $work/env/.yaml), on this machine; its exit code in +# $status, its last line in $line. deploy() { status=0 - ansible-playbook -i localhost, -c local -e ansible_python_interpreter=auto_silent \ - -e stack_name="${stack:-$run-shop}" -e stack_environment="$1" -e stack_compose_file="$2" -e stack_root="$stacks" \ - "${@:3}" plexus.platform.stack "$work/out" 2>&1 || status=$? + ansible-playbook -c local -e ansible_python_interpreter=auto_silent \ + -e stack_name="${stack:-$run-shop}" -e stack_environment_file="${envfile:-$work/env/$1.yaml}" -e stack_compose_file="$2" \ + -e stack_root="$stacks" "${@:3}" plexus.platform.stack "$work/out" 2>&1 || status=$? line=$(sed -n 's/^ *"msg": "\(.*\)"$/\1/p' "$work/out" | tail -1) } @@ -134,6 +169,8 @@ deploy() { container() { docker ps -q --filter "label=com.docker.compose.project=$run-shop-$1" --filter "label=com.docker.compose.service=$2"; } image_of() { docker inspect --format '{{.Config.Image}}' "$(container "$1" "$2")"; } health_of() { docker inspect --format '{{.State.Health.Status}}' "$(container "$1" "$2")"; } +# The value of a variable in the container of web in an environment, as the process sees it. +value_of() { docker exec "$(container "$1" web)" sh -c "printf %s \"\$$2\""; } # How often migrate has run in an environment, read from its volume. migrations() { docker run --rm --name "$run-probe" -v "$run-shop-$1_data:/data" busybox:1.37 sh -c 'cat /data/migrated 2>/dev/null' | wc -l @@ -145,6 +182,10 @@ compose "$web_v1" >"$work/v1.yaml" deploy staging "$work/v1.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(stat -c %a "$stacks/$run-shop-staging")" = 750 ] || fail "the directory is not 0750" +[ "$(cat "$stacks/$run-shop-staging/.env")" = "COMPOSE_PROJECT_NAME=\"$run-shop-staging\"" ] || + fail ".env: $(cat "$stacks/$run-shop-staging/.env")" +[ ! -e "$stacks/$run-shop-staging/.env.secret" ] || fail ".env.secret was written for an environment without secrets" [ "$(image_of staging web)" = "$web_v1" ] || fail "web does not run $web_v1" [ "$(health_of staging web)" = healthy ] || fail "web is not healthy" [ "$(image_of staging worker)" = "$worker" ] || fail "worker does not run $worker" @@ -164,6 +205,7 @@ deploy staging "$work/v2.yaml" [ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" cmp -s "$work/v1.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail "compose.yaml.prev is not the file deployed before" +[ ! -e "$stacks/$run-shop-staging/.env.prev" ] || fail ".env.prev was written, though .env did not change" echo "✓ $case" case='a deploy whose healthcheck fails' @@ -207,6 +249,7 @@ deploy preview "$work/broken.yaml" [[ $line == "$run-shop-preview: failed: "*unhealthy* ]] || fail "last line: $line" [ -z "$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-preview")" ] || fail "containers left running" [ ! -e "$stacks/$run-shop-preview/compose.yaml" ] || fail "compose.yaml left in place" +[ -f "$stacks/$run-shop-preview/.env" ] || fail ".env was removed" echo "✓ $case" case='a deploy in which nothing changed' @@ -214,20 +257,39 @@ web_id=$(container staging web) worker_id=$(container staging worker) deploy staging "$work/v2.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: unchanged" ] || fail "last line: $line" -grep -q 'localhost *: ok=[0-9]* *changed=0 ' "$work/out" || fail "a task reported a change" +! grep -q 'changed=[1-9]' "$work/out" || fail "a task reported a change" [ "$(container staging web)" = "$web_id" ] || fail "web was re-created" [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" echo "✓ $case" -case='an environment without its directory, then without .env' -deploy qa "$work/v1.yaml" -[ "$status" != 0 ] || fail "exit code 0" -[[ $line == "$run-shop-qa: failed: "*"$stacks/$run-shop-qa is not there"* ]] || fail "last line: $line" -mkdir "$stacks/$run-shop-qa" -deploy qa "$work/v1.yaml" -[ "$status" != 0 ] || fail "exit code 0" -[[ $line == "$run-shop-qa: failed: "*"$stacks/$run-shop-qa/.env is not there"* ]] || fail "last line: $line" -[ ! -e "$stacks/$run-shop-qa/compose.yaml" ] || fail "compose.yaml was written" +case="an environment's file the playbook cannot write" +# Each refused before anything is written: no directory for qa. +for file in 'hostname: qa.example.com' 'host: -oProxyCommand=x' 'host: localhost +env: {PORT: 3000}' 'host: localhost +secrets: {TOKEN: plain}' 'host: localhost +hostname: "qa.example.com {"' 'host: localhost +env: {PLEXUS_LOOPBACK_PORT: "3000"}' 'host: localhost +env: {TOKEN: a} +secrets: {TOKEN: op://acme/shop/qa/token}' 'host: localhost +domain: qa.example.com' '- host: localhost' 'host: "localhost\n"' 'host: localhost +hostname: "qa.example.com\n"'; do + printf '%s\n' "$file" >"$work/env/qa.yaml" + deploy qa "$work/v1.yaml" + [ "$status" != 0 ] || fail "$file: exit code 0" + [[ $line == "$run-shop-qa: failed: 'Check the environment's file' failed: $work/env/qa.yaml is not an environment"* ]] || + fail "$file: last line: $line" + [ ! -e "$stacks/$run-shop-qa" ] || fail "$file: the directory was laid out" +done +echo "✓ $case" + +case='a run narrowed by --limit, --tags or --skip-tags' +# Each would leave out the deploy, or the line that says how it ended. +for narrowed in '--limit localhost' '--tags deploy' '--skip-tags deploy'; do + deploy staging "$work/v2.yaml" $narrowed + [ "$status" != 0 ] || fail "$narrowed: exit code 0" + [ "$line" = "the stack: failed: 'Check the arguments' failed: the stack playbook takes no --limit, --tags or --skip-tags; it deploys the environment's file whole" ] || + fail "$narrowed: last line: $line" +done echo "✓ $case" case='a dry run (--check)' @@ -243,6 +305,11 @@ cmp -s "$work/prev.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail " [ "$(container staging worker)" = "$worker_id" ] || fail "worker was re-created" ! sed -n '/Pull the images\]/,/^$/p; /Bring the stack up\]/,/^$/p' "$work/out" | grep -q '^\(ok\|changed\|included\):' || fail "a Compose task ran" +# A new environment: nothing laid out. +environment draft +deploy draft "$work/v1.yaml" --check --diff +[ "$line" = "$run-shop-draft: would deploy" ] || fail "a new environment: last line: $line" +[ ! -e "$stacks/$run-shop-draft" ] || fail "a new environment: the directory was laid out" echo "✓ $case" case='a stack whose only service is migrate' @@ -322,24 +389,132 @@ deploy staging "$work/no-worker.yaml" [ "$(container staging web)" = "$web_id" ] || fail "web was re-created" echo "✓ $case" -case='a change of .env alone' +case='a change of a value alone' web_id=$(container staging web) -printf 'GREETING=hello\n' >>"$stacks/$run-shop-staging/.env" +cp "$stacks/$run-shop-staging/.env" "$work/env-before" +environment staging 'env:' ' GREETING: hello' deploy staging "$work/no-worker.yaml" [ "$status" = 0 ] || fail "exit code $status" [ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" [ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" +[ "$(value_of staging GREETING)" = hello ] || fail "web does not see GREETING=hello" [ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +cmp -s "$work/env-before" "$stacks/$run-shop-staging/.env.prev" || fail ".env.prev is not the .env deployed before" echo "✓ $case" -case='a deploy of the file in place that fails' -cp "$stacks/$run-shop-staging/compose.yaml.prev" "$work/prev.yaml" -printf 'HEALTH=bad\n' >>"$stacks/$run-shop-staging/.env" +case='values and secrets reach the containers as written, and no secret reaches the output' +# A value that a shell, Compose and Ansible would each read otherwise, and a +# secret of two lines, with a newline at its end, as a key in the vault has. +value='a $HOME ${GREETING} "q" '\''s'\'' back\slash #x {{ lookup('\''pipe'\'', '\''id'\'') }}' +password=$'pa$$ "w0rd" \\n\n2nd-line-of-the-secret\n' +secret op://acme/shop/staging/password "$password" +secret op://acme/shop/staging/token 'token-of-the-secret' +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +leaks() { grep -c -e 2nd-line-of-the-secret -e token-of-the-secret -e 'w0rd' "$work/out" || true; } +deploy staging "$work/no-worker.yaml" -v +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run with -v" +[ "$(value_of staging ODD)" = "$value" ] || fail "ODD is $(value_of staging ODD)" +[ "$(value_of staging DB_PASSWORD)" = "${password%$'\n'}" ] || fail "DB_PASSWORD is $(value_of staging DB_PASSWORD)" +docker exec "$(container staging web)" sh -c 'printf %s "$DB_PASSWORD"' | cmp -s - "$VAULT/acme/shop/staging/password" || + fail "DB_PASSWORD is not the vault's value to its last byte" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret")" = 600 ] || fail ".env.secret is not 0600" +! grep -q -e w0rd -e token-of-the-secret "$stacks/$run-shop-staging/.env" || fail "a secret is in .env" +secret op://acme/shop/staging/token 'token-of-the-secret, rotated' +deploy staging "$work/no-worker.yaml" --check --diff -v +[ "$line" = "$run-shop-staging: would deploy" ] || fail "a rotated secret in a dry run: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a dry run with --diff -v" +deploy staging "$work/no-worker.yaml" -v +[ "$line" = "$run-shop-staging: deployed" ] || fail "a rotated secret: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run that rotates one" +[ "$(value_of staging API_TOKEN)" = 'token-of-the-secret, rotated' ] || fail "the rotated secret did not reach web" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret.prev")" = 600 ] || fail ".env.secret.prev is not 0600" +deploy staging "$work/no-worker.yaml" -v +[ "$line" = "$run-shop-staging: unchanged" ] || fail "run again: last line: $line" +[ "$(leaks)" = 0 ] || fail "a secret is in the output of a run that changes nothing" +echo "✓ $case" + +case='a changed value that breaks the healthcheck, beside a rotated secret' +web_id=$(container staging web) +for file in .env .env.secret compose.yaml; do cp "$stacks/$run-shop-staging/$file" "$work/before$file"; done +secret op://acme/shop/staging/token 'token-of-the-secret, rotated twice' +environment staging 'env:' ' GREETING: hello' ' HEALTH: bad' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: rolled back: "*unhealthy* ]] || fail "last line: $line" +for file in .env .env.secret compose.yaml; do + cmp -s "$work/before$file" "$stacks/$run-shop-staging/$file" || fail "$file is not the one before" +done +[ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +[ -z "$(value_of staging HEALTH)" ] || fail "web runs with HEALTH=$(value_of staging HEALTH)" +[ "$(value_of staging API_TOKEN)" = 'token-of-the-secret, rotated' ] || fail "web runs with the new secret" +[ "$(image_of staging web)" = "$web_v2" ] || fail "web does not run $web_v2" +echo "✓ $case" + +case='a secret that cannot be read, is empty, or does not answer' +snapshot() { find "$stacks/$run-shop-staging" -type f -exec sha256sum {} + | sort; } +before=$(snapshot) +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/missing' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the secret DB_PASSWORD (op://acme/shop/staging/missing) could not be read: "*"no such item" ]] || + fail "last line: $line" +[ "$(snapshot)" = "$before" ] || fail "a file of the environment changed" +secret op://acme/shop/staging/empty '' +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/empty' +deploy staging "$work/no-worker.yaml" +[ "$status" != 0 ] || fail "an empty secret: exit code 0" +[ "$line" = "$run-shop-staging: failed: 'Check that every secret was read' failed: the secret DB_PASSWORD (op://acme/shop/staging/empty) is empty in the vault" ] || + fail "an empty secret: last line: $line" +[ "$(snapshot)" = "$before" ] || fail "an empty secret: a file of the environment changed" +environment staging 'env:' ' GREETING: hello' 'secrets:' ' DB_PASSWORD: op://acme/shop/staging/locked' +deploy staging "$work/no-worker.yaml" -e stack_secret_timeout=2 +[ "$status" != 0 ] || fail "a read that does not answer: exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the secret DB_PASSWORD (op://acme/shop/staging/locked) could not be read: op read did not answer within 2 seconds"*unlock* ]] || + fail "a read that does not answer: last line: $line" +[ "$(snapshot)" = "$before" ] || fail "a read that does not answer: a file of the environment changed" +! pgrep -f 'sleep 599' >/dev/null || fail "the read that did not answer is still running" +echo "✓ $case" + +case='a deploy of the files in place that fails' +# Nothing the playbook writes changes; web's data is broken by hand and web +# stopped, so that up starts it again and it never turns healthy. +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" 'secrets:' \ + ' DB_PASSWORD: op://acme/shop/staging/password' ' API_TOKEN: op://acme/shop/staging/token' +secret op://acme/shop/staging/token 'token-of-the-secret, rotated' +before=$(snapshot) +docker exec "$(container staging web)" rm /data/migrated +docker stop -t 1 "$(container staging web)" >/dev/null deploy staging "$work/no-worker.yaml" [ "$status" != 0 ] || fail "exit code 0" [[ $line == "$run-shop-staging: failed: "*unhealthy* ]] || fail "last line: $line" -cmp -s "$work/no-worker.yaml" "$stacks/$run-shop-staging/compose.yaml" || fail "compose.yaml was changed" -cmp -s "$work/prev.yaml" "$stacks/$run-shop-staging/compose.yaml.prev" || fail "compose.yaml.prev was changed" +[ "$(snapshot)" = "$before" ] || fail "a file of the environment changed" +docker run --rm --name "$run-probe" -v "$run-shop-staging_data:/data" busybox:1.37 sh -c 'echo ran >> /data/migrated' +echo "✓ $case" + +case='an environment whose secrets are all dropped' +# .env.secret stays, empty: the services that loaded it are re-created without +# the values. +web_id=$(container staging web) +environment staging 'env:' ' GREETING: hello' " ODD: '${value//\'/\'\'}'" +deploy staging "$work/no-worker.yaml" --check --diff +[ "$status" = 0 ] || fail "a dry run: exit code $status" +[ "$line" = "$run-shop-staging: would deploy" ] || fail "a dry run: last line: $line" +deploy staging "$work/no-worker.yaml" +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ -f "$stacks/$run-shop-staging/.env.secret" ] && [ ! -s "$stacks/$run-shop-staging/.env.secret" ] || fail ".env.secret is not there and empty" +[ "$(stat -c %a "$stacks/$run-shop-staging/.env.secret")" = 600 ] || fail ".env.secret is not 0600" +[ "$(container staging web)" != "$web_id" ] || fail "web was not re-created" +[ -z "$(value_of staging API_TOKEN)" ] || fail "web still sees API_TOKEN" +[ "$(health_of staging web)" = healthy ] || fail "web is not healthy" +deploy staging "$work/no-worker.yaml" +[ "$line" = "$run-shop-staging: unchanged" ] || fail "run again: last line: $line" +deploy staging "$work/no-worker.yaml" --check +[ "$line" = "$run-shop-staging: unchanged" ] || fail "a dry run, run again: last line: $line" echo "✓ $case" case='a first deploy whose migrate fails, beside a container of the project' @@ -356,24 +531,29 @@ echo "✓ $case" case='invalid variables' cp "$stacks/$run-shop-staging/compose.yaml" "$work/in-place.yaml" -deploy staging "$work/v1.yaml" -i 127.0.0.1, -[ "$status" != 0 ] || fail "two hosts: exit code 0" -[[ $line == "the stack: failed: "* ]] || fail "two hosts: last line: $line" deploy staging '' [ "$status" != 0 ] || fail "no compose file: exit code 0" [[ $line == "the stack: failed: "* ]] || fail "no compose file: last line: $line" +deploy nowhere "$work/v1.yaml" +[ "$status" != 0 ] || fail "no environment's file: exit code 0" +[[ $line == "$run-shop-nowhere: failed: "* ]] || fail "no environment's file: last line: $line" cmp -s "$work/in-place.yaml" "$stacks/$run-shop-staging/compose.yaml" || fail "compose.yaml was written" echo "✓ $case" case='an invalid stack or environment name' for name in "$run-Shop staging" "$run-shop pre-view" "$run-shop Staging"; do set -- $name - mkdir -p "$stacks/$1-$2" && touch "$stacks/$1-$2/.env" + environment "$2" stack=$1 deploy "$2" "$work/v1.yaml" [ "$status" != 0 ] || fail "$1-$2: exit code 0" [[ $line == "the stack: failed: "* ]] || fail "$1-$2: last line: $line" - [ ! -e "$stacks/$1-$2/compose.yaml" ] || fail "$1-$2: compose.yaml was written" + [ ! -e "$stacks/$1-$2" ] || fail "$1-$2: the directory was laid out" done +environment yml +mv "$work/env/yml.yaml" "$work/env/yml.yml" +envfile=$work/env/yml.yml deploy yml "$work/v1.yaml" +[ "$status" != 0 ] || fail "yml.yml: exit code 0" +[[ $line == "the stack: failed: "* ]] || fail "yml.yml: last line: $line" echo "✓ $case" case='a deploy that leaves no service to start' @@ -402,3 +582,244 @@ if ansible-galaxy collection install --no-deps -p "$work/lowest" "community.dock else echo "stack-playbook: community.docker $lowest could not be fetched from Galaxy; $case skipped" fi + +# The second part, on a host the platform playbook prepared (the header). +. tests/host-image.sh +skip() { echo "stack-playbook: $*; the cases with a hostname skipped"; exit 0; } +[ -S /var/run/docker.sock ] || skip "this daemon's socket is not /var/run/docker.sock" +host_image "$run:host" || { sed 's/^/ /' "$work/build"; skip "the host's image could not be built"; } +# free: a port of this machine that nothing listens on, as the kernel hands one out. +free() { python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; } +admin=$(free) http=$(free) https=$(free) legacy=$(free) +# The environments' ports: ten in a row that nothing listens on, below the kernel's. +for _ in $(seq 50); do + first=$((21000 + RANDOM % 9000)) + [ -n "$(ss -Hltn "sport >= :$first and sport <= :$((first + 9))")" ] || break +done +range=$first-$((first + 9)) + +host=$run-host +mkdir -p "$work/caddy.service.d" +printf '[Service]\nEnvironment=CADDY_ADMIN=127.0.0.1:%s\n' "$admin" >"$work/caddy.service.d/admin.conf" +docker create --name "$host" --network host --cgroupns=private --cap-add SYS_ADMIN --security-opt apparmor=unconfined \ + --tmpfs /run --tmpfs /run/lock -e container=docker -v /var/run/docker.sock:/docker.sock "$run:host" >/dev/null +docker cp -q "$work/caddy.service.d" "$host:/etc/systemd/system/" +docker start "$host" >/dev/null +if ! timeout 60 docker exec "$host" systemctl is-system-running --wait >/dev/null 2>&1 && + ! docker exec "$host" systemctl is-active -q caddy 2>/dev/null; then + skip "systemd does not boot in a container on this Docker daemon" +fi +cat >"$work/host.yml" <: a command on the prepared host as root; as_deploy : as the deploy user. +on() { docker exec "$host" "$@"; } +as_deploy() { docker exec -u plexus "$host" "$@"; } +# get : the body and status of a request the prepared host's proxy serves. +get() { curl -sk -m 5 -w ' %{http_code}' --resolve "$1:$https:127.0.0.1" "https://$1:$https$2" || true; } +# The port an environment's .env holds; how often the proxy was reloaded. +port_of() { on sed -n 's/^PLEXUS_LOOPBACK_PORT="\{0,1\}\([0-9]*\)"\{0,1\}$/\1/p' "/opt/stacks/$1/.env"; } +reloads() { on journalctl -q --no-pager -u caddy | grep -c Reloading || true; } +# Every file of the environments and the routes, with its size and time. +files() { on sh -c 'find /opt/stacks /etc/caddy/stacks -exec stat -c "%n %s %y" {} + | sort'; } + +case='a host the platform playbook prepares' +status=0 +timeout 600 ansible-playbook -i "$work/host.yml" --tags platform --skip-tags caddy plexus.platform.playbook "$work/out" 2>&1 || status=$? +[ "$status" = 0 ] || fail "the platform playbook: exit code $status" +# Beyond what the platform playbook does: this daemon's socket for the deploy +# user, in place of a daemon of the host's own; the proxy on 127.0.0.1 and the +# run's ports, with certificates from its own CA; and a route of an earlier +# version, in /etc/caddy/apps.caddy as a host in migration has it, which the +# root imports as the ingress role writes it where the file is there. +gid=$(stat -c %g /var/run/docker.sock) +on sh -c "ln -s /docker.sock /run/docker.sock && { getent group $gid >/dev/null || groupadd -g $gid docker; } && + usermod -aG \$(getent group $gid | cut -d: -f1) plexus" +on sh -c "printf '{\n\thttp_port $http\n\thttps_port $https\n\tdefault_bind 127.0.0.1\n\tlocal_certs\n\tskip_install_trust\n}\n' | + cat - /etc/caddy/Caddyfile >/etc/caddy/Caddyfile.run && mv /etc/caddy/Caddyfile.run /etc/caddy/Caddyfile" && + printf 'legacy.example.com {\n\trespond "legacy"\n}\n' | docker exec -i "$host" sh -c 'cat >/etc/caddy/apps.caddy' && + on sed -i 's|^import /etc/caddy/stacks/|import /etc/caddy/apps*.caddy\n&|' /etc/caddy/Caddyfile && on systemctl reload caddy || + fail "the proxy does not take the run's ports" +echo "✓ $case" + +# The stack on the prepared host: web serves GREETING on / and turns healthy +# where /healthz answers and HEALTH is not bad. +cat >"$work/site.yaml" </www/index.html && echo ok >/www/healthz && exec httpd -f -p 3000 -h /www"] + env_file: + - path: .env + - path: .env.secret + required: false + ports: ["127.0.0.1:\${PLEXUS_LOOPBACK_PORT:?set by the deploy}:3000"] + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3000/healthz >/dev/null && ! printenv HEALTH | grep -qx bad"] + interval: 1s + retries: 3 +YAML +# site […]: the environment's file, its host the prepared host. +site() { mkdir -p "$work/host/$1"; { echo "host: $host"; printf '%s\n' "${@:3}"; } >"$work/host/$1/$2.yaml"; } +# play_on [arguments]: one run against the +# prepared host; deploy_on [arguments]: the same, with +# $status and $line as deploy sets them. +play_on() { + ansible-playbook -i "$work/host.yml" -e stack_name="$2" -e stack_environment_file="$work/host/$2/$3.yaml" \ + -e stack_compose_file="$work/site.yaml" -e stack_port_range="$range" "${@:4}" plexus.platform.stack "$1" 2>&1 +} +deploy_on() { + status=0 + play_on "$work/out" "$@" || status=$? + line=$(sed -n 's/^ *"msg": "\(.*\)"$/\1/p' "$work/out" | tail -1) +} + +case='a first deploy that takes a port and writes the route' +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging' +deploy_on "$run-shop" staging +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: deployed" ] || fail "last line: $line" +[ "$(on stat -c '%U %a' "/opt/stacks/$run-shop-staging")" = 'plexus 750' ] || fail "the directory is not the deploy user's, 0750" +[ "$(port_of "$run-shop-staging")" = "$first" ] || fail "the port is $(port_of "$run-shop-staging"), not $first" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$(printf 'staging.shop.example.com {\n\timport stack %s\n}' "$first")" ] || + fail "the fragment: $(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route: $(get staging.shop.example.com /)" +[ "$(get staging.shop.example.com /healthz)" = ' 403' ] || fail "/healthz from outside: $(get staging.shop.example.com /healthz)" +echo "✓ $case" + +case='a run in which nothing changed reloads nothing' +before=$(files) reloaded=$(reloads) +web_id=$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-staging") +deploy_on "$run-shop" staging +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-shop-staging: unchanged" ] || fail "last line: $line" +! grep -q 'changed=[1-9]' "$work/out" || fail "a task reported a change" +[ "$(files)" = "$before" ] || fail "a file changed" +[ "$(reloads)" = "$reloaded" ] || fail "the proxy was reloaded" +[ "$(docker ps -q --filter "label=com.docker.compose.project=$run-shop-staging")" = "$web_id" ] || fail "web was re-created" +echo "✓ $case" + +case='two first deploys started at once end with different ports' +site "$run-shop" production 'hostname: shop.example.com' 'env:' ' GREETING: shop production' +site "$run-docs" production 'hostname: docs.example.com' 'env:' ' GREETING: docs production' +play_on "$work/out-shop" "$run-shop" production & +shop=$! +play_on "$work/out-docs" "$run-docs" production & +docs=$! +shop_status=0 docs_status=0 +wait "$shop" || shop_status=$? +wait "$docs" || docs_status=$? +cat "$work/out-shop" "$work/out-docs" >"$work/out" +[ "$shop_status $docs_status" = '0 0' ] || fail "exit codes $shop_status and $docs_status" +ports="$(port_of "$run-shop-production") $(port_of "$run-docs-production")" +[ "$ports" = "$((first + 1)) $((first + 2))" ] || [ "$ports" = "$((first + 2)) $((first + 1))" ] || fail "the ports are $ports" +[ "$(get shop.example.com /)" = 'shop production 200' ] || fail "shop's route: $(get shop.example.com /)" +[ "$(get docs.example.com /)" = 'docs production 200' ] || fail "docs' route: $(get docs.example.com /)" +echo "✓ $case" + +case='a hostname that another environment serves' +site "$run-shop" preview 'hostname: Staging.Shop.example.com' 'env:' ' GREETING: shop preview' +deploy_on "$run-shop" preview +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-preview: failed: "*"staging.shop.example.com is the hostname of $run-shop-staging on this host"* ]] || + fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-shop-preview.caddy" || fail "a fragment was written" +on test ! -e "/opt/stacks/$run-shop-preview" || fail "the directory was laid out" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route of staging: $(get staging.shop.example.com /)" +echo "✓ $case" + +case='a changed value that breaks the healthcheck, its route kept' +env_before=$(on cat "/opt/stacks/$run-shop-staging/.env") +fragment_before=$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy") +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging, changed' ' HEALTH: bad' +deploy_on "$run-shop" staging +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-shop-staging: rolled back: "*unhealthy* ]] || fail "last line: $line" +[ "$(on cat "/opt/stacks/$run-shop-staging/.env")" = "$env_before" ] || fail ".env is not the one before" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$fragment_before" ] || fail "the fragment changed" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "the route: $(get staging.shop.example.com /)" +echo "✓ $case" + +case='a port that a directory holds is kept, outside the range too' +as_deploy sh -c "mkdir /opt/stacks/$run-docs-legacy && + printf 'COMPOSE_PROJECT_NAME=$run-docs-legacy\nPLEXUS_LOOPBACK_PORT=$legacy\n' >/opt/stacks/$run-docs-legacy/.env" +site "$run-docs" legacy 'hostname: legacy.docs.example.com' 'env:' ' GREETING: docs legacy' +deploy_on "$run-docs" legacy +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-legacy: deployed" ] || fail "last line: $line" +[ "$(port_of "$run-docs-legacy")" = "$legacy" ] || fail "the port is $(port_of "$run-docs-legacy"), not $legacy" +[ "$(get legacy.docs.example.com /)" = 'docs legacy 200' ] || fail "the route: $(get legacy.docs.example.com /)" +echo "✓ $case" + +case='no free port' +site "$run-docs" qa 'hostname: qa.docs.example.com' 'env:' ' GREETING: docs qa' +deploy_on "$run-docs" qa -e stack_port_range="$first-$first" +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-docs-qa: failed: "*"no port from $first to $first is free"* ]] || fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-qa.caddy" || fail "a fragment was written" +echo "✓ $case" + +case='a port of the range that something on the host listens on' +docker run -d --rm --name "$run-listener" --network host busybox:1.37 httpd -f -p "127.0.0.1:$((first + 3))" >/dev/null +for _ in $(seq 50); do curl -s -o /dev/null -m 1 "http://127.0.0.1:$((first + 3))/" && break; sleep 0.2; done +site "$run-docs" listened 'hostname: listened.docs.example.com' 'env:' ' GREETING: docs listened' +deploy_on "$run-docs" listened +docker rm -f "$run-listener" >/dev/null +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-listened: deployed" ] || fail "last line: $line" +[ "$(port_of "$run-docs-listened")" = "$((first + 4))" ] || fail "the port is $(port_of "$run-docs-listened"), not $((first + 4))" +[ "$(get listened.docs.example.com /)" = 'docs listened 200' ] || fail "the route: $(get listened.docs.example.com /)" +echo "✓ $case" + +case='a hostname the routes of an earlier version serve' +# The new environment's: refused by the proxy, its fragment gone and nothing +# else written; an environment's fragment that changes to it: put back as it was. +site "$run-docs" older 'hostname: legacy.example.com' 'env:' ' GREETING: docs older' +deploy_on "$run-docs" older +[ "$status" != 0 ] || fail "a new environment: exit code 0" +[[ $line == "$run-docs-older: failed: "*"the proxy refused to reload with the route of legacy.example.com, which is as it was: caddy validate says "*legacy.example.com* ]] || + fail "a new environment: last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-older.caddy" || fail "a new environment: the refused fragment is still there" +on test ! -e "/opt/stacks/$run-docs-older" || fail "a new environment: the directory was laid out" +[ "$(get legacy.example.com /)" = 'legacy 200' ] || fail "the earlier version's route: $(get legacy.example.com /)" +fragment_before=$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy") env_before=$(on cat "/opt/stacks/$run-shop-staging/.env") +site "$run-shop" staging 'hostname: legacy.example.com' 'env:' ' GREETING: shop staging' +deploy_on "$run-shop" staging +[ "$status" != 0 ] || fail "a changed fragment: exit code 0" +[[ $line == "$run-shop-staging: failed: "*"the proxy refused to reload with the route of legacy.example.com, which is as it was: caddy validate says "*legacy.example.com* ]] || + fail "a changed fragment: last line: $line" +[ "$(on cat "/etc/caddy/stacks/$run-shop-staging.caddy")" = "$fragment_before" ] || fail "a changed fragment: it was not put back" +[ "$(on cat "/opt/stacks/$run-shop-staging/.env")" = "$env_before" ] || fail "a changed fragment: .env changed" +[ "$(get staging.shop.example.com /)" = 'shop staging 200' ] || fail "a changed fragment: the route: $(get staging.shop.example.com /)" +site "$run-shop" staging 'hostname: staging.shop.example.com' 'env:' ' GREETING: shop staging' +echo "✓ $case" + +case='a route the proxy refuses' +# A fragment that does not parse, written by hand; Caddy names the file where +# the parse fails, which can be the one after it. +printf 'broken.example.com {\n' | docker exec -i -u plexus "$host" sh -c "cat >/etc/caddy/stacks/$run-broken.caddy" +site "$run-docs" preview 'hostname: preview.docs.example.com' 'env:' ' GREETING: docs preview' +deploy_on "$run-docs" preview +[ "$status" != 0 ] || fail "exit code 0" +[[ $line == "$run-docs-preview: failed: "*"the proxy refused to reload with the route of preview.docs.example.com, which is as it was: caddy validate says adapting config"* ]] || + fail "last line: $line" +on test ! -e "/etc/caddy/stacks/$run-docs-preview.caddy" || fail "the refused fragment is still there" +as_deploy rm "/etc/caddy/stacks/$run-broken.caddy" +as_deploy sudo -n /usr/bin/systemctl reload caddy || fail "the proxy does not reload once the broken fragment is gone" +echo "✓ $case" + +case='a dry run of a new environment with a hostname' +site "$run-docs" beta 'hostname: beta.docs.example.com' 'env:' ' GREETING: docs beta' +before=$(files) reloaded=$(reloads) +deploy_on "$run-docs" beta --check --diff +[ "$status" = 0 ] || fail "exit code $status" +[ "$line" = "$run-docs-beta: would deploy" ] || fail "last line: $line" +[ "$(files)" = "$before" ] || fail "a file changed" +[ "$(reloads)" = "$reloaded" ] || fail "the proxy was reloaded" +echo "✓ $case"