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/deploy_user/defaults/main.yml b/ansible/platform/roles/deploy_user/defaults/main.yml index 250cc6a4..5c634cd8 100644 --- a/ansible/platform/roles/deploy_user/defaults/main.yml +++ b/ansible/platform/roles/deploy_user/defaults/main.yml @@ -1,19 +1,22 @@ --- # 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 /opt/stacks and no variable: it is the path the -# stack contract names for every environment (PLX-Stack/HostDirectory). +# 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 and have no default -# here; set them in the operations repo's group variables: -# plexus_deploy_user the user's name +# 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. deploy_user_groups: [] diff --git a/ansible/platform/roles/deploy_user/tasks/main.yml b/ansible/platform/roles/deploy_user/tasks/main.yml index 7b0af778..ca7e2600 100644 --- a/ansible/platform/roles/deploy_user/tasks/main.yml +++ b/ansible/platform/roles/deploy_user/tasks/main.yml @@ -10,7 +10,7 @@ # Not recursive: what lies below is the stack playbook's. - name: Give the deploy user the deploy root ansible.builtin.file: - path: /opt/stacks + path: "{{ deploy_user_root }}" state: directory owner: "{{ plexus_deploy_user }}" group: "{{ plexus_deploy_user }}" 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/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/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 888a113d..91b68687 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -35,6 +35,7 @@ import { plxNew, put, relock, + STACK_FILE_ENVIRONMENTS, sh, start, tryRun, @@ -55,7 +56,10 @@ const output = (app: string) => join(repo, 'apps', app, '.next', 'standalone'); before(async () => { here = await open('app-nextjs'); - repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); + repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { + tenant: 'acme', + environments: STACK_FILE_ENVIRONMENTS, + }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, 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/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 5f7f96f0..8609b46b 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -55,6 +55,7 @@ import { open, put, relock, + STACK_FILE_ENVIRONMENTS, sh, tryRun, until, @@ -224,7 +225,11 @@ async function newborn( apps: Record, answers: Record = {}, ): Promise { - const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + const dir = await born(join(here, name), ['repo-turbo', 'updates'], { + tenant: 'acme', + environments: STACK_FILE_ENVIRONMENTS, + ...answers, + }); await bornStacks( dir, Object.fromEntries(Object.entries(apps).map(([app, profile]) => [app, { profile, apps: [app] }])), diff --git a/newborns/helpers.ts b/newborns/helpers.ts index cf695d4e..0e0acd5d 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -407,6 +407,13 @@ export async function born( return dir; } +/** + * The `stack` template writes `production.yaml` and `staging.yaml` by name while the repo declares no environment, + * so a newborn with a stack fails `PLX-Stack/FileNamesDeclared`: the repos that must pass the doctor declare the + * two names. The stack template is to render the files from the declaration, which removes this. + */ +export const STACK_FILE_ENVIRONMENTS = '{staging: {promotes_from: main}, production: {promotes_from: staging}}'; + /** * The stacks of a newborn app repo, each created by `plx new` from the template `stack` with its profile and the * apps it runs: at stack/ where one is given, which needs the answer `repo` in the root marker, else each at diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index ec709f46..d1b21b1d 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -38,7 +38,18 @@ import { join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; import { type Caches, startCaches } from './caches.ts'; -import { born, bornStacks, close, freePort, open, put, relock, sh, tryRun } from './helpers.ts'; +import { + born, + bornStacks, + close, + freePort, + open, + put, + relock, + STACK_FILE_ENVIRONMENTS, + sh, + tryRun, +} from './helpers.ts'; import { type Done, gitOk, of, type Step, walk } from './jobs.ts'; const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); @@ -92,7 +103,12 @@ before(async () => { PATH: `${bin}:${process.env.PATH}`, }; - const repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme', repo: 'web', ci_strategy: 'byom' }); + const repo = await born(join(here, 'web'), ['repo-turbo'], { + tenant: 'acme', + repo: 'web', + ci_strategy: 'byom', + environments: STACK_FILE_ENVIRONMENTS, + }); await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web' }); await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); // A second suite of web: the template names a suite's package after its app, so this one is renamed. diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index a482650a..7a508aca 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -28,7 +28,20 @@ import { import { join, relative } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; -import { assertBuilt, born, bornStacks, close, git, mise, open, pass, put, sh, tryRun } from './helpers.ts'; +import { + assertBuilt, + born, + bornStacks, + close, + git, + mise, + open, + pass, + put, + STACK_FILE_ENVIRONMENTS, + sh, + tryRun, +} from './helpers.ts'; let here = ''; before(async () => { @@ -412,7 +425,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 +454,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 +466,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 +476,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: @@ -513,7 +535,10 @@ interface DeployStep { } test('the job deploy of a newborn operations repo deploys two stacks of third-party software through its own steps, and one that fails leaves the other deployed', async () => { - const dir = await born(join(here, 'deploy-job'), ['repo-operations', 'updates'], { tenant: 'acme' }); + const dir = await born(join(here, 'deploy-job'), ['repo-operations', 'updates'], { + tenant: 'acme', + environments: STACK_FILE_ENVIRONMENTS, + }); const root = join(here, 'deploy-run'); const bin = runnerTools(root); const logs = join(root, 'logs'); @@ -521,7 +546,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 +577,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 +605,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 +616,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 +628,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 54b9cb38..67efe16b 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'); @@ -284,6 +293,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 061da900..a087bfcf 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 f7956eab..6d555437 100644 --- a/packages/cli-ci/src/commands/setupWithoutToken.test.ts +++ b/packages/cli-ci/src/commands/setupWithoutToken.test.ts @@ -58,12 +58,18 @@ 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, marker: MARKER }); 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, + marker: MARKER, + }); + 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 c91d0847..57249deb 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -8,7 +8,6 @@ import { describeBranches, detailOf, environmentOf, - isOperationsRepo, orAbsent, type Plan, readDeclaredEnvironments, @@ -57,8 +56,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. */ @@ -102,11 +99,11 @@ async function refuseOnPushWithoutEnvironment(ctx: Context, env: NodeJS.ProcessE * 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, @@ -114,8 +111,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); @@ -155,6 +153,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. @@ -164,13 +167,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') { @@ -193,17 +195,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]), @@ -392,11 +389,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 f59985dd..9de04bc4 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\nenvironments:\n staging:\n promotes_from: main\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 declared branch; where it follows none, the verb says so and names the branches', 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, @@ -386,7 +451,7 @@ test('without --environment the environment follows the declared branch; where i test('a repo that declares no environment deploys from no branch, and a declaration that is invalid is refused with its reason', async () => { const f = fixture(); - const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo]; + const args = ['deploy', '--commit', SHA, '-C', f.repo]; put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), @@ -405,34 +470,27 @@ test('a repo that declares no environment deploys from no branch, and a declarat assert.deepEqual(runs(f.fake), []); }); -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), []); @@ -484,7 +542,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), @@ -506,7 +564,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( @@ -516,25 +574,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); @@ -558,9 +673,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`, @@ -641,8 +756,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) => @@ -670,15 +786,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 () => { @@ -709,7 +826,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(); @@ -963,14 +1080,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 }); @@ -984,7 +1098,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 4adf2b83..57e02f3d 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 a declared env/ branch -// plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180 +// plx deploy --environment staging +// plx deploy # in a job, on a push to a declared env/ branch +// plx deploy -e production -- -e stack_wait_timeout=180 import { resolve } from 'node:path'; import { declarationRefusal, @@ -30,7 +31,6 @@ import { contextOf, version } from '../program.ts'; interface Opts { environment?: string; - inventory?: string; commit?: string; dir: string; } @@ -39,23 +39,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; @@ -72,7 +67,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 2e32f644..9ddd9691 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/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 3d2a2091..beb007b0 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -1,142 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { Context } from './context.ts'; import { declareEnvironments } from './declaredEnvironments.ts'; -import { - deployLegs, - 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 { environmentOf } from './deployTargets.ts'; const DECLARED = declareEnvironments({ staging: { promotes_from: 'main', auto_promote: true }, diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index 64fc919b..aaf4593b 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -1,34 +1,7 @@ -// 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'; +// The environment a branch deploys into (§ 3 PLX-Delivery): `environmentOf` is the one place that says it, +// for `plx` and `plx-ci`, from the environments the repo declares (declaredEnvironments.ts). +// Where a stack goes is not here: it is the `host` of the stack's environment file (environments.ts). import { type DeclaredEnvironments, environmentOfBranch } from './declaredEnvironments.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 environment a run deploys into (§ 3 PLX-Delivery): `given` when the @@ -44,147 +17,3 @@ export function environmentOf(declared: DeclaredEnvironments, event: string, ref // An invalid declaration deploys nowhere: a caller names its problems. return declared.problems.length > 0 ? '' : (environmentOfBranch(declared.environments, ref) ?? ''); } - -/** 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; -} diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index c93dce63..e03c94aa 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -15,6 +15,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'; @@ -2969,17 +2970,33 @@ test('a cyclic alias in compose.yaml is reported as a compose file that cannot b assert.match(found[0]?.problem ?? '', /aliases form a cycle/); }); -test('a deviation under a name released in an earlier version is told what it is now, or that it is gone', () => { - const stale = new Set([...KNOWN, 'PLX-Stack/NoCommittedValues', 'PLX-Stack/PathPrefix']); +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 gone = ['PLX-Stack', 'PathPrefix'].join('/'); - const found = diagnose([stack('stateless', {}, [old, gone])], stale).units[0]?.findings; + 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`', }, - { requirement: gone, problem: 'listed under `deviations`, but no requirement has this name' }, ]); // The old name silences nothing: the check of the new name still runs. const tracked = repo({ diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 9b44874d..09aca8ed 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -765,8 +765,18 @@ const MOVED_TO_STACK = new Set([ /** What a requirement that was renamed as it moved is called now. */ const RENAMED_ON_MOVE: Readonly> = { NoCommittedValues: 'NoCommittedSecrets' }; -/** Requirements of a version the index of this plx still holds that the compendium no longer has: a deviation under them is unknown whatever the index says. */ -const REMOVED = new Set(['PLX-Stack/PathPrefix']); +/** 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 { @@ -863,7 +873,12 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { requirement: name, problem: `listed under \`deviations\`, but no requirement has this name: it is now \`${renamedInStack(name)}\``, }); - else if (!known.has(name) || REMOVED.has(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)) findings.push({ diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 470bde1c..169330c0 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -32,7 +32,7 @@ export { codeSpan } from './codeSpan.ts'; export { commitVersion } from './commitVersion.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 { DEFAULT_BRANCH, @@ -56,22 +56,7 @@ export { renderCommitSha, type StackOutcome, } from './deploy.ts'; -export { - DEFAULT_ENVIRONMENT, - type DeployLeg, - type Deployment, - type DeployTargets, - deployLegs, - type EnvironmentTargets, - environmentOf, - type InventoryFile, - parseInventoryFile, - readInventory, - recordsWithoutTarget, - selectDeployTargets, - targetsIn, - type Untargeted, -} from './deployTargets.ts'; +export { environmentOf } from './deployTargets.ts'; export { type AppFacts, CHECKS, @@ -143,7 +128,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 152e5924..e48e5c10 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -321,14 +321,24 @@ test('a directory inside a repo whose root has no marker is a new repo of its ow // The two sites the verb exists for, from the bundled templates. const bundled = createRequire(import.meta.url)('../package.json') as { version: string }; -/** A newborn of repo-turbo with updates beside it, named `shop`, its birth faked and git made by hand: the app finds its repo by git. */ -async function bornTurbo() { +/** + * The `stack` template writes `production.yaml` and `staging.yaml` by name while the repo declares no environment, + * so a newborn with a stack fails `PLX-Stack/FileNamesDeclared`: the repos that must pass the doctor declare the + * two names. The stack template is to render the files from the declaration, which removes this. + */ +const FILE_ENVIRONMENTS = { staging: { promotes_from: 'main' }, production: { promotes_from: 'staging' } }; + +/** + * A newborn of repo-turbo with updates beside it, named `shop`, its birth faked and git made by hand: the app finds its + * repo by git. It declares the two environments of the stack template's files, unless `declared` is false. + */ +async function bornTurbo(declared = true) { const target = scratch.fresh('turbo'); const { ctx, ran } = recording(); const created = await newSite(ctx, { dir: target, templates: ['repo-turbo', 'updates'], - answers: { tenant: 'acme', repo: 'shop' }, + answers: { tenant: 'acme', repo: 'shop', ...(declared ? { environments: FILE_ENVIRONMENTS } : {}) }, plxVersion: bundled.version, root: templatesRoot(), }); @@ -357,7 +367,7 @@ async function doctorOf(target: string): Promise<{ findings: string[]; units: nu } } -test('a repo from repo-turbo with updates beside it, an app from app-nextjs and a stack from stack in it: the trees and the markers, and the newborn repo passes the doctor', async () => { +test('a repo from repo-turbo with updates beside it, an app from app-nextjs and a stack from stack in it: the trees and the markers, and the newborn repo that declares the stack files’ two environments passes the doctor', async () => { const { target, ran, created: repo } = await bornTurbo(); assert.equal(repo.kind, 'repo'); assert.deepEqual(repo.files, [ @@ -419,7 +429,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'), @@ -468,6 +478,17 @@ test('a repo born with environments holds the declaration in its marker, read ba assert.deepEqual((await doctorOf(target)).findings.length, 1); }); +test('a newborn repo with a stack and no declaration fails the doctor for both files the stack template writes', async () => { + const { target } = await bornTurbo(false); + await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web' }); + await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); + assert.deepEqual( + (await doctorOf(target)).findings.map((f) => f.replace(/ names the environment.*/, '')), + ['.: stack/production.yaml', '.: stack/staging.yaml'], + ); + assert.ok((await doctorOf(target)).findings.every((f) => f.includes('does not declare under `environments`'))); +}); + test('a stateful stack whose app carries the migration passes the doctor as born', async () => { const { target } = await bornTurbo(); await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web', migrates: 'true' }); 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 5be1baed..e783be72 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -128,6 +128,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/standard-index.json b/packages/lib/src/standard-index.json index 3833ab0c..be6b06be 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", @@ -255,6 +253,7 @@ "PLX-Stack/EnvironmentParity", "PLX-Stack/EnvironmentCoverage", "PLX-Stack/HostnamePort", + "PLX-Stack/PreparedHost", "PLX-Stack/FileNamesDeclared", "PLX-Stack/DeclaredHasFile" ] 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 dfa9e2fa..dbf232ea 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -61,7 +61,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 3936c82f..3f6aedfd 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -84,7 +84,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/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 index 5f758d3e..90af74b8 100755 --- a/tests/platform-playbook.sh +++ b/tests/platform-playbook.sh @@ -1,21 +1,21 @@ #!/usr/bin/env bash # The platform playbook (plexus.platform.playbook) against hosts that are -# containers of this machine's Docker daemon: Debian with systemd, sudo, and -# Caddy's binary and unit as its package installs them, 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. +# 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 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. +# 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")/.." @@ -41,44 +41,13 @@ fail() { exit 1 } -# The host's image: what a Debian host has when the platform layer's roles run -# on it, the proxy included, and the stand-in for docker. -mkdir "$work/image" -cat >"$work/image/Dockerfile" <<'EOF' -FROM caddy:2 AS caddy -FROM debian:13 -RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ - systemd systemd-sysv python3 sudo curl >/dev/null && rm -rf /var/lib/apt/lists/* -COPY --from=caddy /usr/bin/caddy /usr/bin/caddy -COPY caddy.service /etc/systemd/system/caddy.service -COPY docker /usr/local/bin/docker -RUN useradd --system --home-dir /var/lib/caddy --create-home --shell /usr/sbin/nologin caddy \ - && mkdir /etc/caddy && printf ':80 {\n\trespond "the package default"\n}\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 -cat >"$work/image/docker" <<'EOF' -#!/bin/sh -echo "$*" >>/var/log/docker-calls -EOF -chmod +x "$work/image/docker" -if ! docker build -q -t "$run:host" "$work/image" >"$work/build" 2>&1; then - echo "platform-playbook: the host's image could not be built (debian:13, caddy:2 or Debian's packages not to be had); skipped" +# 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 @@ -87,7 +56,8 @@ fi # $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 "$run:host" >/dev/null + --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" 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"