diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 26f8e3db..af36a5da 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -49,8 +49,23 @@ # with the vault's CLI, `op`, which the second play installs from the # vendor's repository where the host has none (plexus.ci.actions_runners, # vault_cli). The playbook reads every other secret from there itself (vars/vault.yml names the items -# and fields), and none is passed in. A runner host sends no mail: no mail -# relay is mounted, and a failed unit shows in the journal alone. +# and fields), and none is passed in. +# +# The host mails the tenant through the tenant's relay, as an app host does +# (plexus.host.mail): what it needs, the relay, its credentials, the sender +# and the recipient, is the vault's item mail-relay. It mails once a day at +# most per unit: when a unit fails (BuildKit, a cache server, a slot's +# container, the housekeeping), when the disk is fuller than +# actions_runners_disk_alert_percent, and when a slot has failed to mint its +# runner config for longer than actions_runners_slot_alert_after, saying for +# how long; the last two are units of their own, so that no other failure of +# the day takes their mail, and one failed minting mails nobody +# (plexus.ci.actions_runners). The host takes no mail over SMTP, since its +# slots share its loopback. An item that is missing, lacks a field, leaves one +# empty or names a port that is no number or a mode Postfix does not know +# fails no run: the host is set up, sends no mail, and says so and why in its +# journal; so does a mail role that fails. A relay that refuses fails no run +# either; Postfix says so in the journal at each try. # # The first play locks the host down: the values are checked before # anything changes, then the jobs' user takes the runner image's uid, the @@ -65,7 +80,8 @@ # for a run that logged in as root over SSH, which this one never did, so it # is told the first admin's name instead. The handlers of the first play run # even when a task of it fails. The second play reads the vault and sets up -# the rest: the baseline, the overlay, Docker, the cache servers, the slots. +# the rest: the mail, the baseline, the overlay, Docker, the cache servers, +# the slots. # # Tags: every play carries its layer (`host`, `ci`) and every role its own # name. @@ -196,7 +212,7 @@ vars: unread: >- {%- set unread = [] -%} - {%- for read in ci_vault_read.results if read.rc is defined and read.rc != 0 -%} + {%- for read in ci_vault_read.results if read.rc is defined and read.rc != 0 and not read.item.optional | default(false) -%} {%- set _ = unread.append(read.item.item ~ '/' ~ read.item.field ~ ' (' ~ (read.stderr | trim) ~ ')') -%} {%- endfor -%} {{ unread }} @@ -207,9 +223,93 @@ ansible.builtin.set_fact: "{{ ci_vault[item].var }}": "{{ ci_vault_read.results[item].stdout }}" loop: "{{ range(ci_vault | length) | list }}" - when: ci_vault_read.results[item].rc is defined + when: ci_vault_read.results[item].rc | default(1) == 0 no_log: true tags: [always] + + # From the variables, not from the reads, so that one given on the command + # line counts. A field that is empty counts as missing; a port is digits, + # and a mode one the mail role knows. Anything wrong leaves the host + # without mail. + - name: What is wrong with the mail relay + ansible.builtin.set_fact: + ci_mail_wrong: >- + {%- set fields = ci_vault | selectattr('item', 'eq', 'mail-relay') | list -%} + {%- set lacks = [] -%} + {%- for entry in fields if lookup('ansible.builtin.vars', entry.var, default='') | string | trim | length == 0 -%} + {%- set _ = lacks.append(entry.field) -%} + {%- endfor -%} + {%- set wrong = [] -%} + {%- if lacks | length == fields | length -%} + {%- set _ = wrong.append('the vault ' ~ ci_owner ~ '-ci-host has no item mail-relay') -%} + {%- elif lacks | length > 0 -%} + {%- set _ = wrong.append('the item mail-relay of the vault ' ~ ci_owner ~ '-ci-host lacks ' ~ lacks | join(', ')) -%} + {%- endif -%} + {%- set port = lookup('ansible.builtin.vars', 'ci_mail_port', default='') | string | trim -%} + {%- if port | length > 0 and port is not match('^[0-9]+$') -%} + {%- set _ = wrong.append('the item mail-relay names the port ' ~ port ~ ', which is no number') -%} + {%- endif -%} + {%- set mode = lookup('ansible.builtin.vars', 'ci_mail_mode', default='') | string | trim -%} + {%- if mode | length > 0 and mode not in ['starttls', 'tls'] -%} + {%- set _ = wrong.append('the item mail-relay names the mode ' ~ mode ~ ', which is neither starttls nor tls') -%} + {%- endif -%} + {{ wrong }} + tags: [always] + + - name: Hand the mail relay to the mail role + ansible.builtin.set_fact: + mail_smtp: + server: "{{ ci_mail_server }}" + port: "{{ ci_mail_port }}" + mode: "{{ ci_mail_mode }}" + username: "{{ ci_mail_username }}" + password: "{{ ci_mail_password }}" + from_address: "{{ ci_mail_from_address }}" + mailto: "{{ ci_mail_mailto }}" + when: ci_mail_wrong | length == 0 + no_log: true + tags: [always] + + # Before the roles, so that a unit of theirs that fails is mailed about + # from its first start, a slot whose first run cannot register among them, + # and rescued, so that a mail role that fails (a Postfix that cannot be + # installed) fails no run: the host is set up all the same and says so + # below. Its port on loopback closed, since the slots share the host's + # network. + - name: The host's mail + when: ci_mail_wrong | length == 0 + tags: [mail] + block: + - name: The mail role + ansible.builtin.import_role: + name: plexus.host.mail + vars: + mail_loopback_smtp: false + rescue: + - name: What failed of the mail role + ansible.builtin.set_fact: + ci_mail_wrong: + - >- + the role plexus.host.mail failed at '{{ ansible_failed_task.name | default('?') }}': + {{ ansible_failed_result.msg | default('') | truncate(400) }} + + # Under cloud-init the run's output is a log nobody reads; the journal is + # where an admin looks first. + - name: Say in the journal that the host sends no mail + ansible.builtin.command: + argv: + - logger + - --tag + - plexus-ci + - --priority + - user.warning + - >- + This host sends no mail: {{ ci_mail_wrong | join('; ') }}. A failed + unit, a disk over its threshold and a slot that cannot register + show in this journal alone. + when: ci_mail_wrong | length > 0 + changed_when: false + tags: [mail] roles: - { role: plexus.host.base, tags: [base] } - { role: plexus.host.upgrades, tags: [upgrades] } diff --git a/ansible/ci/playbooks/vars/vault.yml b/ansible/ci/playbooks/vars/vault.yml index 28b4a902..bc97f6ba 100644 --- a/ansible/ci/playbooks/vars/vault.yml +++ b/ansible/ci/playbooks/vars/vault.yml @@ -1,8 +1,9 @@ --- # What the playbook reads from the host's vault, -ci-host, and # into which variable: the one place the items and fields are named. An -# entry with `when` is read only where that holds; a variable given on the -# command line wins over what is read. +# entry with `when` is read only where that holds; an `optional` one fails +# no run when the vault lacks it; a variable given on the command line wins +# over what is read. ci_vault: - { var: actions_runners_app_client_id, item: github-app, field: client-id } - { var: actions_runners_app_private_key, item: github-app, field: private-key } @@ -17,3 +18,16 @@ ci_vault: - { var: actions_runners_connect_credentials, item: 1password-connect, field: credentials, when: actions_runners_connect } - { var: actions_runners_connect_token, item: 1password-connect, field: token, when: actions_runners_connect } - { var: netbird_setup_key, item: netbird, field: setup-key, when: netbird_enabled } + # The tenant's mail relay, which the host mails through (plexus.host.mail, + # its mail_smtp): the relay's name or address, its port, `starttls` or + # `tls` (implicit TLS), the relay's user and password, the sender every + # mail goes from and the one mailbox it goes to. An item that is missing, + # lacks a field, leaves one empty, or names a port that is no number or + # another mode leaves the host without mail, which it says in its journal. + - { var: ci_mail_server, item: mail-relay, field: server, optional: true } + - { var: ci_mail_port, item: mail-relay, field: port, optional: true } + - { var: ci_mail_mode, item: mail-relay, field: mode, optional: true } + - { var: ci_mail_username, item: mail-relay, field: username, optional: true } + - { var: ci_mail_password, item: mail-relay, field: password, optional: true } + - { var: ci_mail_from_address, item: mail-relay, field: from-address, optional: true } + - { var: ci_mail_mailto, item: mail-relay, field: mailto, optional: true } diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index b0bcf336..748c7a8e 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -68,8 +68,17 @@ # file a repo slot reads (turbo_cache). The role opens no port: the runner # polls the forge. # -# A runner host sends no mail: the playbook mounts no mail relay, so a failed -# unit, the housekeeping's disk alert among them, shows in the journal alone. +# Where the playbook sets up the host's mail (plexus.host.mail), a unit that +# fails is a mail, at most once a day per unit: a slot's container, BuildKit, +# the housekeeping. Two units exist to fail, so that a mail says so, each with +# a budget of its own: ci-runner-disk, hourly, on a disk fuller than +# actions_runners_disk_alert_percent, and ci-runner-cannot-register@, +# on a slot whose minting has failed at every attempt for +# actions_runners_slot_alert_after, which says for how long. A slot fails at +# every attempt that fails, and is started again; its own mail is held back +# for a failed minting (files/ci-runner-mail-hold), so that one refusal of the +# forge mails nobody. Without the host's mail every failure shows in the +# journal alone. # Where the slots register: `org` at the organisation, in a runner group of # it, `repo` on one repository (they are then that repository's alone, @@ -208,10 +217,15 @@ actions_runners_connect_uid: 999 actions_runners_connect_port: 8080 # Housekeeping, hourly: the registry pair onto this week's buckets, the -# pinned image pulled, stopped containers, unused images and volumes removed; -# fails when the root file system is fuller than this afterwards. +# pinned image pulled, stopped containers, unused images and volumes removed. +# The disk check, hourly too, a unit of its own: fails when the root file +# system is fuller than this, in percent. actions_runners_disk_alert_percent: 85 +# How long, in seconds, a slot's minting fails at every attempt before the +# host mails about it; an attempt takes about 50 s with the wait after it. +actions_runners_slot_alert_after: 300 + # The BuildKit service (§ 8 PLX-Delivery): one buildkitd on the host, the # systemd unit ci-buildkit, through which the publish step of a job builds # and pushes its image without a Docker daemon of its own, with buildx's diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register b/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register new file mode 100755 index 00000000..b3e20e94 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner-cannot-register @@ -0,0 +1,48 @@ +#!/bin/sh +# Says that a slot cannot register, as a unit that fails, so that the host's +# mail on a failed unit (plexus.host.mail) mails it with a daily budget of its +# own (ci-runner-cannot-register@.service): a container of the slot that +# failed earlier the same day takes nothing from it. Managed by Ansible +# (actions_runners). +# +# The slot's ExecStopPost starts it after every attempt that failed. It fails +# when the slot's row of failed mintings, /run/ci-runner/.failing (the +# host's uptime in seconds as the row's first attempt started, which +# ci-runner-jit writes), is older than ALERT_AFTER seconds, and says for how +# long; the mail carries what it says and the slot's last lines. Without a +# row, or with a younger one, it exits 0 and nobody is mailed. It fails +# towards mailing: a row or a threshold that is no number fails at once and +# says what it holds. Hand-runnable as root: +# +# ALERT_AFTER=300 ci-runner-cannot-register repo-1; echo $? +slot=${1:?the slot, e.g. repo-1} +row=/run/ci-runner/$slot.failing +[ -e "$row" ] || exit 0 +since=$(cat "$row" 2>/dev/null) +after=${ALERT_AFTER:-} + +fail() { + echo "ci-runner-cannot-register: $*" + echo "The last lines of ci-runner@$slot.service:" + journalctl --no-pager -o cat -n 20 -u "ci-runner@$slot.service" || true + exit 1 +} + +case $since in + '' | *[!0-9]*) fail "the slot $slot has failed to mint its runner config, and its row $row holds no number but '$since'" ;; +esac +case $after in + '' | *[!0-9]*) fail "the slot $slot has failed to mint its runner config, and the threshold ALERT_AFTER is no number but '$after'" ;; +esac +read -r up _ &2 + exit 1 +fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index eef6a646..0e822470 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -1,12 +1,13 @@ #!/bin/sh # Hourly housekeeping of a CI runner host. Managed by Ansible # (actions_runners); IMAGE, PULL (false for an image built on the host), -# REGISTRY (true | false), REGISTRY_IMAGE and DISK_ALERT_PERCENT come from -# the unit's environment. Hand-runnable as root: +# REGISTRY (true | false) and REGISTRY_IMAGE come from the unit's +# environment. How full the disk is, ci-runner-disk says, a unit of its own. +# Hand-runnable as root: # IMAGE=ghcr.io/plexus-ms/ci-runner: PULL=true REGISTRY=true \ -# REGISTRY_IMAGE=registry:2 DISK_ALERT_PERCENT=85 ci-runner-housekeeping +# REGISTRY_IMAGE=registry:2 ci-runner-housekeeping set -eu -: "${IMAGE:?}" "${PULL:?}" "${REGISTRY:?}" "${REGISTRY_IMAGE:?}" "${DISK_ALERT_PERCENT:?}" +: "${IMAGE:?}" "${PULL:?}" "${REGISTRY:?}" "${REGISTRY_IMAGE:?}" # The registry pair onto this week's buckets, first: a failure here is the # one that costs every run of the week a cold cache. @@ -31,10 +32,3 @@ done # The BuildKit service (ci-buildkit) keeps its cache in /var/lib/buildkit, # outside this daemon, and bounds it by its own garbage collection; nothing # here touches it, since a build may be using it. - -used=$(df --output=pcent / | tail -1 | tr -dc '0-9') -echo "root file system ${used}% used" -if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the repo slots' caches: the pnpm store, mise, corepack, Playwright), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 - exit 1 -fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-jit b/ansible/ci/roles/actions_runners/files/ci-runner-jit index 24531eb3..47e695ee 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-jit +++ b/ansible/ci/roles/actions_runners/files/ci-runner-jit @@ -33,9 +33,33 @@ esac name="$HOST-$instance" out=/run/ci-runner/$instance.env +# The row of failed attempts, $failing: the host's uptime in seconds as the +# row's first attempt started, a clock no time step moves and that starts +# again with /run at a boot. Each attempt starts the row where there is none, +# so that an attempt systemd ends for its time counts too, and a minting that +# succeeds ends it. A start of the slot that is not one of systemd's restarts +# (NRestarts 0) begins a new row, since a stop between two attempts runs no +# ExecStopPost and leaves the old one. After an attempt that failed the +# slot's ExecStopPost starts ci-runner-cannot-register@, which mails +# once the row is older than a few minutes; ci-runner-mail-hold keeps the +# slot's own mail for a container that failed after it minted. +failing=/run/ci-runner/$instance.failing +mkdir -p /run/ci-runner +if [ "$(systemctl show -P NRestarts "ci-runner@$instance.service")" = 0 ]; then + rm -f "$failing" +fi +if [ ! -e "$failing" ]; then + read -r up _ "$failing" +fi + # A failure waits before it fails, so that a forge outage costs one attempt # per slot every half minute rather than every restart interval. -trap 'echo "ci-runner-jit: minting the config of $name failed" >&2; sleep 30' ERR +minting_failed() { + echo "ci-runner-jit: minting the config of $name failed" >&2 + sleep 30 +} +trap minting_failed ERR forge_login @@ -92,4 +116,5 @@ done umask 077 mkdir -p /run/ci-runner printf 'ACTIONS_RUNNER_INPUT_JITCONFIG=%s\n' "$jit" >"$out" +rm -f "$failing" echo "$name: registered on $base with $labels" diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold new file mode 100644 index 00000000..ec0b5345 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner-mail-hold @@ -0,0 +1,31 @@ +#!/bin/sh +# Holds back the host's mail on a slot that failed in its minting +# (ExecCondition of failure-mail@.service, plexus.host.mail, by a drop-in of +# this role): ci-runner-cannot-register@ mails that, once the minting +# has failed for a few minutes, with a daily budget of its own. Managed by +# Ansible (actions_runners). +# +# A slot fails as a unit at every attempt that fails, and is started again. +# The slot's row of failed mintings, /run/ci-runner/.failing, which +# ci-runner-jit writes as an attempt starts and removes once it has minted, +# tells a minting that failed from a container that failed after it: the +# second is mailed at once, as every other unit is. It fails towards mailing: +# a row that is missing or holds no number lets the slot's mail go. A failed +# minting it holds back is mailed only if the slot's ExecStopPost can start +# ci-runner-cannot-register@. Exits 0 to mail, 1 to hold back, which +# systemd counts as no failure of failure-mail@. +# +# ci-runner-mail-hold ci-runner@repo-1.service; echo $? +unit=${1:?the unit that failed, e.g. ci-runner@repo-1.service} +case $unit in + ci-runner@*.service) ;; + *) exit 0 ;; +esac +slot=${unit#ci-runner@} +slot=${slot%.service} +since=$(cat "/run/ci-runner/$slot.failing" 2>/dev/null) || exit 0 +case $since in + '' | *[!0-9]*) exit 0 ;; +esac +echo "ci-runner-mail-hold: $slot failed in its minting; ci-runner-cannot-register@$slot.service mails that" +exit 1 diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index 16a11007..7895b404 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -13,7 +13,8 @@ # # the runner GitHub's Actions runner and the libraries it needs, run # as the user runner (1001), with sudo where the engine -# allows it (a slot's no-new-privileges does not) +# allows it (a slot's container, which ci-runner-slot +# starts with no capability, does not) # node, pnpm node from the base; pnpm and yarn through corepack, at # the version a repo's packageManager names, downloaded # into ~/.cache/node/corepack diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml index e7664287..11935c73 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -1,16 +1,20 @@ # The tools the environment image carries (Dockerfile beside this file), as # mise's system config, /etc/mise/config.toml: the lowest of mise's configs, so # that a repo's own pin of any of them wins. Installed at build time into mise's -# system directory, which mise searches after its data directory and never -# writes; a version a repo pins and the image lacks installs into the data -# directory, which a runner host shares between its repo slots; in -# a delivery slot it stays in the job's container. +# system directory, which mise searches after its data directory and which only +# root can write; a version a repo pins and the image lacks installs into the +# data directory, which a runner host shares between its repo slots; in +# a delivery slot it stays in the job's container. A job's `mise use` that names +# a version installed here makes mise rebuild the shims here, through sudo, +# which fails in a slot: the job deploy has it write them elsewhere. [tools] # plx-ci at the Plexus version: the pin is written with each version, never by # the update bot (§ 1 PLX-Updates); allow_low_downloads only waives npm's # young-package heuristics. It runs on the base image's node. "npm:@plexus-ms/cli-ci" = { version = "0.135.0", allow_low_downloads = true } -# The vault's CLI, which load-secrets-action uses where it finds one. +# The vault's CLI, which plx-ci setup reads the vault with. A runner without it, the forge's own, gets the same +# version installed by plx-ci setup (packages/cli-ci/src/core/op.ts holds it in code). The update bot cannot look +# this package up, so a person moves the two together, and a test of cli-ci holds them equal. "aqua:1password/cli" = "2.42.0" # What jobs installed for themselves: gh for plx-update. exo stays for the # transition, for the sweep of the instances an earlier version launched; the diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 95162578..c579b038 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -107,7 +107,15 @@ owner: root group: root mode: "0755" - loop: [ci-runner-jit, ci-runner-unregister, ci-runner-slot, ci-connect-refresh, ci-runner-housekeeping] + loop: + - ci-runner-jit + - ci-runner-unregister + - ci-runner-slot + - ci-connect-refresh + - ci-runner-housekeeping + - ci-runner-disk + - ci-runner-cannot-register + - ci-runner-mail-hold - name: Create the shared caches ansible.builtin.file: @@ -259,6 +267,11 @@ ExecStart=/usr/local/sbin/ci-runner-slot %i ExecStopPost=-/usr/bin/docker rm --force --volumes ci-runner-%i ExecStopPost=-/usr/bin/rm -f /run/ci-runner/%i.env + # A slot stopped while it mints ends the row of failed mintings + # (ci-runner-jit); an attempt that failed keeps it, and asks whether the + # row is old enough to mail about (ci-runner-cannot-register). + ExecStopPost=-/bin/sh -c 'if [ "$$SERVICE_RESULT" = success ]; then rm -f /run/ci-runner/%i.failing; \ + else systemctl start --no-block ci-runner-cannot-register@%i.service; fi' TimeoutStartSec=5min TimeoutStopSec=1min SuccessExitStatus=143 @@ -272,6 +285,48 @@ WantedBy=multi-user.target notify: [Reload systemd, Restart the slots] +# A slot that cannot register is a unit that fails, once its minting has +# failed for actions_runners_slot_alert_after, so that the host's mail on a +# failed unit (plexus.host.mail, where the playbook sets it up) mails it with +# a budget of its own (files/ci-runner-cannot-register). The slot's own mail +# is held back for a failed minting and goes for a failed container +# (files/ci-runner-mail-hold), by a drop-in of the unit that sends it, +# harmless on a host without it. +- name: Install the unit that says a slot cannot register + ansible.builtin.copy: + dest: /etc/systemd/system/ci-runner-cannot-register@.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Say whether the CI runner slot %i has failed to register for long + + [Service] + Type=oneshot + Environment=ALERT_AFTER={{ actions_runners_slot_alert_after }} + ExecStart=/usr/local/sbin/ci-runner-cannot-register %i + notify: Reload systemd + +- name: Create the drop-in directory of the failure mail + ansible.builtin.file: + path: /etc/systemd/system/failure-mail@.service.d + state: directory + owner: root + group: root + mode: "0755" + +- name: Hold back the slot's own mail on a failed minting + ansible.builtin.copy: + dest: /etc/systemd/system/failure-mail@.service.d/20-ci-runner.conf + owner: root + group: root + mode: "0644" + content: | + [Service] + ExecCondition=/usr/local/sbin/ci-runner-mail-hold %i + notify: Reload systemd + - name: Install the housekeeping service ansible.builtin.copy: dest: /etc/systemd/system/ci-runner-housekeeping.service @@ -290,19 +345,37 @@ Environment=PULL={{ (not actions_runners_image_build | bool) | lower }} Environment=REGISTRY={{ actions_runners_registry | bool | lower }} Environment=REGISTRY_IMAGE={{ actions_runners_registry_image }} - Environment=DISK_ALERT_PERCENT={{ actions_runners_disk_alert_percent }} ExecStart=/usr/local/sbin/ci-runner-housekeeping notify: Reload systemd -- name: Install the housekeeping timer +# How full the disk is, a unit apart from the housekeeping: the host's mail +# goes at most once a day per unit, and a pull that failed that day, or +# fails for a full disk, is to take neither the check nor its mail with it. +- name: Install the disk check ansible.builtin.copy: - dest: /etc/systemd/system/ci-runner-housekeeping.timer + dest: /etc/systemd/system/ci-runner-disk.service owner: root group: root mode: "0644" content: | [Unit] - Description=CI runner host housekeeping + Description=CI runner host disk check + + [Service] + Type=oneshot + Environment=DISK_ALERT_PERCENT={{ actions_runners_disk_alert_percent }} + ExecStart=/usr/local/sbin/ci-runner-disk + notify: Reload systemd + +- name: Install the timers of the housekeeping and the disk check + ansible.builtin.copy: + dest: /etc/systemd/system/ci-runner-{{ item }}.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Hourly ci-runner-{{ item }} [Timer] OnCalendar=hourly @@ -311,16 +384,18 @@ [Install] WantedBy=timers.target + loop: [housekeeping, disk] notify: Reload systemd - name: Flush handlers ansible.builtin.meta: flush_handlers -- name: Enable the housekeeping timer +- name: Enable the timers of the housekeeping and the disk check ansible.builtin.systemd_service: - name: ci-runner-housekeeping.timer + name: ci-runner-{{ item }}.timer enabled: true state: started + loop: [housekeeping, disk] - name: Enable and start the slots ansible.builtin.systemd_service: diff --git a/ansible/host/roles/mail/defaults/main.yml b/ansible/host/roles/mail/defaults/main.yml index 328e4257..3d4f08de 100644 --- a/ansible/host/roles/mail/defaults/main.yml +++ b/ansible/host/roles/mail/defaults/main.yml @@ -15,6 +15,14 @@ # Empty leaves the host's mail as it is. mail_smtp: {} +# Postfix takes the host's own mail from sendmail(1), which mail(1), cron and +# failure-mail use, and also over SMTP on loopback, port 25, from whatever +# reaches the host's loopback. False closes that port, for a host whose +# loopback runs code that is not to mail as the host: a runner host, whose +# slots share its network. True again opens it, restoring the line that +# false commented out. +mail_loopback_smtp: true + # Have unattended-upgrades mail when an upgrade fails (never on success). mail_unattended_upgrades: true diff --git a/ansible/host/roles/mail/tasks/main.yml b/ansible/host/roles/mail/tasks/main.yml index 4f84eaa9..192a7004 100644 --- a/ansible/host/roles/mail/tasks/main.yml +++ b/ansible/host/roles/mail/tasks/main.yml @@ -30,6 +30,25 @@ mode: "0644" notify: Restart postfix + # The service `smtp inet` of master.cf, as Debian ships it: commented out + # behind a mark of this role's, and that line alone restored, so that a + # line commented out by hand stays as it is. + - name: Close the SMTP port on loopback + ansible.builtin.replace: + path: /etc/postfix/master.cf + regexp: '^(smtp\s+inet\s.*)$' + replace: '#closed by mail_loopback_smtp: \1' + when: not mail_loopback_smtp + notify: Restart postfix + + - name: Open the SMTP port on loopback + ansible.builtin.replace: + path: /etc/postfix/master.cf + regexp: '^#closed by mail_loopback_smtp: (.*)$' + replace: '\1' + when: mail_loopback_smtp + notify: Restart postfix + - name: Enable Postfix ansible.builtin.systemd_service: name: postfix diff --git a/newborns/deploy-job.test.ts b/newborns/deploy-job.test.ts index 4152436d..868a44aa 100644 --- a/newborns/deploy-job.test.ts +++ b/newborns/deploy-job.test.ts @@ -13,22 +13,30 @@ // option of the tool node and of plx, node and plx as `path:` versions, an asdf plugin for node, the // settings that send node's download elsewhere, a .miserc.toml that undoes the job's ignoring of the // repo's config, and a tool option of a nested project; and, with a system config as a runner image has it, the -// plx-ci the later steps run and the file tasks of the checkout. The step of the job repo, run the same way, is -// the control: it runs the hook, exports the variable and installs the other tool, which is what shows -// that a probe can fire. +// plx-ci the later steps run and the file tasks of the checkout; and the steps as a delivery slot runs +// them, in a container of the environment image (`slotImage`), whose mise system directory is root's. +// The step of the job repo, run the same way, is the control: it runs the hook, exports the variable +// and installs the other tool, which is what shows that a probe can fire. // -// Every case has data, state and system directories of its own, and a home: nothing of what the -// machine's own mise holds is in the way, and what the case installs is installed into it alone; mise -// itself is the one download, made once and linked in. What this does not stand in for: the runner's own -// program (it passes the inputs, orders the path and masks values), and a runner of the forge. It needs -// the network: the action's source from the forge, mise from its releases, node, and the registry. +// Every case but the slot's has data, state and system directories of its own, and a home: nothing of +// what the machine's own mise holds is in the way, and what the case installs is installed into it +// alone; mise itself is the one download, made once and linked in, and copied into the slot's +// container. What this does not stand in for: the runner's own program (it passes the inputs, orders +// the path and masks values), and a runner of the forge. It needs the network: the action's source +// from the forge, mise from its releases, node, and the registry. The slot's case also needs Docker, +// and builds its image as the image's own build does, from Docker Hub (the base), Debian's mirror, +// mise's releases (the image's pin) and npm (the image's plx-ci), registries the other newborns use +// as well; the image is kept, so a warm run builds from Docker's cache and downloads only node. +// The case took two minutes cold, with the base image already present, and between 15 seconds and +// three minutes warm, as fast as node's download. import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; -import { born, builtVersion, close, git, open, put, sh, tryRun } from './helpers.ts'; +import { born, builtVersion, close, git, open, put, type Ran, sh, tryRun } from './helpers.ts'; /** The variable the repo's [env] sets: what the job deploy must not export. */ const VARIABLE = 'PLX_DEPLOY_JOB_PROBE'; @@ -55,6 +63,8 @@ let control: Step; let requests = 0; let mirror: Server | undefined; let mirrorUrl = ''; +/** The delivery slot's container (`slot`), which `after` removes. */ +let slotContainer = ''; before(async () => { here = await open('deploy-job'); @@ -91,11 +101,12 @@ before(async () => { }); after(async () => { + if (slotContainer) await tryRun('docker', ['rm', '-f', slotContainer], here); await new Promise((resolve) => (mirror ? mirror.close(resolve) : resolve(undefined))); await close(); }); -/** The expressions the workflow's inputs and environment hold; any other fails here. */ +/** The expressions the workflow's inputs and environment hold, each where it stands in a value; any other fails here. */ function evaluated(value: unknown, workspace: string, temp = ''): string { if (typeof value !== 'string' || !value.includes('${{')) return String(value); const known: Record = { @@ -103,11 +114,17 @@ function evaluated(value: unknown, workspace: string, temp = ''): string { '${{ github.workspace }}': workspace, '${{ runner.temp }}': join(temp, 'temp'), }; - const found = known[value]; - assert.ok(found !== undefined, `an expression this test does not know: ${value}`); - return found; + return value.replace(/\$\{\{.*?\}\}/g, (expression) => { + const found = known[expression]; + assert.ok(found !== undefined, `an expression this test does not know: ${expression}`); + return found; + }); } +/** A step's own environment, its expressions evaluated. */ +const stepEnv = (step: Step, workspace: string, temp: string): NodeJS.ProcessEnv => + Object.fromEntries(Object.entries(step.env ?? {}).map(([key, value]) => [key, evaluated(value, workspace, temp)])); + /** The lines of a runner's file command: `NAME=value`, or `NAME< { const out: Record = {}; @@ -187,15 +204,31 @@ function actionEnv(dir: string, temp: string, inputs: Record): }; } +/** Where a job's steps run: this machine, with the case's own directories, or a slot's container (`slot`). */ +interface Machine { + /** What every step's environment starts from. */ + env: NodeJS.ProcessEnv; + /** The PATH the runner hands a step, behind what the steps put in front of it. */ + path: string; + exec(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Promise; +} + +/** This machine, the case's directories in place of mise's own. */ +const host = (name: string, extra: NodeJS.ProcessEnv = {}): Machine => ({ + env: { ...worldOf(name), ...extra }, + path: process.env.PATH ?? '', + exec: (command, args, cwd, env) => tryRun(command, args, cwd, env), +}); + interface After { /** The environment a later step runs in: the job's, what the steps exported, and the path they gave. */ env: NodeJS.ProcessEnv; dir: string; + machine: Machine; } /** The steps, as a job runs them in `dir` up to its setup step, then what a later step finds. */ -async function run(dir: string, job: Job, name: string, extra: NodeJS.ProcessEnv = {}): Promise { - const world = { ...worldOf(name), ...extra }; +async function run(dir: string, job: Job, name: string, machine: Machine = host(name)): Promise { const temp = join(here, 'cases', name, 'runner'); const jobEnv = Object.fromEntries(Object.entries(job.env ?? {}).map(([key, value]) => [key, evaluated(value, dir)])); const files = { env: join(temp, 'env'), path: join(temp, 'path') }; @@ -203,27 +236,31 @@ async function run(dir: string, job: Job, name: string, extra: NodeJS.ProcessEnv const next = (): NodeJS.ProcessEnv => { const path = existsSync(files.path) ? readFileSync(files.path, 'utf8').split('\n').filter(Boolean).reverse() : []; const exported = existsSync(files.env) ? entries(files.env) : {}; - return { ...world, ...jobEnv, ...exported, PATH: [...path, process.env.PATH].join(':') }; + return { ...machine.env, ...jobEnv, ...exported, PATH: [...path, machine.path].join(':') }; }; for (const step of job.steps) { if (step.uses?.startsWith('actions/checkout')) continue; if (step.id === 'setup') break; if (step.uses) { - const env = { ...next(), ...actionEnv(dir, temp, step.with ?? {}), ...step.env }; - const ran = await tryRun('node', [join(action, 'dist', 'index.js')], dir, env); + const env = { ...next(), ...actionEnv(dir, temp, step.with ?? {}), ...stepEnv(step, dir, temp) }; + const ran = await machine.exec('node', [join(action, 'dist', 'index.js')], dir, env); assert.ok(ran.ok, ran.output); } else { const cwd = step['working-directory'] ? evaluated(step['working-directory'], dir, temp) : dir; mkdirSync(cwd, { recursive: true }); - const ran = await tryRun('sh', ['-c', step.run ?? ''], cwd, { ...next(), ...step.env }); + const ran = await machine.exec('sh', ['-c', step.run ?? ''], cwd, { ...next(), ...stepEnv(step, dir, temp) }); assert.ok(ran.ok, `${step.run}\n${ran.output}`); } } - return { env: next(), dir }; + return { env: next(), dir, machine }; } /** What a later step prints for a shell command, in the checkout. */ -const later = async (after: After, command: string) => (await sh('sh', ['-c', command], after.dir, after.env)).trim(); +async function later(after: After, command: string): Promise { + const ran = await after.machine.exec('sh', ['-c', command], after.dir, after.env); + assert.ok(ran.ok, `${command}\n${ran.output}`); + return ran.output.trim(); +} /** A file a case's code would write, which must not exist. */ const probe = (name: string) => join(here, 'probes', name); @@ -325,11 +362,209 @@ const IMAGE_VERSION = '9.9.9'; test('on a slot the plx-ci the later steps run is the one the workflow names, not the runner image’s', async () => { const name = 'image-plx-ci'; const dir = copyOf(name); - const after = await run(dir, deploy, name, slotSystem(name)); + const after = await run(dir, deploy, name, host(name, slotSystem(name))); assert.equal(await later(after, 'plx-ci --version'), builtVersion()); assert.equal(await later(after, 'plx --version'), builtVersion()); }); +const IMAGE_DIR = join(import.meta.dirname, '..', 'ansible', 'ci', 'roles', 'actions_runners', 'files', 'ci-runner'); +/** The slot's image, tagged by what it is built from (`slot`) and kept between runs, so that a warm run builds nothing. */ +const SLOT_IMAGE = 'plx-newborn-deploy-job-slot'; +/** How long a slot's container lives at most, so that one a killed run leaves goes by itself. */ +const SLOT_LIFETIME = 30 * 60; + +/** + * The environment image as far as the step that installs plx meets it, built from the image's own Dockerfile and + * mise.toml (`slotImage`). Taken over word for word, in their order, the Dockerfile's instructions that make what the + * step meets: its base, every ENV, the apt-get install that brings sudo, curl and zstd, the user runner and the + * sudoers line out of the instruction that creates them, the download of mise at its pin into /usr/local/bin, the copy + * of mise.toml as the system config, the line that installs and shims the system tools as root, USER and WORKDIR. The + * system config is the image's own [settings] block and its plx-ci line. Left out on purpose: the Actions runner, + * docker's client, the browsers' libraries, corepack and ci-mise-install, none of which the step runs (`LEFT_OUT`), and + * the system config's other tools (the vault's CLI, gh, exo), which the step does not name: plx-ci alone is enough for + * mise to rebuild the system shims. A line the test takes that the Dockerfile no longer has fails the test, and so + * does a RUN, COPY or ADD of the Dockerfile that it neither takes nor leaves out by name. + */ +const LEFT_OUT: Record = { + "docker's client": /^RUN curl [^\n]*docker\.tgz/, + "the browsers' libraries": /playwright@[^\n]* install-deps/, + corepack: /^RUN corepack enable$/, + 'ci-mise-install': /^COPY [^\n]*ci-mise-install /, +}; + +function slotImage(): { dockerfile: string; config: string } { + const text = readFileSync(join(IMAGE_DIR, 'Dockerfile'), 'utf8'); + // The instructions, each with its continuation lines, comments and blank lines dropped. + const instructions: string[] = []; + let current = ''; + for (const line of text.split('\n')) { + if (!current && (/^\s*#/.test(line) || !line.trim())) continue; + current += current ? `\n${line}` : line; + if (!line.endsWith('\\')) { + instructions.push(current); + current = ''; + } + } + const taken = new Map(); + const take = (what: string, instruction: string) => { + taken.set(what, (taken.get(what) ?? 0) + 1); + return instruction; + }; + const kept: string[] = []; + for (const instruction of instructions) { + const before = kept.length; + if (/^(FROM|ENV|USER|WORKDIR) /.test(instruction)) + kept.push(take(instruction.split(' ')[0] as string, instruction)); + else if (/^ARG MISE_(VERSION|SHA256)=/.test(instruction)) kept.push(take('ARG MISE_*', instruction)); + else if (/^RUN apt-get update[\s\S]*apt-get install[\s\S]*\bsudo\b/.test(instruction)) + kept.push(take('the apt-get install of sudo', instruction)); + else if (/^RUN .*\/usr\/local\/bin\/mise "https:/.test(instruction)) + kept.push(take('the download of mise', instruction)); + else if (instruction === 'COPY mise.toml /etc/mise/config.toml') kept.push(take('the system config', instruction)); + else if (/^RUN mise install --system/.test(instruction)) kept.push(take('the system install', instruction)); + else if (/useradd .* runner\b/.test(instruction)) { + const user = /useradd [^&;]*runner/.exec(instruction)?.[0]; + const sudoers = /echo '[^']*' >\/etc\/sudoers\.d\/runner/.exec(instruction)?.[0]; + if (user && sudoers) kept.push(take('the user runner and sudoers', `RUN ${user} && ${sudoers}`)); + } + if (kept.length === before && /^(RUN|COPY|ADD) /.test(instruction)) + assert.ok( + Object.values(LEFT_OUT).some((pattern) => pattern.test(instruction)), + `an instruction of the image's Dockerfile this test neither takes nor leaves out:\n${instruction}`, + ); + } + for (const what of [ + 'FROM', + 'ENV', + 'USER', + 'WORKDIR', + 'ARG MISE_*', + 'the apt-get install of sudo', + 'the download of mise', + 'the system config', + 'the system install', + 'the user runner and sudoers', + ]) + assert.ok(taken.has(what), `the image's Dockerfile no longer has ${what} as this test takes it`); + const toml = readFileSync(join(IMAGE_DIR, 'mise.toml'), 'utf8'); + const settings = /^\[settings\]\n(?:(?!\[)[^\n]*\n?)*/m.exec(toml)?.[0]; + const pin = /^"npm:@plexus-ms\/cli-ci" = .*$/m.exec(toml)?.[0]; + assert.ok(settings && pin, "the image's mise.toml has a [settings] block and pins plx-ci"); + return { dockerfile: `${kept.join('\n')}\n`, config: `[tools]\n${pin}\n\n${settings}` }; +} + +/** + * A delivery slot of a runner host, as ci-runner-slot starts one: a container of the image (`slotImage`) on the host's + * network, as the user runner, with no capability (which ci-runner-slot must still give), so that sudo fails as it does + * there. Mounted of the host's is only + * what this file must hand a step: the case's own directory, the action's source, the registry's npmrc, and the mise + * the action downloaded in `before`, which is copied to where the action keeps it, so that the action verifies it and + * downloads no mise, only its signed checksums. The container is named for the run's directory, lives `SLOT_LIFETIME` + * at most and is removed by `after`. The image is tagged by a hash of its Dockerfile and config, so that two checkouts + * with different Dockerfiles do not test each other's image, and the older tags of its name are removed where no + * container uses them. + */ +async function slot(name: string): Promise { + const root = join(here, 'cases', name); + const temp = join(root, 'runner'); + // The runner's directories and file commands, written by the steps as the user runner. + for (const sub of ['temp', 'tool-cache']) mkdirSync(join(temp, sub), { recursive: true }); + for (const file of ['env', 'path', 'output', 'state']) writeFileSync(join(temp, file), ''); + await sh('chmod', ['-R', 'a+rwX', root], here); + assert.match( + readFileSync(join(IMAGE_DIR, '..', 'ci-runner-slot'), 'utf8'), + /--cap-drop ALL/, + 'ci-runner-slot starts a slot with no capability, as this test does', + ); + const { dockerfile, config } = slotImage(); + put(here, { 'slot-image/Dockerfile': dockerfile, 'slot-image/mise.toml': config }); + const tag = createHash('sha256').update(dockerfile).update('\0').update(config).digest('hex').slice(0, 16); + const image = `${SLOT_IMAGE}:${tag}`; + const tags = await sh('docker', ['images', SLOT_IMAGE, '--format', '{{.Tag}}'], here); + for (const old of tags.split('\n').filter((other) => other && other !== tag)) + await tryRun('docker', ['rmi', `${SLOT_IMAGE}:${old}`], here); + await sh('docker', ['build', '-q', '-t', image, join(here, 'slot-image')], here); + const npmrc = join(here, 'npmrc'); + const seed = join(here, 'mise-data', 'bin'); + const mounts = [ + `${root}:${root}`, + `${action}:${action}:ro`, + `${seed}:${seed}:ro`, + ...(existsSync(npmrc) ? [`${npmrc}:${npmrc}:ro`] : []), + ]; + slotContainer = `${basename(here)}-slot`; + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--init', + '--name', + slotContainer, + '--network', + 'host', + '--cap-drop', + 'ALL', + '--memory', + '2g', + ...mounts.flatMap((mount) => ['-v', mount]), + image, + 'sleep', + String(SLOT_LIFETIME), + ], + here, + ); + await sh( + 'docker', + ['exec', slotContainer, 'sh', '-c', `mkdir -p ~/.local/share/mise/bin && cp -a ${seed}/. ~/.local/share/mise/bin/`], + here, + ); + const path = (await sh('docker', ['exec', slotContainer, 'printenv', 'PATH'], here)).trim(); + return { + env: existsSync(npmrc) ? { NPM_CONFIG_USERCONFIG: npmrc } : {}, + path, + exec: (command, args, cwd, env) => + tryRun( + 'docker', + [ + 'exec', + '-w', + cwd, + ...Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : ['-e', `${key}=${value}`])), + slotContainer, + command, + ...args, + ], + here, + ), + }; +} + +// The step as a delivery slot runs it: the image's plx-ci is the version the workflow names, since a version stamps both, +// so mise finds it installed in the system directory and rebuilds the system shims, which point at the image's mise and +// not at the one the action downloads; only root can write them, and sudo fails in a container without capabilities. +// It downloads, cold: the image's base and Debian's packages, mise at the image's pin from its releases, and the +// image's plx-ci with its dependencies from npm, as the image's own build does; in the container node from its +// project. Warm, the image is built from Docker's cache and node is the one download. +test('on a delivery slot, in a container of the environment image, the job deploy installs plx at the version the workflow names', async () => { + const name = 'delivery-slot'; + const pin = /^"npm:@plexus-ms\/cli-ci" = \{ version = "([^"]+)"/m.exec( + readFileSync(join(IMAGE_DIR, 'mise.toml'), 'utf8'), + )?.[1]; + assert.equal(pin, builtVersion(), "the image's plx-ci is the version the workflow names: a version stamps both"); + const dir = copyOf(name); + const machine = await slot(name); + try { + const after = await run(dir, deploy, name, machine); + assert.equal(await later(after, 'plx --version'), builtVersion()); + assert.equal(await later(after, 'plx-ci --version'), builtVersion()); + } finally { + // What the user runner wrote into the case's directory, for `close` to remove. + await tryRun('docker', ['exec', slotContainer, 'chmod', '-R', 'a+rwX', join(here, 'cases', name)], here); + } +}); + // A file task in the checkout is a config file mise must trust before it reads it, and a job that ignores the // checkout's config cannot trust it: the step failed on the slot, whose image sets `paranoid = ["config"]` (tried: the // same repo passed on a host with no such setting, and failed there with MISE_PARANOID=1), so a repo's author could @@ -341,7 +576,7 @@ for (const directory of ['.mise/tasks', 'mise-tasks', '.config/mise/tasks']) mkdirSync(join(dir, directory), { recursive: true }); writeFileSync(join(dir, directory, 'x'), `#!/bin/sh\ntouch ${probe(name)}\n`); chmodSync(join(dir, directory, 'x'), 0o755); - const after = await run(dir, deploy, name, slotSystem(name)); + const after = await run(dir, deploy, name, host(name, slotSystem(name))); assert.ok(!existsSync(probe(name)), 'the task ran'); assert.equal(await later(after, 'plx --version'), builtVersion()); }); diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index f7297466..b8ca53c3 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -7,7 +7,8 @@ // actions/checkout a fresh clone of the repo's origin at the pushed commit // jdx/mise-action mise install, and every later command through mise's environment // run the command, split on its spaces: plx-ci setup itself, with an `op` -// that reads the vault's items from this file, and the verbs +// that says its version, as plx-ci setup asks before it installs one, and +// reads the vault's items from this file, and the verbs // actions/upload-artifact the files its path finds in the checkout, as the artifact holds them // // A step's `if` and the expressions of its environment are the few the @@ -26,10 +27,13 @@ // without one. The first run passes every step and pushes each app's image // under build- and the commit. A second run on the same content replays // check, test, build and e2e from the caches and only tags each image with the -// new commit. Where a suite fails, the step after e2e finds in the checkout, at -// the path it names, the failed suite's results under the suite's directory -// name and nothing of the suite that passed, and publish does not run. Needs -// Docker and the network, as the newborns do. +// new commit. A run on a machine that names no cache server builds each app +// once, in the step build: e2e and publish replay that build from the job's +// local cache, and the image holds the very directory e2e ran against. Where +// a suite fails, the step after e2e finds in the checkout, at the path it +// names, the failed suite's results under the suite's directory name and +// nothing of the suite that passed, and publish does not run. Needs Docker and +// the network, as the newborns do. import assert from 'node:assert/strict'; import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; @@ -75,7 +79,7 @@ before(async () => { mkdirSync(bin); writeFileSync( join(bin, 'op'), - `#!/bin/sh\n[ "$1 $2" = "read op://acme-ci/repo_web/server-actions-key" ] && echo '${KEY}' && exit 0\necho "op: no item $2" >&2\nexit 1\n`, + `#!/bin/sh\n[ "$1" = "--version" ] && echo '2.42.0' && exit 0\n[ "$1 $2" = "read op://acme-ci/repo_web/server-actions-key" ] && echo '${KEY}' && exit 0\necho "op: no item $2" >&2\nexit 1\n`, ); chmodSync(join(bin, 'op'), 0o755); env = { @@ -171,16 +175,22 @@ const handed = (file: string): Record => let jobs = 0; /** - * The job repo of on_push.yml on a push of `sha`: its steps as the job's checkout lists them, in their order, each - * as the forge would run it. A failed step skips the steps after it, except those whose condition holds. + * The job repo of on_push.yml on a push of `sha`, on a machine whose environment is `env` and `machine` over it: its + * steps as the job's checkout lists them, in their order, each as the forge would run it. A failed step skips the + * steps after it, except those whose condition holds. `after` is called with each step's name and the job's checkout + * once the step is done. */ -async function repoJob(sha: string): Promise<{ job: string; done: Done[]; ok: boolean }> { +async function repoJob( + sha: string, + machine: Record = {}, + after: (step: string, job: string) => void = () => {}, +): Promise<{ job: string; done: Done[]; ok: boolean }> { const job = join(here, 'jobs', String(jobs)); // The runner's own directory, outside the checkout, as the forge's is. const temp = join(here, 'runner', String(jobs++)); const files = { GITHUB_OUTPUT: join(temp, 'output'), GITHUB_ENV: join(temp, 'env') }; /** The job's environment: the world's, the forge's, and what setup handed on. */ - let jobEnv: Record = { ...env, GITHUB_SHA: sha, RUNNER_TEMP: temp }; + let jobEnv: Record = { ...env, ...machine, GITHUB_SHA: sha, RUNNER_TEMP: temp }; let outputs: Record = {}; let failed = false; let withMise = false; @@ -253,6 +263,7 @@ async function repoJob(sha: string): Promise<{ job: string; done: Done[]; ok: bo } } else throw new Error(`a step this file does not stand in for: ${JSON.stringify(step)}`); done.push({ step: name, conclusion: ok ? 'success' : 'failure', output, ...(artifact && { artifact }) }); + after(name, job); if (!ok) failed = true; } return { job, done, ok: !failed }; @@ -346,6 +357,55 @@ test('a second run on the same content replays check, test, build and e2e, and o } }); +/** + * Turbo's line for a task it runs, in a job of the forge as a group of the log, with the hash it runs under: a miss, + * or where Turbo has no cache at all a bypass. + */ +const executed = (task: string) => + new RegExp(`(?:${task}: |::group::${task}\\n)cache (?:miss,|bypass, force) executing (\\w+)`, 'g'); + +test('on a machine that names no cache server, the step build builds each app once, and e2e and publish replay that build, which the image is made from', async () => { + // A source file of web's own moves its hash, so that the registry has no image of it yet; site's stays. + const sha = await push('push-uncached', (dir) => { + put(dir, { 'apps/web/src/uncached.ts': "export const uncached = 'a job without a cache server';\n" }); + }); + // A file planted in web's build output after the step build: a build of Next empties its output directory first, + // and a replay restores the cached files over it, so the file is still there where nothing built web again. Neither + // BUILD_ID, the hash, nor Next's preview keys, which a build in one checkout reuses, would tell two builds apart. + const outputDir = join('apps', 'web', '.next', 'standalone', 'apps', 'web'); + const planted = `planted after the step build of ${sha}`; + const kept: Record = {}; + const run = await repoJob( + sha, + { PLX_TURBO_SHARED: '', PLX_TURBO_SHARED_TOKEN: '', PLX_TURBO_TRUSTED: '', PLX_TURBO_TRUSTED_TOKEN: '' }, + (step, job) => { + const file = join(job, outputDir, 'planted.txt'); + if (step === 'mise run build') writeFileSync(file, planted); + if (step === 'e2e' || step === 'mise run publish') + kept[step] = existsSync(file) && readFileSync(file, 'utf8') === planted; + }, + ); + const failure = run.done.find((d) => d.conclusion === 'failure'); + assert.ok(run.ok, `${failure?.step} failed:\n${failure?.output}`); + const build = of(run, 'mise run build').output; + const web = [...build.matchAll(executed('@acme/web:build'))].map((m) => m[1]); + assert.equal(web.length, 1, build); + assert.equal([...build.matchAll(executed('@acme/site:build'))].length, 1, build); + for (const step of ['e2e', 'mise run publish']) { + const output = of(run, step).output; + assert.match(output, /@acme\/web:build/, `${step} asks for web's build`); + const again = [...output.matchAll(executed('@acme/\\w+:build'))].map((m) => m[0]); + assert.deepEqual(again, [], `${step} built again:\n${output}`); + } + const publish = of(run, 'mise run publish').output; + assert.match(publish, new RegExp(`${registry}/acme/web:build-${web[0]} is missing, building it`), publish); + assert.match(publish, new RegExp(`${registry}/acme/site:build-${hashes.site} is there already, tagging it ${sha}`)); + // The directory e2e ran against is the one the step build made, and the image holds that directory. + assert.deepEqual(kept, { e2e: true, 'mise run publish': true }); + const cat = ['run', '--rm', '-q', '--network', 'none', '--entrypoint', 'cat', `${registry}/acme/web:${sha}`]; + assert.equal(await sh('docker', [...cat, '/repo/apps/web/planted.txt'], here), planted); +}); + test('where a suite fails, the step after e2e keeps that suite’s results alone, and publish does not run', async () => { const sha = await push('push-3', (dir) => { put(dir, { diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index cb2dcbdf..f61420cf 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -30,6 +30,16 @@ const SHAPES: [string, Record][] = [ ['github', {}], ['infrastructure', { infrastructure: 'true', ci_strategy: 'byom', pr_reviewers: 'reviewer-a,reviewer-b' }], ['byom', { ci_strategy: 'byom', ci_overlay: 'netbird' }], + // The state in a bucket of an S3-compatible store: `check` sets the root up with `init -backend=false`, which reaches none. + [ + 'byom-bucket', + { + ci_strategy: 'byom', + ci_state_bucket: 'acme-state', + ci_state_endpoint: 'https://s3.storage.example.test', + ci_state_region: 'eu-one', + }, + ], ]; /** @@ -174,6 +184,7 @@ const USUAL = ` slots = { repo = { count = 2, memory = "4g" } location = "fsn1" ssh_source_ips = [] turbo_cache_overlay = false + connect_server = false overlay_management_url = "" iam_admins = [{ name = "alice", ssh_keys = ["ssh-ed25519 AAAA alice"] }] ssh_keys = ["key-a"]`; @@ -196,7 +207,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an const run = (...args: string[]) => tryRun('mise', ['run', 'ci-hosts', '--', ...args], dir, refused); const init = await tryRun('mise', ['run', 'ci-hosts', '--', 'init', '-input=false'], dir, env); assert.ok(init.ok, init.output); - const second = `{ slots = { delivery = { count = 1, memory = "2g" } }, server_type = "cpx52", location = "nbg1", ssh_source_ips = ["203.0.113.0/24"], turbo_cache_overlay = true, overlay_management_url = "https://overlay.example", iam_admins = [{ name = "bob", ssh_keys = ["ssh-ed25519 BBBB bob"] }], ssh_keys = ["key-b"] }`; + const second = `{ slots = { delivery = { count = 1, memory = "2g" } }, server_type = "cpx52", location = "nbg1", ssh_source_ips = ["203.0.113.0/24"], turbo_cache_overlay = true, connect_server = true, overlay_management_url = "https://overlay.example", iam_admins = [{ name = "bob", ssh_keys = ["ssh-ed25519 BBBB bob"] }], ssh_keys = ["key-b"] }`; writeHosts(dir, USUAL, ` "ci-1" = {}\n "ci-2" = ${second}`); const planned = await run('plan', '-no-color', '-input=false'); assert.ok(planned.ok, planned.output); @@ -209,6 +220,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an location: 'nbg1', ssh_source_ips: '203.0.113.0/24', turbo_cache_overlay: /turbo_cache_overlay\s+= true/, + connect_server: /connect_server\s+= true/, overlay_management_url: 'https://overlay.example', iam_admins: 'bob', ssh_keys: 'key-b', @@ -219,6 +231,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an location: 'fsn1', ssh_source_ips: /ssh_source_ips\s+= \[\]/, turbo_cache_overlay: /turbo_cache_overlay\s+= false/, + connect_server: /connect_server\s+= false/, overlay_management_url: /overlay_management_url\s+= ""/, iam_admins: 'alice', ssh_keys: 'key-a', @@ -286,7 +299,13 @@ test('a host’s own value wins over the default, attribute by attribute, and an }); /** Terraform's diagnostics, wrapped and boxed, on one line. */ -const flat = (output: string): string => output.replace(/[│╷╵]/g, ' ').replace(/\s+/g, ' '); +// Terraform wraps and colours its errors, and where it wraps follows the message's length: the colour codes of the frame must not split a phrase. +const flat = (output: string): string => + output + // biome-ignore lint/suspicious/noControlCharactersInRegex: the escape that starts a colour code + .replace(/\x1B\[[0-9;]*m/g, '') + .replace(/[│╷╵]/g, ' ') + .replace(/\s+/g, ' '); /** A git repository of two tagged versions of this checkout's modules, `v1` and `v2`, which a root names as `git::file://…?ref=`. */ async function moduleRepo(dir: string): Promise { diff --git a/newborns/runner-host-mail.test.ts b/newborns/runner-host-mail.test.ts new file mode 100644 index 00000000..d853cf84 --- /dev/null +++ b/newborns/runner-host-mail.test.ts @@ -0,0 +1,683 @@ +// What a runner host mails its tenant, set up by one run of plexus.ci.playbook +// on itself as runner-host.test.ts sets one up (its header says how), with the +// same stand-ins for the vault's CLI and the forge, and two more: a mail relay +// on the host's loopback that takes STARTTLS and AUTH, as a tenant's relay +// does, and records every message it is handed, and a runner that waits for a +// job that never comes, in place of a slot's container. The forge refuses to +// mint a slot's runner config, or keeps the minting waiting, when the test +// says so. The relay's address, credentials, sender and recipient are the +// vault's item mail-relay. +// +// A host whose vault has no mail-relay, or one that lacks a field, leaves one +// empty, names a port that is no number or a mode Postfix does not know, is +// set up all the same, runs its slots, and says in its journal that it sends +// no mail and why; a field given on the command line counts. So is a host whose mail role fails, here +// on a Postfix that cannot be installed. With the item, the host mails +// through the relay, with the item's credentials, from its sender to its +// recipient, and takes no mail over SMTP from what shares its loopback, the +// slots included: one mail for a unit that fails (BuildKit, a cache server, a +// slot's container), one for a disk fuller than the threshold whatever the +// housekeeping failed at before, none for a slot whose minting failed once, +// and one, saying for how long, for a slot whose minting has failed for +// longer than the threshold the run gives (actions_runners_slot_alert_after), +// whatever its container failed at before; never one per attempt. The row of +// failed mintings fails towards mailing: a row that holds no number or a +// threshold that is none mails at once, a stop between two attempts leaves no +// row for the next start, and a minting systemd ends for its time counts. A +// relay that refuses is said in the journal, and the host is set up all the +// same. The SMTP port on loopback opens again and closes again with +// mail_loopback_smtp. Nothing reaches a real vault, App, relay or mailbox. +// Needs Docker and the network, as the newborns do. +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { close, open, put, sh, tryRun, until } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const NAME = 'runner-a'; +const IMAGE = 'plx-newborn-runner-host-ansible:trixie'; +const DOCKERFILE = `FROM debian:trixie +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \\ + systemd systemd-sysv dbus ansible python3-apt iproute2 ca-certificates curl openssl openssh-server sudo \\ + && rm -rf /var/lib/apt/lists/* +CMD ["/sbin/init"] +`; +const TOKEN = 'a-service-account-token'; +const VAULT: Record = { + 'github-app/client-id': 'vault-app-client-id', + 'bucket-turbo/endpoint': 'http://127.0.0.1:9', + 'bucket-turbo/region': 'us-east-1', + 'bucket-turbo/access-key-id': 'vault-shared-access-key', + 'bucket-turbo/secret-access-key': 'vault-shared-secret-key', + 'bucket-turbo-trusted/access-key-id': 'vault-trusted-access-key', + 'bucket-turbo-trusted/secret-access-key': 'vault-trusted-secret-key', +}; +/** The item that names the relay, which the vault holds from the second run on. */ +const RELAY: Record = { + 'mail-relay/server': '127.0.0.1', + 'mail-relay/port': '2525', + 'mail-relay/mode': 'starttls', + 'mail-relay/username': 'vault-relay-username', + 'mail-relay/password': 'vault-relay-password', + 'mail-relay/from-address': 'ci-hosts@example.org', + 'mail-relay/mailto': 'alerts@example.org', +}; +const OP = `#!/bin/sh +[ -n "\${OP_SERVICE_ACCOUNT_TOKEN:-}" ] || { echo "op: no service account token" >&2; exit 1; } +[ "$1" = read ] || { echo "op stand-in: only read" >&2; exit 2; } +for ref; do :; done +file=/stand-in/vault/\${ref#op://} +[ -f "$file" ] || { echo "[ERROR] could not read secret '$ref'" >&2; exit 1; } +cat "$file" +`; +/** + * The forge, as far as ci-runner-jit asks it. A minting is refused (500) while + * /var/lib/stand-in/refuse-mint says `always`, or as many times as the number + * it holds, and keeps it waiting for a minute while /var/lib/stand-in/hang-mint + * exists; each minting it answers, and each it refuses, is a line of a log. + */ +const FORGE = `import http.server, json, os, ssl, time +REFUSE = "/var/lib/stand-in/refuse-mint" +def refused(): + try: + left = open(REFUSE).read().strip() + except FileNotFoundError: + return False + if left == "always": return True + if int(left) <= 0: return False + open(REFUSE, "w").write(str(int(left) - 1)) + return True +class Api(http.server.BaseHTTPRequestHandler): + def answer(self, status, body): + data = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + def do_GET(self): + if self.path.endswith("/installation"): return self.answer(200, {"id": 1}) + if "/runner-groups" in self.path: return self.answer(200, {"runner_groups": [{"id": 1, "name": "Default"}]}) + if "/actions/runners?" in self.path: return self.answer(200, {"runners": []}) + self.answer(404, {}) + def do_POST(self): + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if self.path.endswith("/access_tokens"): return self.answer(201, {"token": "t"}) + if self.path.endswith("/generate-jitconfig"): + if os.path.exists("/var/lib/stand-in/hang-mint"): time.sleep(60) + refuse = refused() + with open("/var/log/forge-stand-in.jsonl", "a") as log: + log.write(json.dumps({"name": json.loads(body)["name"], "refused": refuse}) + "\\n") + if refuse: return self.answer(500, {"message": "stand-in refuses"}) + return self.answer(201, {"encoded_jit_config": "e30="}) + self.answer(404, {}) + def log_message(self, *args): pass +server = http.server.ThreadingHTTPServer(("127.0.0.1", 443), Api) +context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +context.load_cert_chain("/etc/forge-stand-in/api.crt", "/etc/forge-stand-in/api.key") +server.socket = context.wrap_socket(server.socket, server_side=True) +server.serve_forever() +`; +/** + * The tenant's mail relay on 127.0.0.1:2525: STARTTLS with a certificate of + * its own, then AUTH PLAIN or LOGIN, which it refuses (535) while + * /var/lib/stand-in/relay-refuse exists; a message only after AUTH. Each + * message it takes is a line of a log: the credentials, the envelope, the text. + */ +const RELAY_SERVER = `import base64, json, os, re, socketserver, ssl +CONTEXT = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +CONTEXT.load_cert_chain("/etc/relay-stand-in/relay.crt", "/etc/relay-stand-in/relay.key") +class Session(socketserver.StreamRequestHandler): + def reply(self, line): + self.wfile.write((line + "\\r\\n").encode()) + self.wfile.flush() + def read(self): + return self.rfile.readline().decode(errors="replace").rstrip("\\r\\n") + def handle(self): + tls, auth, sender, recipients = False, None, None, [] + self.reply("220 relay.example.org ESMTP stand-in") + while True: + line = self.read() + if not line: return + verb, _, arg = line.partition(" ") + verb = verb.upper() + if verb in ("EHLO", "HELO"): + offers = ["relay.example.org"] + (["AUTH PLAIN LOGIN"] if tls else ["STARTTLS"]) + for i, offer in enumerate(offers): self.reply(("250 " if i == len(offers) - 1 else "250-") + offer) + elif verb == "STARTTLS" and not tls: + self.reply("220 2.0.0 go ahead") + self.connection = CONTEXT.wrap_socket(self.connection, server_side=True) + self.rfile = self.connection.makefile("rb") + self.wfile = self.connection.makefile("wb") + tls = True + elif verb == "AUTH" and tls: + mechanism, _, initial = arg.partition(" ") + if mechanism.upper() == "PLAIN": + if not initial: + self.reply("334 ") + initial = self.read() + _, username, password = base64.b64decode(initial).decode().split("\\0") + else: + self.reply("334 VXNlcm5hbWU6") + username = base64.b64decode(self.read()).decode() + self.reply("334 UGFzc3dvcmQ6") + password = base64.b64decode(self.read()).decode() + if os.path.exists("/var/lib/stand-in/relay-refuse"): + self.reply("535 5.7.8 Authentication credentials invalid") + else: + auth = {"username": username, "password": password} + self.reply("235 2.7.0 Authentication successful") + elif verb == "MAIL": + if not auth: + self.reply("530 5.7.0 Authentication required") + continue + sender, recipients = re.search(r"<([^>]*)>", arg).group(1), [] + self.reply("250 2.1.0 Ok") + elif verb == "RCPT": + recipients.append(re.search(r"<([^>]*)>", arg).group(1)) + self.reply("250 2.1.5 Ok") + elif verb == "DATA": + self.reply("354 End data with .") + text = [] + while True: + data = self.read() + if data == ".": break + text.append(data[1:] if data.startswith("..") else data) + with open("/var/log/relay-stand-in.jsonl", "a") as log: + log.write(json.dumps({"auth": auth, "from": sender, "to": recipients, "text": "\\n".join(text)}) + "\\n") + self.reply("250 2.0.0 Ok: queued") + elif verb == "RSET": + sender, recipients = None, [] + self.reply("250 2.0.0 Ok") + elif verb == "NOOP": + self.reply("250 2.0.0 Ok") + elif verb == "QUIT": + self.reply("221 2.0.0 Bye") + return + else: + self.reply("502 5.5.2 Error: command not recognized") +class Server(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True +Server(("127.0.0.1", 2525), Session).serve_forever() +`; +/** A slot's runner, waiting for a job that never comes; a stop ends it as docker run reports SIGTERM. */ +const RUNNER = `#!/bin/sh +trap 'exit 143' TERM +while :; do sleep 1 & wait $!; done +`; +const CERTIFICATES = `set -eu +mkdir -p /etc/forge-stand-in && cd /etc/forge-stand-in +openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 2 -subj /CN=stand-in-ca 2>/dev/null +openssl req -newkey rsa:2048 -nodes -keyout api.key -out api.csr -subj /CN=api.github.com 2>/dev/null +printf 'subjectAltName=DNS:api.github.com\\nextendedKeyUsage=serverAuth\\n' >ext +openssl x509 -req -in api.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out api.crt -days 2 -extfile ext 2>/dev/null +cp ca.crt /usr/local/share/ca-certificates/forge-stand-in.crt && update-ca-certificates >/dev/null +mkdir -p /etc/relay-stand-in && cd /etc/relay-stand-in +openssl req -x509 -newkey rsa:2048 -nodes -keyout relay.key -out relay.crt -days 2 -subj /CN=relay.example.org 2>/dev/null +mkdir -p /var/lib/stand-in +`; +/** The threshold the run gives, in seconds: past it a slot that cannot mint mails. */ +const ALERT_AFTER = 60; +const VALUES = { + ci_owner: 'acme', + actions_runners_slots: { repo: { count: 1, memory: '1g' } }, + actions_runners_image: 'busybox:1.37', + netbird_enabled: false, + base_kernel_hardening: false, + actions_runners_slot_alert_after: ALERT_AFTER, +}; +const SLOT = 'ci-runner@repo-1.service'; +/** The unit that says a slot cannot register, of a mail budget apart from the slot's. */ +const CANNOT = 'ci-runner-cannot-register@repo-1.service'; +/** The row of the slot's failed mintings. */ +const ROW = '/run/ci-runner/repo-1.failing'; + +let here = ''; +let host = ''; +let adminKey = ''; + +const onHost = (...command: string[]) => sh('docker', ['exec', host, ...command], here); +const shellOnHost = (line: string) => tryRun('docker', ['exec', host, 'sh', '-c', line], here); + +before(async () => { + here = await open('runner-host-mail', { registry: false }); + put(here, { + 'image/Dockerfile': DOCKERFILE, + 'stand-in/bin/op': OP, + 'stand-in/forge.py': FORGE, + 'stand-in/relay.py': RELAY_SERVER, + 'stand-in/runner': RUNNER, + }); + for (const [field, value] of Object.entries(VAULT)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + await sh('chmod', ['+x', join(here, 'stand-in/bin/op'), join(here, 'stand-in/runner')], here); + await sh('docker', ['build', '-q', '-t', IMAGE, join(here, 'image')], here); + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--name', + `plx-newborn-${process.pid}-runner-host-mail`, + '--privileged', + '--cgroupns=private', + '--hostname', + NAME, + '--add-host', + 'api.github.com:127.0.0.1', + '--tmpfs', + '/run', + '--tmpfs', + '/run/lock', + '-v', + '/var/lib/docker', + '-v', + '/var/lib/buildkit', + '--cpus', + '4', + '--memory', + '6g', + '--pids-limit', + '2000', + '-v', + `${join(WORKSPACE, 'ansible')}:/collections/ansible_collections/plexus:ro`, + '-v', + `${join(here, 'stand-in')}:/stand-in`, + IMAGE, + ], + here, + ) + ).match(/^[0-9a-f]{64}$/m); + host = started?.[0] ?? ''; + if (!host) throw new Error('docker run printed no container id'); + await until('the host to finish booting', async () => { + const state = await tryRun('docker', ['exec', host, 'systemctl', 'is-system-running', '--wait'], here); + return /^(running|degraded)$/m.test(state.output); + }); + await onHost('sh', '-c', CERTIFICATES); + await onHost('systemd-run', '--unit', 'forge-stand-in', 'python3', '/stand-in/forge.py'); + await onHost('systemd-run', '--unit', 'relay-stand-in', 'python3', '/stand-in/relay.py'); + await onHost('sh', '-c', 'openssl genrsa -out /stand-in/vault/acme-ci-host/github-app/private-key 2048 2>/dev/null'); + await onHost('ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'ada@example.invalid', '-f', '/root/ada'); + adminKey = (await onHost('cat', '/root/ada.pub')).trim(); + // The slots run the stand-in runner in place of a container, from their first start. + await onHost( + 'sh', + '-c', + 'mkdir -p /etc/systemd/system/ci-runner@.service.d && printf "[Service]\\nExecStart=\\nExecStart=/stand-in/runner %%i\\n" >/etc/systemd/system/ci-runner@.service.d/stand-in.conf', + ); +}); + +after(async () => { + if (host) await tryRun('docker', ['rm', '-f', '-v', host], here); + await close(); +}); + +/** One run of the playbook on the host as its user-data starts it; unfailing. */ +async function play(args: string[] = []) { + return tryRun( + 'docker', + [ + 'exec', + host, + 'env', + `OP_SERVICE_ACCOUNT_TOKEN=${TOKEN}`, + 'PATH=/stand-in/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + 'ANSIBLE_COLLECTIONS_PATH=/collections', + 'ANSIBLE_NOCOLOR=1', + 'ansible-playbook', + 'plexus.ci.playbook', + '-e', + JSON.stringify({ ...VALUES, iam_admins: [{ name: 'ada', ssh_keys: [adminKey] }] }), + ...args, + ], + here, + ); +} + +interface Mail { + auth: { username: string; password: string } | null; + from: string; + to: string[]; + text: string; +} +/** A message's headers and its body as read, decoded where it is quoted-printable (systemctl's status is UTF-8). */ +function readable(text: string): string { + const end = text.indexOf('\n\n'); + const [head, body] = end < 0 ? [text, ''] : [text.slice(0, end), text.slice(end + 2)]; + if (!/^Content-Transfer-Encoding: quoted-printable$/im.test(head)) return text; + const bytes = body + .replace(/=\n/g, '') + .replace(/=([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))); + return `${head}\n\n${Buffer.from(bytes, 'latin1').toString('utf8')}`; +} +/** Every message the relay has taken, its text readable. */ +async function mails(): Promise { + const log = (await shellOnHost('cat /var/log/relay-stand-in.jsonl 2>/dev/null')).output.trim(); + if (!log) return []; + return log.split('\n').map((line) => { + const mail: Mail = JSON.parse(line); + return { ...mail, text: readable(mail.text) }; + }); +} +/** The messages whose subject names the unit. */ +const about = async (unit: string) => + (await mails()).filter((mail) => new RegExp(`^Subject: .*${unit.replace(/[.@]/g, '\\$&')}`, 'm').test(mail.text)); +/** Until the relay has one message about the unit; that message. */ +async function oneMailAbout(unit: string, limit = 90_000): Promise { + await until(`a mail about ${unit}`, async () => (await about(unit)).length > 0, limit); + return (await about(unit))[0] as Mail; +} +/** Until nothing is left to send: no failure mail being written, and Postfix's queue empty. */ +async function settled() { + await until( + 'the host to have sent what it had', + async () => { + const writing = await shellOnHost('systemctl list-units --plain --no-legend "failure-mail@*" --state=activating'); + const queue = await shellOnHost('mailq'); + return writing.output.trim() === '' && /Mail queue is empty/.test(queue.output); + }, + 120_000, + ); +} +/** A slot's mintings the forge answered or refused, in order. */ +async function mintings(): Promise<{ name: string; refused: boolean }[]> { + const log = (await shellOnHost('cat /var/log/forge-stand-in.jsonl 2>/dev/null')).output.trim(); + return log ? log.split('\n').map((line) => JSON.parse(line)) : []; +} +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +/** What the playbook said last in the journal. */ +const lastSaid = async () => + (await onHost('journalctl', '--no-pager', '-t', 'plexus-ci', '-o', 'cat', '-n', '1')).trim(); +/** Until the slot runs. */ +const slotRuns = () => + until( + 'the slot to run again', + async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', + 180_000, + ); + +describe('a runner host mails its tenant', () => { + test('a host whose vault has no item mail-relay is set up all the same, runs its slots, and says in its journal that it sends no mail', async () => { + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT, 'ci-buildkit')).trim(), 'active\nactive'); + const journal = await onHost('journalctl', '--no-pager', '-t', 'plexus-ci'); + assert.match(journal, /sends no mail/); + assert.match(journal, /acme-ci-host/); + assert.match(journal, /mail-relay/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + }); + + test('an item that lacks a field, leaves one empty, names a port that is no number or an unknown mode is no item: the run passes and the journal says what is wrong; a field given on the command line counts', async () => { + const partial: Record = { + ...RELAY, + 'mail-relay/username': '', + 'mail-relay/port': 'twenty-five', + 'mail-relay/mode': 'pigeon', + }; + delete partial['mail-relay/mailto']; + for (const [field, value] of Object.entries(partial)) + put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + try { + const ran = await play(['-e', JSON.stringify({ ci_mail_mailto: 'alerts@example.org' })]); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + const said = await lastSaid(); + assert.match(said, /sends no mail/); + assert.match(said, /\busername\b/); + assert.match(said, /\btwenty-five\b/); + assert.match(said, /\bpigeon\b/); + assert.doesNotMatch(said, /mailto/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + } finally { + await onHost('rm', '-r', '/stand-in/vault/acme-ci-host/mail-relay'); + } + }); + + test('a mail role that fails, as where Postfix cannot be installed, fails no run: the slots run, and the journal says the host sends no mail', async () => { + for (const [field, value] of Object.entries(RELAY)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + await onHost( + 'sh', + '-c', + 'printf "Package: postfix\\nPin: version *\\nPin-Priority: -1\\n" >/etc/apt/preferences.d/stand-in-no-postfix', + ); + try { + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + const said = await lastSaid(); + assert.match(said, /sends no mail/); + assert.match(said, /plexus\.host\.mail/); + assert.equal((await shellOnHost('dpkg -s postfix')).ok, false); + } finally { + await onHost('rm', '/etc/apt/preferences.d/stand-in-no-postfix'); + } + }); + + test('with the item, a run at -vvv passes and prints none of it, and the host takes no mail over SMTP from its loopback, which the slots share', async () => { + for (const [field, value] of Object.entries(RELAY)) put(here, { [`stand-in/vault/acme-ci-host/${field}`]: value }); + const ran = await play(['-vvv']); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + for (const field of ['username', 'password']) + assert.equal(ran.output.includes(RELAY[`mail-relay/${field}`] ?? '?'), false, field); + assert.equal((await onHost('systemctl', 'is-active', 'postfix')).trim(), 'active'); + assert.equal((await onHost('ss', '-Hltn', 'sport = :25')).trim(), ''); + }); + + test('a unit that fails, BuildKit or a cache server, is one mail each, through the relay with the item’s credentials, from its sender to its recipient', async () => { + for (const unit of ['ci-buildkit.service', 'ci-turbo-cache@shared.service']) { + await onHost('systemctl', 'kill', '--signal=SIGKILL', unit); + const mail = await oneMailAbout(unit); + assert.deepEqual(mail.auth, { username: 'vault-relay-username', password: 'vault-relay-password' }); + assert.equal(mail.from, 'ci-hosts@example.org'); + assert.deepEqual(mail.to, ['alerts@example.org']); + assert.match(mail.text, new RegExp(`^Subject: \\[${NAME}\\] `, 'm')); + } + await settled(); + assert.equal((await about('ci-buildkit.service')).length, 1); + assert.equal((await about('ci-turbo-cache@shared.service')).length, 1); + }); + + test('a disk fuller than the threshold is one mail that says how full, however often it is found, and whatever the housekeeping failed at before that day', async () => { + // The disk is the test machine's: the threshold goes under what it holds instead. + const used = Number((await onHost('sh', '-c', "df --output=pcent / | tail -1 | tr -dc '0-9'")).trim()); + const threshold = Math.max(used - 1, 0); + const units = '/etc/systemd/system'; + await onHost( + 'sh', + '-c', + `mkdir -p ${units}/ci-runner-housekeeping.service.d ${units}/ci-runner-disk.service.d && printf "[Service]\\nEnvironment=IMAGE=127.0.0.1:9/nowhere:1\\n" >${units}/ci-runner-housekeeping.service.d/stand-in.conf && printf "[Service]\\nEnvironment=DISK_ALERT_PERCENT=${threshold}\\n" >${units}/ci-runner-disk.service.d/stand-in.conf && systemctl daemon-reload`, + ); + try { + // A pull that fails, earlier the same day: the housekeeping's one mail of the day. + assert.equal((await shellOnHost('systemctl start ci-runner-housekeeping.service')).ok, false); + await oneMailAbout('ci-runner-housekeeping.service'); + for (let run = 0; run < 2; run++) + assert.equal((await shellOnHost('systemctl start ci-runner-disk.service')).ok, false); + const mail = await oneMailAbout('ci-runner-disk.service'); + assert.match(mail.text, /root file system \d+% used/); + assert.match(mail.text, new RegExp(`above ${threshold}%`)); + await settled(); + assert.equal((await about('ci-runner-disk.service')).length, 1); + assert.equal((await about('ci-runner-housekeeping.service')).length, 1); + } finally { + await shellOnHost( + `rm -r ${units}/ci-runner-housekeeping.service.d ${units}/ci-runner-disk.service.d; systemctl daemon-reload; systemctl reset-failed ci-runner-housekeeping.service ci-runner-disk.service`, + ); + } + }); + + test('a slot whose container fails is one mail at once, as any unit', async () => { + await onHost('systemctl', 'kill', '--signal=SIGKILL', '--kill-whom=main', SLOT); + await oneMailAbout(SLOT, 60_000); + await settled(); + assert.equal((await about(SLOT)).length, 1); + await slotRuns(); + }); + + test('a slot whose minting fails once mails nobody; one whose minting has failed for longer than the threshold mails once, saying for how long, although its container failed the same day', async () => { + const before = (await mintings()).length; + // One failed attempt: ci-runner-jit asks three times before it gives up. + await onHost('sh', '-c', 'echo 3 >/var/lib/stand-in/refuse-mint'); + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'the slot to mint again after one failed attempt', + async () => { + const since = (await mintings()).slice(before); + return since.some((minting) => minting.refused) && since.at(-1)?.refused === false; + }, + 180_000, + ); + await until( + 'the slot to run again', + async () => (await shellOnHost(`systemctl is-active ${SLOT}`)).output.trim() === 'active', + ); + await sleep((ALERT_AFTER + 15) * 1000); + await settled(); + assert.equal((await about(SLOT)).length, 1, 'the container’s mail alone'); + assert.deepEqual(await about(CANNOT), []); + + await onHost('sh', '-c', 'echo always >/var/lib/stand-in/refuse-mint'); + try { + const refusedFrom = Date.now(); + await onHost('systemctl', 'restart', '--no-block', SLOT); + const mail = await oneMailAbout(CANNOT, 5 * 60_000); + assert.ok(Date.now() - refusedFrom >= ALERT_AFTER * 1000, 'mailed before the threshold'); + assert.match(mail.text, /has failed .*for 1 min/); + // Two more attempts, each refused: no further mail. + const attempts = (await mintings()).length; + await until('two more refused attempts', async () => (await mintings()).length >= attempts + 6, 180_000); + await settled(); + assert.equal((await about(CANNOT)).length, 1); + assert.equal((await about(SLOT)).length, 1, 'the container’s mail alone'); + } finally { + await onHost('rm', '-f', '/var/lib/stand-in/refuse-mint'); + } + await slotRuns(); + }); + + test('the row of a slot’s failed mintings fails towards mailing: a row that holds no number, or a threshold that is none, mails at once and says so', async () => { + // By hand, for a slot this host does not run. + const row = '/run/ci-runner/repo-9.failing'; + const now = (minus = 0) => `read up _ ${row}`; + const cannot = (after = '60') => + shellOnHost(`ALERT_AFTER=${after} /usr/local/sbin/ci-runner-cannot-register repo-9 2>&1`); + const hold = () => shellOnHost('/usr/local/sbin/ci-runner-mail-hold ci-runner@repo-9.service 2>&1'); + try { + // No row: nothing to say, and a failure of the slot is mailed. + await onHost('rm', '-f', row); + assert.equal((await cannot()).ok, true); + assert.equal((await hold()).ok, true); + // A row younger than the threshold: no mail yet, of either. + await onHost('sh', '-c', `mkdir -p /run/ci-runner && ${now()}`); + assert.equal((await cannot()).ok, true); + assert.equal((await hold()).ok, false); + // Older: the mail, which says for how long. + await onHost('sh', '-c', now(150)); + const old = await cannot(); + assert.equal(old.ok, false); + assert.match(old.output, /for 2 min \d+ s/); + // A row that holds no number: both mail, and the mail says what the row holds. + await onHost('sh', '-c', `echo garbage >${row}`); + const garbage = await cannot(); + assert.equal(garbage.ok, false); + assert.match(garbage.output, /garbage/); + assert.equal((await hold()).ok, true); + // A threshold that is no number: the mail, which says so. + await onHost('sh', '-c', now()); + const soon = await cannot('soon'); + assert.equal(soon.ok, false); + assert.match(soon.output, /soon/); + } finally { + await onHost('rm', '-f', row); + } + }); + + test('a slot stopped between two failed attempts starts a new row when it is started again', async () => { + // A wait between the attempts long enough to stop the slot in. + const gap = '/etc/systemd/system/ci-runner@.service.d/stand-in-gap.conf'; + await onHost( + 'sh', + '-c', + `printf "[Service]\\nRestartSec=40s\\n" >${gap} && systemctl daemon-reload && echo always >/var/lib/stand-in/refuse-mint`, + ); + try { + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'the slot to wait between two attempts', + async () => (await shellOnHost(`systemctl show -P SubState ${SLOT}`)).output.trim() === 'auto-restart', + 180_000, + ); + const first = (await onHost('cat', ROW)).trim(); + await onHost('systemctl', 'stop', SLOT); + assert.equal((await onHost('cat', ROW)).trim(), first, 'the stop came between two attempts'); + await sleep(2000); + const attempts = (await mintings()).length; + await onHost('systemctl', 'start', '--no-block', SLOT); + await until('a new attempt', async () => (await mintings()).length > attempts, 120_000); + assert.notEqual((await onHost('cat', ROW)).trim(), first); + } finally { + await onHost('sh', '-c', `rm -f ${gap} /var/lib/stand-in/refuse-mint && systemctl daemon-reload`); + } + await slotRuns(); + }); + + test('a minting that hangs until systemd ends it counts in the row', async () => { + const limit = '/etc/systemd/system/ci-runner@.service.d/stand-in-timeout.conf'; + await slotRuns(); + await onHost( + 'sh', + '-c', + `printf "[Service]\\nTimeoutStartSec=20s\\n" >${limit} && systemctl daemon-reload && touch /var/lib/stand-in/hang-mint`, + ); + try { + assert.equal((await shellOnHost(`test -e ${ROW}`)).ok, false, 'a row before the test'); + await onHost('systemctl', 'restart', '--no-block', SLOT); + await until( + 'systemd to end the minting', + async () => (await shellOnHost(`systemctl show -P Result ${SLOT}`)).output.trim() === 'timeout', + 120_000, + ); + assert.equal((await shellOnHost(`test -s ${ROW}`)).ok, true); + } finally { + await onHost('sh', '-c', `rm -f ${limit} /var/lib/stand-in/hang-mint && systemctl daemon-reload`); + } + await slotRuns(); + }); + + test('a relay that refuses is said in the journal, and the host is set up all the same', async () => { + await onHost('touch', '/var/lib/stand-in/relay-refuse'); + try { + const before = (await mails()).length; + await onHost('systemctl', 'kill', '--signal=SIGKILL', 'ci-turbo-cache@trusted.service'); + await until( + 'Postfix to say the relay refused', + async () => /535 5\.7\.8/.test((await shellOnHost('journalctl --no-pager -t postfix/smtp')).output), + 120_000, + ); + assert.equal((await mails()).length, before); + const ran = await play(); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await onHost('systemctl', 'is-active', SLOT)).trim(), 'active'); + } finally { + await onHost('rm', '-f', '/var/lib/stand-in/relay-refuse'); + } + }); + + test('mail_loopback_smtp true opens the SMTP port on loopback again, false closes it, and a run after that changes nothing there', async () => { + const listens = async () => (await onHost('ss', '-Hltn', 'sport = :25')).trim() !== ''; + const opened = await play(['--tags', 'mail', '-e', JSON.stringify({ mail_loopback_smtp: true })]); + assert.equal(opened.ok, true, opened.output.slice(-6000)); + await until('Postfix to listen on port 25', listens, 30_000); + const closed = await play(['--tags', 'mail']); + assert.equal(closed.ok, true, closed.output.slice(-6000)); + await until('Postfix to listen on port 25 no more', async () => !(await listens()), 30_000); + const again = await play(['--tags', 'mail']); + assert.equal(again.ok, true, again.output.slice(-6000)); + assert.match(again.output, /TASK \[plexus\.host\.mail : Close the SMTP port on loopback\][^\n]*\nok: /); + assert.equal(await listens(), false); + }); +}); diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index f3c17f3b..13b50952 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -20,7 +20,7 @@ const SERVICE_ACCOUNT = { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }; /** The vault's credentials each `op` call saw. */ const credentialsOf = (calls: ReturnType['calls']) => calls - .filter((c) => c.tool === 'op') + .filter((c) => c.tool === 'op' && c.args[0] === 'read') .map((c) => Object.keys(c.seen) .filter((k) => k.startsWith('OP_')) @@ -53,8 +53,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, the job fails in one line that names both, and nothing is read', () => { - const job = runJob(['repo'], { vault: VAULT }); +test('with neither, a deploy job fails in one line that names both, and nothing is read', () => { + const job = runJob(['deploy'], { 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/); @@ -93,7 +93,11 @@ test('the server-actions key is in no variable of the job', () => { test('a repo job is logged in to the forge’s image registry with its own token, in a Docker config of the job’s own', () => { const job = runJob(['repo'], { env: CONNECT, vault: VAULT }); assert.equal(job.status, 0, job.log); - assert.deepEqual(Object.keys(job.env), ['DOCKER_CONFIG']); + assert.deepEqual( + Object.keys(job.env), + ['DOCKER_CONFIG', 'PLX_TURBO_TRUSTED'], + 'and the local cache, as no server is named', + ); assert.equal(job.env.DOCKER_CONFIG, join(job.temp, 'docker')); const config = JSON.parse(readFileSync(join(job.temp, 'docker', 'config.json'), 'utf8')); const auth = Buffer.from('octocat:ghs_job').toString('base64'); @@ -260,7 +264,8 @@ test('under --dry-run a deploy job reads and masks, and calls nothing: no API, n assert.equal(job.status, 0, job.log); assert.deepEqual( job.calls.map((c) => c.tool), - ['op', 'op', 'op'], + ['op', 'op', 'op', 'op'], + 'the probe for op, then the three reads', ); assert.deepEqual([job.output, job.env], [{}, {}]); }); @@ -293,6 +298,7 @@ test('on a forge runner, a repo job of a repo with a cache host on netbird joins const job = runJob(['repo', '--overlay', 'netbird'], { env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, vault: { ...VAULT, ...OVERLAY_VAULT }, + cacheStatus: 200, }); assert.equal(job.status, 0, job.log); assert.deepEqual(job.env, { @@ -337,7 +343,8 @@ test('on a forge runner, a repo job joins nothing where the repo names no cache const job = runJob([...args], { env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...env }, vault: VAULT }); assert.equal(job.status, 0, job.log); assert.ok(!job.calls.some((c) => c.tool === 'netbird'), args.join(' ')); - assert.deepEqual(Object.keys(job.env), ['DOCKER_CONFIG'], args.join(' ')); + // And so it reaches no trusted server, and takes the local cache. + assert.deepEqual(Object.keys(job.env), ['DOCKER_CONFIG', 'PLX_TURBO_TRUSTED'], args.join(' ')); } }); @@ -388,3 +395,173 @@ test('a deploy job waits for the network map, never for the cache host its repo ); assert.ok(!opReads(job).some((ref) => /turbo-cache/.test(ref ?? '')), 'a deploy job reads no cache token'); }); + +/** A repo slot's environment: its host's two servers on loopback, and their tokens. */ +const SLOT_CACHES = { + PLX_TURBO_SHARED: 'http://127.0.0.1:8585', + PLX_TURBO_SHARED_TOKEN: 'slot-shared-token', + PLX_TURBO_TRUSTED: 'http://127.0.0.1:8586', + PLX_TURBO_TRUSTED_TOKEN: 'slot-trusted-token', +}; +/** The requests a job made of a cache server's status. */ +const asked = (job: ReturnType) => + job.calls.filter((c) => c.tool === 'curl' && /\/v8\/artifacts\/status"$/m.test(c.input ?? '')); + +test('a repo job that names no trusted server hands build, e2e and publish the job’s local cache, and asks nothing', () => { + for (const env of [ + CONNECT, + { ...SERVICE_ACCOUNT, ...FORGE_RUNNER }, + { ...CONNECT, ...SLOT, PLX_TURBO_TRUSTED: '', PLX_TURBO_CACHE_HOST: '' }, + ]) { + const job = runJob(['repo'], { env, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.PLX_TURBO_TRUSTED, 'local', JSON.stringify(env)); + assert.deepEqual(asked(job), []); + assert.match(job.log, /^without a trusted remote cache: the repo names no cache host.*the job’s local cache/m); + } +}); + +test('a repo job whose trusted server does not answer, or refuses the token, hands the job’s local cache', () => { + for (const cacheStatus of [undefined, 401, 500]) { + const job = runJob(['repo'], { env: { ...CONNECT, ...SLOT, ...SLOT_CACHES }, vault: VAULT, cacheStatus }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.PLX_TURBO_TRUSTED, 'local', String(cacheStatus)); + assert.equal(asked(job).length, 1, String(cacheStatus)); + assert.match(job.log, /^without a trusted remote cache: the trusted server does not answer/m); + assert.ok(!job.log.includes('127.0.0.1:8586'), 'the line names the case, not the server'); + } +}); + +test('with curl itself, a trusted server where nothing listens is one that does not answer', () => { + const job = runJob(['repo'], { + env: { ...CONNECT, ...SLOT, ...SLOT_CACHES, PLX_TURBO_TRUSTED: 'http://127.0.0.1:1' }, + vault: VAULT, + realCurl: true, + }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.PLX_TURBO_TRUSTED, 'local'); +}); + +test('a forge runner’s repo job whose join fails hands the job’s local cache', () => { + const job = runJob(['repo', '--overlay', 'netbird'], { + env: { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, + vault: { ...VAULT, ...OVERLAY_VAULT }, + netbirdFails: true, + cacheStatus: 200, + }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.PLX_TURBO_TRUSTED, 'local'); + assert.match(job.log, /^without a trusted remote cache: the job is not on the overlay, where the cache host is;/m); + assert.ok(!job.log.includes(':8586'), 'the line names the case, not the server'); +}); + +test('where the trusted server answers, nothing changes: the job is handed no local cache, and the token goes on stdin', () => { + for (const [env, server, token] of [ + [{ ...CONNECT, ...SLOT, ...SLOT_CACHES, ...CACHE_HOST }, 'http://127.0.0.1:8586', 'slot-trusted-token'], + [ + { ...SERVICE_ACCOUNT, ...FORGE_RUNNER, ...CACHE_HOST }, + 'http://cache.acme.internal:8586', + 'trusted-token-0123456789', + ], + ] as const) { + const job = runJob(['repo', '--overlay', 'netbird'], { + env, + vault: { ...VAULT, ...OVERLAY_VAULT }, + cacheStatus: 200, + }); + assert.equal(job.status, 0, job.log); + assert.ok(!('PLX_TURBO_TRUSTED' in job.env), server); + const [call, ...more] = asked(job); + assert.equal(more.length, 0, 'asked once, for the whole job'); + assert.deepEqual(call?.args, ['-K', '-']); + assert.match(call?.input ?? '', new RegExp(`^url = "${server.replaceAll('.', '\\.')}/v8/artifacts/status"$`, 'm')); + assert.match(call?.input ?? '', new RegExp(`^header = "Authorization: Bearer ${token}"$`, 'm')); + } +}); + +test('a trusted server named without its token is asked nothing and handed no local cache: turbow fails the verb', () => { + const job = runJob(['repo'], { + env: { ...CONNECT, ...SLOT, ...SLOT_CACHES, PLX_TURBO_TRUSTED_TOKEN: '' }, + vault: VAULT, + cacheStatus: 200, + }); + assert.equal(job.status, 0, job.log); + assert.ok(!('PLX_TURBO_TRUSTED' in job.env)); + assert.deepEqual(asked(job), []); +}); + +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, + cacheStatus: 200, + }); + assert.equal(deploy.status, 0, deploy.log); + assert.deepEqual(asked(deploy), []); + assert.ok(!('PLX_TURBO_TRUSTED' in deploy.env)); + const dry = runJob(['--dry-run', 'repo'], { env: { ...CONNECT, ...SLOT, ...SLOT_CACHES }, vault: VAULT }); + assert.equal(dry.status, 0, dry.log); + assert.deepEqual(asked(dry), []); + assert.deepEqual(dry.env, {}); +}); + +/** A run of a workflow of the repo as the forge starts it: its name, its event, and the branch or tag it runs on. */ +const RUN = (workflow: string, ref: string, event = 'workflow_dispatch', type = 'branch') => ({ + GITHUB_WORKFLOW: workflow, + GITHUB_EVENT_NAME: event, + GITHUB_REF_NAME: ref, + GITHUB_REF_TYPE: type, +}); + +for (const job of ['repo', 'deploy'] as const) { + test(`${job}: a run of on_push on a branch that deploys nowhere fails in one line naming the branch and the branches that deploy, before anything is read`, () => { + const run = runJob([job], { env: { ...CONNECT, ...RUN('on_push', 'feature-x') }, vault: VAULT }); + assert.equal(run.status, 1, run.log); + assert.deepEqual(run.calls, []); + assert.match(run.log, /on_push.*feature-x.*main.*develop/); + assert.equal(run.log.trim().split('\n').length, 1, run.log); + assert.deepEqual([run.output, run.env], [{}, {}]); + }); +} + +test('a branch named like a property of every object deploys nowhere either', () => { + const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'constructor') }, vault: VAULT }); + assert.equal(run.status, 1, run.log); + assert.deepEqual(run.calls, []); + assert.match(run.log, /on_push on constructor deploys nowhere/); +}); + +for (const tag of ['v1', 'main']) { + test(`a run of on_push on the tag ${tag} is refused, and the message says tag`, () => { + const run = runJob(['repo'], { + env: { ...CONNECT, ...RUN('on_push', tag, 'workflow_dispatch', 'tag') }, + vault: VAULT, + }); + assert.equal(run.status, 1, run.log); + assert.deepEqual(run.calls, []); + assert.match(run.log, new RegExp(`on_push on tag ${tag} deploys nowhere`)); + assert.equal(run.log.trim().split('\n').length, 1, run.log); + }); +} + +for (const [branch, event] of [ + ['main', 'push'], + ['develop', 'push'], + ['main', 'workflow_dispatch'], + ['develop', 'workflow_dispatch'], +]) { + test(`a run of on_push on ${branch} by ${event} is not refused`, () => { + const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', branch, event) }, vault: VAULT }); + assert.equal(run.status, 0, run.log); + }); +} + +for (const [workflow, event] of [ + ['on_commit', 'push'], + ['on_pr', 'pull_request'], +]) { + test(`a run of ${workflow} on a branch that deploys nowhere is not refused`, () => { + const run = runJob(['repo'], { env: { ...CONNECT, ...RUN(workflow, 'feature-x', event) }, vault: VAULT }); + assert.equal(run.status, 0, run.log); + }); +} diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index 430ef781..647575bd 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -7,7 +7,25 @@ // which is on the overlay already and whose repo slots carry their host's // cache servers. In order: // -// 1. Read from the vault `-ci` what the job needs, every read through +// 1. Refuse, before anything is read, a run of the workflow on_push (the +// forge's GITHUB_WORKFLOW) on a branch that deploys nowhere, or on a tag, +// as a run started by hand can be: the command fails in one line naming +// the branch and the branches that deploy. +// 2. Where the job has a credential for the vault (a Connect server or the +// service account's token) 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. 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 6 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, and a repo job of the workflow on_push, which publishes +// images that carry the repo's one key, fail there in a line that names +// the credentials missing. +// 3. 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 // service account otherwise, and masks each secret in the log as it @@ -22,37 +40,48 @@ // netbird`, also netbird/setup-key // A key pasted into a one-line field gets its lines back, and each of // them is masked as it is restored. -// 2. deploy: mint a token of the tenant's GitHub App that may read the +// 4. deploy: mint a token of the tenant's GitHub App that may read the // operations repo (`--operations-repo`, default `operations`) and // nothing else, and mask it. The App's key never leaves this process. // Where GitHub refuses the App (401) or finds it not installed on the // operations repo (404), the job fails in one line naming the App's // client ID and the repo. -// 3. Say how the vault was read. -// 4. repo: log the job in to the forge's image registry with its own token +// 5. Say how the vault was read. +// 6. repo: log the job in to the forge's image registry with its own token // (GITHUB_TOKEN as GITHUB_ACTOR), in a Docker config of the job's own // under RUNNER_TEMP, which buildx reads; with // `--private-packages`, to the forge's package registry too, in a // user-level npmrc there. Each file is 0600 in a directory 0700. // deploy: start an SSH agent on a socket under RUNNER_TEMP and add the // deploy key. -// 5. On a forge runner, where step 1 read a setup key: join the overlay as +// 7. On a forge runner, where step 3 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 // key reaches the app hosts and not the cache host). A repo job that // cannot join goes on without the remote cache and warns on the run; a // deploy job fails. -// 6. Hand later steps what they need. As outputs of the step: +// 8. repo: find the trusted cache server turbow would use for build, e2e and +// publish (PLX_TURBO_TRUSTED, else port 8586 of the cache host, which a +// forge runner reaches only where it joined) and ask it once, with the +// trusted token, as turbow does. Where none is named, the forge runner +// did not join, or the server does not answer 200 within two seconds, +// the job gets the variable PLX_TURBO_TRUSTED=local, and turbow gives the +// three verbs the local cache of the job's checkout: the step build +// builds each app once, and e2e and publish replay that build, which the +// image is made from. Asked once, so that every step keeps one answer. +// Where the server answers, or is named without a token (which turbow +// fails the verb for), nothing is handed and turbow works as ever. +// 9. Hand later steps what they need. As outputs of the step: // repo server-actions-key, for the build and publish steps alone // deploy operations-token, for the checkout of the operations repo // both joined=true, where the job joined the overlay // As variables of the job (GITHUB_ENV): DOCKER_CONFIG and, with private // packages, NPM_CONFIG_USERCONFIG; PLX_TURBO_SHARED_TOKEN and -// PLX_TURBO_TRUSTED_TOKEN where step 1 read them; SSH_AUTH_SOCK. No +// PLX_TURBO_TRUSTED_TOKEN where step 3 read them; SSH_AUTH_SOCK. No // secret of the vault is a variable of the job but the two cache tokens. // // Under --dry-run it reads and masks, calls no API, and writes and starts -// nothing. Exit code 1 where a read, the token or a deploy job's join fails. +// nothing. Exit code 1 where that refusal, a read, the token or a deploy job's join fails. // // plx-ci setup repo --overlay netbird --private-packages // plx-ci setup deploy --overlay netbird diff --git a/packages/cli-ci/src/commands/setupOp.test.ts b/packages/cli-ci/src/commands/setupOp.test.ts new file mode 100644 index 00000000..40830e06 --- /dev/null +++ b/packages/cli-ci/src/commands/setupOp.test.ts @@ -0,0 +1,232 @@ +// plx-ci setup on a runner that has no `op`: the forge's own runners carry none. A job with a token installs the +// pinned version from 1Password's download, verified against its signature, into the job's own temporary directory, +// and reads as before; a runner that has `op` is left as it is (§ 8.4 of the project's decisions). The fakes of +// testing/job.ts stand in for the download, gpg and `op`. +import assert from 'node:assert/strict'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { test } from 'node:test'; +import { OP_SIGNING_KEY, OP_VERSION } from '../core/op.ts'; +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' }; +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'; + +const tool = (calls: Call[], name: string) => calls.filter((c) => c.tool === name); +const downloads = (calls: Call[]) => tool(calls, 'curl').filter((c) => c.args.includes('--output')); +/** The vault reads and which `op` made them. */ +const reads = (calls: Call[]) => tool(calls, 'op').filter((c) => c.args[0] === 'read'); + +test('a job with a token on a runner without op downloads the pinned version, and reads the vault with it', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + assert.deepEqual( + downloads(job.calls).map((c) => c.args.at(-1)), + [ZIP, KEY], + ); + assert.equal(job.output['server-actions-key'], 'a-key'); + const [read, ...more] = reads(job.calls); + assert.equal(more.length, 0); + assert.equal(read?.path, join(job.temp, 'op', 'bin', 'op'), 'the vault is read by the installed op'); + assert.deepEqual(read?.seen, { OP_SERVICE_ACCOUNT_TOKEN: 'ops_service-account' }); + assert.match(job.log, new RegExp(`^installed op ${OP_VERSION.replaceAll('.', '\\.')}`, 'm')); +}); + +test('everything of the install is in the job’s own temporary directory, never in the checkout', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + const paths = [ + ...downloads(job.calls).map((c) => c.args[c.args.indexOf('--output') + 1] ?? ''), + ...tool(job.calls, 'unzip').map((c) => c.args[c.args.indexOf('-d') + 1] ?? ''), + ...tool(job.calls, 'gpg').map((c) => c.args[c.args.indexOf('--homedir') + 1] ?? ''), + ]; + assert.equal(paths.length, 5); + for (const path of paths) assert.ok(path.startsWith(`${job.temp}/`), path); +}); + +test('the download is verified before op is run: the signature against the pinned key, in a keyring of its own', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + const gpg = tool(job.calls, 'gpg'); + assert.deepEqual( + gpg.map((c) => c.args.find((a) => a === '--import' || a === '--verify')), + ['--import', '--verify'], + ); + const homes = new Set(gpg.map((c) => c.args[c.args.indexOf('--homedir') + 1])); + assert.equal(homes.size, 1, 'one keyring, the job’s, not the runner’s'); + const verify = gpg[1]?.args ?? []; + assert.deepEqual(verify.slice(-2), [join(job.temp, 'op', 'bin', 'op.sig'), join(job.temp, 'op', 'bin', 'op')]); + const order = job.calls.map((c) => `${c.tool}${c.args[0] === 'read' ? ' read' : ''}`); + assert.ok(order.indexOf('gpg') < order.indexOf('op read'), order.join(', ')); + assert.ok( + job.calls.findIndex((c) => c.tool === 'gpg' && c.args.includes('--verify')) < + job.calls.findIndex((c) => c.path.startsWith(job.temp)), + 'nothing the download holds is run before it is verified', + ); +}); + +test('a signature that does not verify fails the job in one line, and the vault is never read', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, gpgSigner: false }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, new RegExp(`op ${OP_VERSION.replaceAll('.', '\\.')} .*not .*signature`)); + assert.deepEqual(reads(job.calls), []); + assert.deepEqual(job.output, {}); +}); + +test('a signature made by another key than 1Password’s fails the job, whichever key the download offers', () => { + const job = runJob(['repo'], { + env: SERVICE_ACCOUNT, + vault: VAULT, + noOp: true, + gpgSigner: 'ABCDEF0123456789ABCDEF0123456789ABCDEF01', + }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /ABCDEF0123456789ABCDEF0123456789ABCDEF01/); + assert.ok(job.log.includes(OP_SIGNING_KEY), 'it names the key it expected'); + assert.deepEqual(reads(job.calls), []); +}); + +test('an op that is not the version it was downloaded as fails the job', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, opVersion: '2.0.1' }); + assert.equal(job.status, 1, job.log); + assert.match( + job.log, + new RegExp(`2\\.0\\.1.*${OP_VERSION.replaceAll('.', '\\.')}|${OP_VERSION.replaceAll('.', '\\.')}.*2\\.0\\.1`), + ); + assert.deepEqual(reads(job.calls), []); +}); + +test('a runner that has op is left as it is: nothing is downloaded, and the vault is read with its op', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT }); + assert.equal(job.status, 0, job.log); + for (const name of ['curl', 'unzip', 'gpg']) assert.deepEqual(tool(job.calls, name), [], name); + assert.ok(!/installed op/.test(job.log)); + const [read] = reads(job.calls); + assert.equal(dirname(read?.path ?? ''), dirname(tool(job.calls, 'op')[0]?.path ?? '')); + 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'); + 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'))); +}); + +test('a job without a token installs nothing, whether or not the runner has op', () => { + const job = runJob(['repo'], { env: { GITHUB_WORKFLOW: 'on_pr' }, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(downloads(job.calls), []); + assert.deepEqual(tool(job.calls, 'op'), []); +}); + +test('under --dry-run nothing is downloaded or written', () => { + const job = runJob(['--dry-run', 'repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.deepEqual(downloads(job.calls), []); + assert.deepEqual(tool(job.calls, 'unzip'), []); + assert.deepEqual(tool(job.calls, 'gpg'), []); + assert.match(job.log, /\[dry-run\].*op/); +}); + +test('the version is stated once in the code, and the environment image’s pin is the same', () => { + const image = readFileSync( + join(import.meta.dirname, '../../../../ansible/ci/roles/actions_runners/files/ci-runner/mise.toml'), + 'utf8', + ); + assert.match(image, new RegExp(`^"aqua:1password/cli" = "${OP_VERSION.replaceAll('.', '\\.')}"$`, 'm')); +}); + +/** What a tampered download can hold besides `op` and `op.sig`: a gpg configuration naming a program for the agent, and a file that climbs out. */ +const PLANTED = ['gnupg/gpg.conf', 'gpg.conf', '../../evil', 'agent']; + +test('only op and op.sig are taken from the zip, into a directory that holds nothing else', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, zipExtra: PLANTED }); + assert.equal(job.status, 0, job.log); + const [unzip] = tool(job.calls, 'unzip'); + const into = unzip?.args[unzip.args.indexOf('-d') + 1] ?? ''; + assert.deepEqual(unzip?.args.slice(unzip.args.indexOf('-d') - 2, unzip.args.indexOf('-d')), ['op', 'op.sig']); + assert.deepEqual(readdirSync(into).sort(), ['op', 'op.sig']); + const keyring = tool(job.calls, 'gpg')[0]?.args[tool(job.calls, 'gpg')[0]?.args.indexOf('--homedir') + 1] ?? ''; + assert.ok( + !keyring.startsWith(`${into}/`) && !into.startsWith(`${keyring}/`) && keyring !== into, + 'the keyring is elsewhere', + ); + assert.deepEqual(readdirSync(keyring), [], 'nothing of the zip is in the keyring'); + for (const planted of ['gpg.conf', 'agent', 'evil']) + assert.ok(!existsSync(join(job.temp, 'op', planted)) && !existsSync(join(job.temp, planted)), planted); +}); + +test('the key is imported before anything is unzipped, and gpg takes no configuration and starts no agent of its own', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + const order = job.calls.map((c) => + c.tool === 'gpg' ? `gpg ${c.args.find((a) => a === '--import' || a === '--verify')}` : c.tool, + ); + assert.ok(order.indexOf('gpg --import') < order.indexOf('unzip'), order.join(', ')); + assert.ok(order.indexOf('unzip') < order.indexOf('gpg --verify'), order.join(', ')); + for (const gpg of tool(job.calls, 'gpg')) { + assert.equal(gpg.args[0], '--no-options', 'which gpg reads before it reads any file'); + assert.ok(gpg.args.includes('--no-autostart'), gpg.args.join(' ')); + } +}); + +test('the downloads are over https alone, and tried again', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + for (const curl of downloads(job.calls)) { + assert.ok(curl.args.join(' ').includes('--proto =https'), curl.args.join(' ')); + assert.ok(curl.args.includes('--retry'), curl.args.join(' ')); + } +}); + +test('nothing the install starts, and nothing the installed op is asked, sees the vault’s credentials', () => { + const job = runJob(['repo'], { env: { ...SERVICE_ACCOUNT, OP_CONNECT_HOST: 'h' }, vault: VAULT, noOp: true }); + assert.equal(job.status, 0, job.log); + const started = job.calls.filter( + (c) => ['curl', 'unzip', 'gpg'].includes(c.tool) || (c.tool === 'op' && c.args[0] === '--version'), + ); + assert.ok(started.length >= 7, 'the probe, the downloads, gpg, unzip and the installed op'); + for (const call of started) + assert.deepEqual( + Object.keys(call.seen).filter((k) => k.startsWith('OP_')), + [], + `${call.tool} ${call.args.join(' ')}`, + ); +}); + +test('the primary key must be the pinned one, whichever subkey signs', () => { + const OTHER = 'ABCDEF0123456789ABCDEF0123456789ABCDEF01'; + const wrongPrimary = runJob(['repo'], { + env: SERVICE_ACCOUNT, + vault: VAULT, + noOp: true, + gpgSigner: OTHER, + gpgSubkey: OP_SIGNING_KEY, + }); + assert.equal(wrongPrimary.status, 1, wrongPrimary.log); + assert.deepEqual(reads(wrongPrimary.calls), []); + const subkey = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, gpgSubkey: OTHER }); + assert.equal(subkey.status, 0, subkey.log); +}); + +test('a verification that exits 0 and names no signature fails the job', () => { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, gpgSilent: true }); + assert.equal(job.status, 1, job.log); + assert.deepEqual(reads(job.calls), []); +}); + +test('a runner without unzip or gpg or curl fails the job in one line that names the tool', () => { + for (const missing of ['unzip', 'gpg', 'curl']) { + const job = runJob(['repo'], { env: SERVICE_ACCOUNT, vault: VAULT, noOp: true, without: [missing] }); + assert.equal(job.status, 1, `${missing}\n${job.log}`); + assert.match(job.log, new RegExp(`cannot install op: .*${missing}.* not on this runner`), missing); + assert.deepEqual(reads(job.calls), []); + } +}); diff --git a/packages/cli-ci/src/commands/setupWithoutToken.test.ts b/packages/cli-ci/src/commands/setupWithoutToken.test.ts new file mode 100644 index 00000000..500a8b66 --- /dev/null +++ b/packages/cli-ci/src/commands/setupWithoutToken.test.ts @@ -0,0 +1,116 @@ +// plx-ci setup in a job that is handed no token for the vault, as the job of a pull request from a fork is (the +// forge gives it no secrets), and neither a Connect server on the runner: it reads nothing from the vault, says so +// in one line, and goes on with what needs none (§ 8.4 of the project's decisions). +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { runJob } from '../testing/job.ts'; + +const FORGE_RUNNER = { RUNNER_ENVIRONMENT: 'github-hosted' }; +const CACHE_HOST = { PLX_TURBO_CACHE_HOST: 'cache.acme.internal' }; +const VAULT = { 'op://acme-ci/repo_web/server-actions-key': 'a-key' }; +/** A pull request from a fork: a forge runner, the repo's cache host, the overlay, and no secret. */ +const ON_PUSH = { GITHUB_WORKFLOW: 'on_push', GITHUB_REF_NAME: 'main', GITHUB_EVENT_NAME: 'push' }; +const FORK = { ...FORGE_RUNNER, ...CACHE_HOST, GITHUB_WORKFLOW: 'on_pr', GITHUB_EVENT_NAME: 'pull_request' }; + +/** The one line the step says about it. */ +const SAYS = /^::warning::no token for the vault: /m; + +test('a repo job with no token reads nothing, and says so in one line', () => { + const job = runJob(['repo', '--overlay', 'netbird'], { env: FORK, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual( + job.calls.filter((c) => c.tool === 'op'), + [], + ); + assert.equal(job.log.match(new RegExp(SAYS, 'gm'))?.length, 1, job.log); + assert.match(job.log, /without the server-actions key and without the remote cache/); + assert.ok(!/with the service account|Connect server/.test(job.log), 'it does not claim to have read the vault'); +}); + +test('a job with no token hands no key and no cache token, and joins no overlay', () => { + const job = runJob(['repo', '--overlay', 'netbird'], { env: FORK, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.deepEqual(job.output, {}); + assert.equal(job.log.match(/::add-mask::/g)?.length, 1, 'the registry login’s alone is masked'); + assert.ok(!job.calls.some((c) => ['netbird', 'apt-get', 'curl'].includes(c.tool)), 'no overlay, no download'); + for (const name of Object.keys(job.env)) assert.ok(!/TOKEN/.test(name), name); +}); + +test('a job with no token is still logged in to the forge’s registries with the job’s own token, which needs no vault', () => { + const job = runJob(['repo', '--private-packages'], { env: FORK, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.equal(job.env.DOCKER_CONFIG, join(job.temp, 'docker')); + assert.equal(job.env.NPM_CONFIG_USERCONFIG, join(job.temp, 'npm', 'npmrc')); +}); + +test('a repo job of the workflow on_commit or on_pr reads nothing where it has no token, and one of on_push fails', () => { + for (const GITHUB_WORKFLOW of ['on_commit', 'on_pr']) { + const job = runJob(['repo'], { env: { GITHUB_WORKFLOW }, vault: VAULT }); + assert.equal(job.status, 0, `${GITHUB_WORKFLOW}\n${job.log}`); + } + const job = runJob(['repo'], { env: ON_PUSH, vault: VAULT }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /on_push .*vault/); + assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); + assert.deepEqual(job.output, {}); +}); + +test('a deploy job with no token fails, since it cannot deploy', () => { + const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT }); + assert.equal(job.status, 1, job.log); + assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); + assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); + assert.ok(!SAYS.test(job.log), 'it does not go on as a job that deploys nothing'); +}); + +test('a job with a token reads as before and says nothing of the kind', () => { + const job = runJob(['repo'], { env: { OP_SERVICE_ACCOUNT_TOKEN: 'ops_x', GITHUB_WORKFLOW: 'on_pr' }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.ok(!SAYS.test(job.log), job.log); + assert.equal(job.output['server-actions-key'], 'a-key'); +}); + +/** A slot of a runner host: its host's cache servers on loopback and their tokens, which no workflow hands it. */ +const SLOT_CACHES = { + RUNNER_ENVIRONMENT: 'self-hosted', + PLX_TURBO_SHARED: 'http://127.0.0.1:8585', + PLX_TURBO_SHARED_TOKEN: 'slot-shared-token', + PLX_TURBO_TRUSTED: 'http://127.0.0.1:8586', + PLX_TURBO_TRUSTED_TOKEN: 'slot-trusted-token', +}; + +test('on a forge runner the line says the job has no key and no remote cache, as annotation of the run', () => { + const job = runJob(['repo'], { env: FORK, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.match( + job.log, + /^::warning::no token for the vault: reading nothing from it; .*without the server-actions key and without the remote cache$/m, + ); +}); + +test('on a slot without a Connect server the line claims no lack of cache: the slot hands its host’s cache tokens', () => { + const job = runJob(['repo'], { env: { ...SLOT_CACHES, GITHUB_WORKFLOW: 'on_pr' }, vault: VAULT }); + assert.equal(job.status, 0, job.log); + assert.match(job.log, SAYS); + assert.match(job.log, /without the server-actions key/); + assert.ok(!/without the remote cache/.test(job.log), 'the slot’s cache servers stay with the job'); + assert.match(job.log, /the cache servers of this runner’s host/); + assert.deepEqual(job.output, {}); +}); + +test('on a slot with a Connect server the job has a credential: it reads the key, and says nothing of having no token', () => { + const job = runJob(['repo'], { + env: { + ...SLOT_CACHES, + OP_CONNECT_HOST: 'http://localhost:8080', + OP_CONNECT_TOKEN: 'connect-token', + GITHUB_WORKFLOW: 'on_pr', + }, + vault: VAULT, + }); + assert.equal(job.status, 0, job.log); + assert.ok(!SAYS.test(job.log), job.log); + assert.match(job.log, /through the runner’s Connect server/); + assert.equal(job.output['server-actions-key'], 'a-key'); +}); diff --git a/packages/cli-ci/src/core/op.ts b/packages/cli-ci/src/core/op.ts new file mode 100644 index 00000000..4966ce73 --- /dev/null +++ b/packages/cli-ci/src/core/op.ts @@ -0,0 +1,109 @@ +// The vault's CLI, `op`, on a runner that has none: the forge's own runners +// carry no `op`, and a job with a credential needs it to read the vault +// (core/vault.ts). A runner that has one, as the environment image of a runner +// host does, is left as it is. Otherwise `opOf` installs OP_VERSION into the +// job's own temporary directory (RUNNER_TEMP/op, outside the checkout), as +// 1Password documents its CLI for Linux (developer.1password.com, "Get +// started with 1Password CLI", the manual install): the zip from +// cache.agilebits.com, which holds `op` and its detached signature `op.sig`, +// and `gpg --verify op.sig op` against 1Password's signing key. The key is +// fetched from 1Password's own site (the apt repository's key file, the same +// key), and it is the signature's primary key that must be the pinned +// fingerprint, so that a key the download served instead is no key of +// 1Password's. +// +// What is run before the signature verifies is only curl, unzip and gpg, and +// none of them can be made to run what the zip holds: the keyring is made and +// the key imported before the zip is opened; unzip takes the two members `op` +// and `op.sig` by name and nothing else, into a directory of their own; gpg +// runs with `--no-options`, which reads no configuration file, and +// `--no-autostart`, which starts no gpg-agent or dirmngr (neither is needed +// to import a public key or verify a signature); and none of the four, nor +// the installed op asked for its version, sees the vault's credentials +// (OP_*). `op` itself is run only after it verifies. +// +// The version is stated here and nowhere else in the code. The environment +// image pins the same version in its mise.toml (aqua:1password/cli); a person +// moves the two together, and a test holds them equal. +import { join } from 'node:path'; +import { type Context, run } from '@plexus-ms/lib'; + +export const OP_VERSION = '2.42.0'; +/** 1Password's code-signing key (fingerprint 3FEF 9748 469A DBE1 5DA7 CA80 AC2D 6274 2012 EA22). */ +export const OP_SIGNING_KEY = '3FEF9748469ADBE15DA7CA80AC2D62742012EA22'; + +const KEY_URL = 'https://downloads.1password.com/linux/keys/1password.asc'; +/** 1Password's names for the CPU architectures of a Linux runner. */ +const ARCHITECTURES: Record = { x64: 'amd64', arm64: 'arm64', arm: 'arm', ia32: '386' }; + +/** + * The command that runs the vault's CLI on this runner: `op` where the runner + * has it, else the verified install of OP_VERSION under `temp`, whose path. + */ +export async function opOf(ctx: Context, env: NodeJS.ProcessEnv, temp: string): Promise { + // Everything below is started without the vault's credentials, which none of it needs. + const clean = Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith('OP_'))); + // A plan step's environment is laid over the process's, so there the credentials are blanked; a read's replaces it. + const blank = Object.fromEntries( + Object.keys(env) + .filter((name) => name.startsWith('OP_')) + .map((name) => [name, undefined]), + ); + if ( + await ctx.read('op', ['--version'], { env: clean }).then( + () => true, + () => false, + ) + ) + return 'op'; + const architecture = ARCHITECTURES[process.arch]; + if (!architecture) throw new Error(`no op for the architecture ${process.arch}`); + const dir = join(temp, 'op'); + const [gnupg, downloads, unpacked] = ['gnupg', 'download', 'bin'].map((name) => join(dir, name)) as [ + string, + string, + string, + ]; + const [zip, key] = [join(downloads, 'op.zip'), join(downloads, 'key.asc')]; + const [bin, sig] = [join(unpacked, 'op'), join(unpacked, 'op.sig')]; + const what = `op ${OP_VERSION} from 1Password’s download`; + const gpg = ['--no-options', '--no-autostart', '--homedir', gnupg, '--batch']; + const download = (to: string, url: string) => + run('curl', ['-fsSL', '--proto', '=https', '--retry', '3', '--output', to, url], { env: blank }); + ctx.say(`${ctx.dryRun ? '[dry-run] ' : ''}this runner has no op: installing ${OP_VERSION}, verified, into ${dir}`); + try { + await ctx.apply([ + run('mkdir', ['-p', '-m', '700', dir], { env: blank }), + run('mkdir', ['-m', '700', gnupg, downloads, unpacked], { env: blank }), + download( + zip, + `https://cache.agilebits.com/dist/1P/op2/pkg/v${OP_VERSION}/op_linux_${architecture}_v${OP_VERSION}.zip`, + ), + download(key, KEY_URL), + ]); + if (ctx.dryRun) return 'op'; + await ctx.read('gpg', [...gpg, '--quiet', '--import', key], { env: clean }); + // Only the two members, whatever else the zip holds, into a directory that holds nothing else. + await ctx.apply([run('unzip', ['-qo', zip, 'op', 'op.sig', '-d', unpacked], { env: blank })]); + const status = await ctx + .read('gpg', [...gpg, '--status-fd', '1', '--verify', sig, bin], { env: clean }) + .catch(() => { + throw new Error(`${what} did not pass its signature check, and is not run`); + }); + const signer = /^\[GNUPG:\] VALIDSIG .* ([0-9A-F]{40})$/m.exec(status)?.[1]; + if (signer !== OP_SIGNING_KEY) + throw new Error( + `${what} is not signed by 1Password’s key ${OP_SIGNING_KEY} but by ${signer ?? 'no key'}, and is not run`, + ); + await ctx.apply([run('chmod', ['700', bin], { env: blank })]); + const said = (await ctx.read(bin, ['--version'], { env: clean })).trim(); + if (said !== OP_VERSION) throw new Error(`${what} says it is ${said}, not ${OP_VERSION}`); + } catch (error) { + const missing = error as { code?: string; path?: string }; + if (missing.code === 'ENOENT') + throw new Error(`cannot install op: ${missing.path ?? 'a tool'} is not on this runner`); + throw error; + } + ctx.say(`installed op ${OP_VERSION}, signature verified`); + return bin; +} diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index d2560d39..960ec13a 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -2,9 +2,19 @@ import { createSign } from 'node:crypto'; import { appendFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import { type Context, detailOf, orAbsent, type Plan, run, write } from '@plexus-ms/lib'; +import { + type Context, + detailOf, + ENVIRONMENT_BRANCHES, + environmentOf, + orAbsent, + type Plan, + run, + write, +} from '@plexus-ms/lib'; import { need, ownerOf } from '../commands/shared.ts'; -import { mask, vaultOf } from './vault.ts'; +import { opOf } from './op.ts'; +import { mask, type Vault, vaultAccess, vaultOf } from './vault.ts'; export const JOBS = ['repo', 'deploy'] as const; export type Job = (typeof JOBS)[number]; @@ -36,13 +46,72 @@ const NETBIRD_VERSION = '0.82.0'; */ const cacheHostOf = (env: NodeJS.ProcessEnv): string | undefined => env.PLX_TURBO_CACHE_HOST?.trim() || undefined; +/** + * A run of the workflow on_push, which a person can start on any branch, on a + * branch that deploys nowhere would build and push images and only then fail + * in the deploy: it fails here, before anything is read, built or pushed. The + * workflow is told by its name, which the forge hands every step. + */ +function refuseOnPushWithoutEnvironment(env: NodeJS.ProcessEnv): void { + if (env.GITHUB_WORKFLOW !== 'on_push') return; + const ref = env.GITHUB_REF_NAME ?? ''; + const tag = env.GITHUB_REF_TYPE === 'tag'; + if (!tag && environmentOf(env.GITHUB_EVENT_NAME ?? '', ref)) return; + throw new Error( + `on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: only the branches ${Object.keys(ENVIRONMENT_BRANCHES).join(' and ')} deploy; run on_push there`, + ); +} + +/** + * The vault this job reads, or undefined where it reads none: a repo job handed + * no credential for it, as the job of a pull request from a fork is, since the + * forge gives such a job no secrets. It says so in one line, a warning of the + * run so that a secret unset or misnamed in a pull request of the repo itself + * is seen, and goes on with what needs none: the logins are the job's own + * token's, and without the key the build runs with a key of Next's own + * making. Without the cache tokens it runs without the remote cache, but a + * 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. + */ +async function vaultFor( + ctx: Context, + options: SetupOptions, + env: NodeJS.ProcessEnv, + temp: string, +): Promise { + if (vaultAccess(env)) return vaultOf(ctx, env, await opOf(ctx, env, temp)); + if (options.job === 'deploy') return vaultOf(ctx, env); + if (env.GITHUB_WORKFLOW === 'on_push') { + try { + vaultOf(ctx, env); + } catch (error) { + throw new Error(`on_push publishes the repo’s images and cannot run without the vault; ${detailOf(error)}`); + } + } + // A slot hands its host's cache servers and their tokens whether or not the job has a credential for the vault. + const slotCaches = Boolean(env.PLX_TURBO_SHARED_TOKEN || env.PLX_TURBO_TRUSTED_TOKEN); + ctx.io.stdout.write( + `::warning::no token for the vault: reading nothing from it; the job runs without the server-actions key and ${ + slotCaches + ? 'with the remote cache only where the cache servers of this runner’s host answer' + : 'without the remote cache' + }\n`, + ); + return undefined; +} + export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise { + refuseOnPushWithoutEnvironment(env); const repository = need('GITHUB_REPOSITORY', env); const owner = ownerOf(repository); const repo = repository.split('/')[1] ?? repository; const vaultName = `${owner}-ci`; const temp = need('RUNNER_TEMP', env); - const vault = vaultOf(ctx, env); + const vault = await vaultFor(ctx, options, env, temp); const outputs: Record = {}; const variables: Record = {}; const plan: Plan = []; @@ -53,11 +122,11 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro env.RUNNER_ENVIRONMENT === 'github-hosted' && options.overlay === 'netbird' && (options.job === 'deploy' || cacheHost !== undefined); - const setupKey = overlay ? await vault.read(`op://${vaultName}/netbird/setup-key`) : undefined; + const setupKey = overlay && vault ? await vault.read(`op://${vaultName}/netbird/setup-key`) : undefined; if (options.job === 'repo') { - outputs['server-actions-key'] = await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); - if (overlay) { + if (vault) outputs['server-actions-key'] = await vault.read(`op://${vaultName}/repo_${repo}/server-actions-key`); + if (overlay && vault) { variables.PLX_TURBO_SHARED_TOKEN = await vault.read(`op://${vaultName}/turbo-cache/shared-token`); variables.PLX_TURBO_TRUSTED_TOKEN = await vault.read(`op://${vaultName}/turbo-cache/trusted-token`); } @@ -74,6 +143,7 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro variables.NPM_CONFIG_USERCONFIG = npmrc; } } 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`)); const clientId = await vault.read(`op://${vaultName}/github-app/client-id`, { secret: false }); const appKey = keyLines(ctx, await vault.read(`op://${vaultName}/github-app/private-key`)); @@ -95,11 +165,12 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro variables.SSH_AUTH_SOCK = socket; } - ctx.say( - vault.access === 'connect' - ? `the vault ${vaultName}, through the runner’s Connect server` - : `the vault ${vaultName}, with the service account`, - ); + if (vault) + ctx.say( + vault.access === 'connect' + ? `the vault ${vaultName}, through the runner’s Connect server` + : `the vault ${vaultName}, with the service account`, + ); await ctx.apply(plan); if (setupKey) { try { @@ -118,6 +189,16 @@ export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.Pro ); } } + if (options.job === 'repo') { + const offOverlay = env.RUNNER_ENVIRONMENT === 'github-hosted' && outputs.joined !== 'true'; + const without = await withoutTrustedCache(ctx, env, variables.PLX_TURBO_TRUSTED_TOKEN, offOverlay); + if (without) { + ctx.say( + `without a trusted remote cache: ${without}; build, e2e and publish share the job’s local cache, so that each app is built once`, + ); + variables.PLX_TURBO_TRUSTED = 'local'; + } + } hand(ctx, 'the outputs of the step', () => need('GITHUB_OUTPUT', env), outputs); hand(ctx, 'the environment of the job', () => need('GITHUB_ENV', env), variables); } @@ -161,6 +242,48 @@ async function joinOverlay( ctx.say(`joined the overlay as ${hostname}`); } +/** + * Why the job's build, e2e and publish reach no trusted cache server, or + * undefined where they reach one, which turbow then uses as ever. The reason + * names the case and never the server's address, since a run's log may be + * public. The server + * is the one turbow takes, PLX_TURBO_TRUSTED, else the cache host's port 8586, + * which a forge runner reaches only where it joined the overlay (`offOverlay` + * where it did not). It is asked once here as turbow asks it, with the trusted + * token from the environment or from the vault (`vaultToken`): 200 is a + * server that answers, and anything else, or no answer within two seconds, + * none. Where there is none, + * the job is handed PLX_TURBO_TRUSTED=local and every later step keeps that + * one answer, so that the step build builds each app once and e2e and publish + * replay that build from the job's local cache; a server that turbow found + * again between two steps would otherwise have e2e build once more. A server + * named without a token is left to turbow, which fails the verb; under + * --dry-run a named server is asked nothing. + */ +async function withoutTrustedCache( + ctx: Context, + env: NodeJS.ProcessEnv, + vaultToken: string | undefined, + offOverlay: boolean, +): Promise { + const host = cacheHostOf(env); + const server = env.PLX_TURBO_TRUSTED || (host ? `http://${host}:8586` : ''); + const token = env.PLX_TURBO_TRUSTED_TOKEN || vaultToken; + if (!server) return 'the repo names no cache host, and the environment no trusted server'; + if (offOverlay && !env.PLX_TURBO_TRUSTED) return 'the job is not on the overlay, where the cache host is'; + if (!token || ctx.dryRun) return undefined; + const config = [ + `url = "${server}/v8/artifacts/status"`, + 'silent', + `header = "Authorization: Bearer ${token}"`, + 'max-time = 2', + 'output = "/dev/null"', + 'write-out = "%{http_code}"', + ]; + const status = await ctx.read('curl', ['-K', '-'], { input: `${config.join('\n')}\n` }).catch(() => ''); + return status.trim() === '200' ? undefined : 'the trusted server does not answer with the trusted token'; +} + /** Ask `ok` once a second, `seconds` times at most; an error naming `what` when it never answers yes. */ async function until(what: string, seconds: number, ok: () => Promise): Promise { for (let i = 0; i < seconds; i++) { diff --git a/packages/cli-ci/src/core/vault.ts b/packages/cli-ci/src/core/vault.ts index 7560985d..3c5dedb8 100644 --- a/packages/cli-ci/src/core/vault.ts +++ b/packages/cli-ci/src/core/vault.ts @@ -33,20 +33,29 @@ export function mask(ctx: Context, value: string): void { for (const line of value.split('\n').map((l) => l.trim())) if (line) ctx.io.stdout.write(`::add-mask::${line}\n`); } -/** The vault as this runner reaches it; an error naming both ways where it reaches it neither way. */ -export function vaultOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Vault { - const connect = CONNECT.every((name) => env[name]); - if (!connect && !env.OP_SERVICE_ACCOUNT_TOKEN) +/** How this runner reaches the vault, or undefined where it carries no credential for it, which only a job without secrets does. */ +export function vaultAccess(env: NodeJS.ProcessEnv = process.env): VaultAccess | undefined { + if (CONNECT.every((name) => env[name])) return 'connect'; + return env.OP_SERVICE_ACCOUNT_TOKEN ? 'service account' : undefined; +} + +/** + * The vault as this runner reaches it, read with the CLI at `op` (the runner's own, unless core/op.ts installed + * one); an error naming both ways where it reaches it neither way. + */ +export function vaultOf(ctx: Context, env: NodeJS.ProcessEnv = process.env, op = 'op'): Vault { + const access = vaultAccess(env); + if (!access) throw new Error( 'the job cannot read the vault: the runner carries no Connect server (OP_CONNECT_HOST and OP_CONNECT_TOKEN), and the step was handed no OP_SERVICE_ACCOUNT_TOKEN', ); const opEnv = { ...env }; - if (connect) delete opEnv.OP_SERVICE_ACCOUNT_TOKEN; + if (access === 'connect') delete opEnv.OP_SERVICE_ACCOUNT_TOKEN; else for (const name of CONNECT) delete opEnv[name]; return { - access: connect ? 'connect' : 'service account', + access, read: async (ref, { secret = true } = {}) => { - const value = (await ctx.read('op', ['read', ref], { env: opEnv })).replace(/\n$/, ''); + const value = (await ctx.read(op, ['read', ref], { env: opEnv })).replace(/\n$/, ''); if (secret) mask(ctx, value); return value; }, diff --git a/packages/cli-ci/src/testing/job.ts b/packages/cli-ci/src/testing/job.ts index 84887037..ac0085e7 100644 --- a/packages/cli-ci/src/testing/job.ts +++ b/packages/cli-ci/src/testing/job.ts @@ -6,10 +6,19 @@ // vault's and the overlay's variables it saw. Not shipped (excluded in // tsconfig). // -// op `op read ` answers from `vault`, else fails as op does +// op `op read ` answers from `vault`, else fails as op does; `op --version` answers +// `opVersion` (default the pinned one); with `noOp`, the op on the PATH is not found, +// as on a runner without it, and only one that was unzipped works // curl the forge's API, as curl answers with the config's `fail-with-body` // or `write-out`: a repository's installation, and a token for it, -// or for every call the status `apiStatus`; any other download, a key +// or for every call the status `apiStatus`; a cache server's status +// request, the status `cacheStatus`, or without one no connection, +// as curl fails where nothing listens; a download to a file +// (`--output`), which `fake download of ` fills; any other +// download, a key; with `realCurl`, curl itself +// unzip puts a working `op` (the fake itself) and its `op.sig` into the `-d` directory +// gpg `--import` succeeds; `--verify` reports the signature valid for the pinned key, +// `gpgSigner` for another key's, or fails as gpg does for `gpgSigner: false` // sudo runs the rest of its arguments, its own options dropped // netbird `up` and `down` succeed unless `netbirdFails`; `status` is connected // getent every name resolves @@ -23,10 +32,12 @@ import { mkdtempSync, openSync, readFileSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { basename, dirname, join } from 'node:path'; +import { OP_SIGNING_KEY, OP_VERSION } from '../core/op.ts'; const BIN = join(import.meta.dirname, '..', 'bin.ts'); @@ -34,16 +45,24 @@ const BIN = join(import.meta.dirname, '..', 'bin.ts'); const SEEN = ['OP_CONNECT_HOST', 'OP_CONNECT_TOKEN', 'OP_SERVICE_ACCOUNT_TOKEN', 'NB_SETUP_KEY', 'SSH_AUTH_SOCK']; const FAKE = `#!/usr/bin/env node -const { appendFileSync, readFileSync } = require('node:fs'); +const { appendFileSync, chmodSync, copyFileSync, readFileSync, writeFileSync } = require('node:fs'); const { basename } = require('node:path'); const tool = basename(process.argv[1]); const args = process.argv.slice(2); -const input = ['ssh-add', 'gpg', 'tee'].includes(tool) || args.includes('-K') ? readFileSync(0, 'utf8') : undefined; +const input = ['ssh-add', 'tee'].includes(tool) || (tool === 'gpg' && args.includes('--dearmor')) || args.includes('-K') ? readFileSync(0, 'utf8') : undefined; const seen = Object.fromEntries(${JSON.stringify(SEEN)}.filter((k) => process.env[k] !== undefined).map((k) => [k, process.env[k]])); -appendFileSync(process.env.FAKE_LOG, JSON.stringify({ tool, args, input, seen }) + '\\n'); +appendFileSync(process.env.FAKE_LOG, JSON.stringify({ tool, args, input, seen, path: process.argv[1] }) + '\\n'); const fail = (message) => { process.stderr.write(message + '\\n'); process.exit(1); }; switch (tool) { case 'op': { + if (process.env.FAKE_NO_OP && require('node:path').dirname(process.argv[1]) === process.env.FAKE_BIN) { + process.stderr.write('op: command not found\\n'); + process.exit(127); + } + if (args[0] === '--version') { + process.stdout.write((process.env.FAKE_OP_VERSION || ${JSON.stringify(OP_VERSION)}) + '\\n'); + break; + } const vault = JSON.parse(readFileSync(process.env.FAKE_VAULT, 'utf8')); const ref = args[1]; if (args[0] !== 'read' || !(ref in vault)) fail('[ERROR] could not read secret ' + ref); @@ -51,11 +70,24 @@ switch (tool) { break; } case 'curl': { + if (args.includes('--output')) { + writeFileSync(args[args.indexOf('--output') + 1], 'fake download of ' + args.at(-1)); + break; + } if (!input) { process.stdout.write('-----BEGIN PGP PUBLIC KEY BLOCK-----\\nfake\\n-----END PGP PUBLIC KEY BLOCK-----\\n'); break; } const url = /^url = "(.*)"$/m.exec(input)[1]; + if (url.endsWith('/v8/artifacts/status')) { + const answer = process.env.FAKE_CACHE_STATUS; + if (!answer) { + process.stderr.write('curl: (7) Failed to connect to ' + new URL(url).host + ': Could not connect to server\\n'); + process.exit(7); + } + process.stdout.write(/^write-out = "(.*)"$/m.exec(input)[1].replaceAll('\\\\n', '\\n').replaceAll('%{http_code}', answer)); + break; + } const failed = process.env.FAKE_API_STATUS; const [status, body] = failed ? [Number(failed), { message: failed === '401' ? 'A JSON web token could not be decoded' : 'Not Found', status: failed }] @@ -82,13 +114,38 @@ switch (tool) { if (process.env.FAKE_NETBIRD_FAILS && args[0] === 'up') fail('netbird: the management server refused the setup key'); if (args[0] === 'status') process.stdout.write('Management: Connected\\nSignal: Connected\\nPeers count: 0/3 Connected\\n'); break; + case 'unzip': { + // As unzip does: the members named after the zip, or every member where none is; a name loses its leading ../ + const dir = args[args.indexOf('-d') + 1]; + const named = args.slice(args.findIndex((a) => !a.startsWith('-')) + 1).filter((a, i, all) => a !== '-d' && all[i - 1] !== '-d'); + const members = ['op', 'op.sig', ...JSON.parse(process.env.FAKE_ZIP_EXTRA || '[]')]; + for (const member of named.length ? members.filter((m) => named.includes(m)) : members) { + const file = require('node:path').join(dir, member.replace(/^(\\.\\.\\/)+/, '')); + require('node:fs').mkdirSync(require('node:path').dirname(file), { recursive: true }); + if (member === 'op') { + copyFileSync(process.argv[1], file); + chmodSync(file, 0o755); + } else writeFileSync(file, member === 'op.sig' ? 'fake signature' : 'planted by the zip'); + } + break; + } + case 'gpg': { + if (args.includes('--verify')) { + if (process.env.FAKE_GPG_BAD) fail('gpg: BAD signature from "Code signing for 1Password"'); + if (process.env.FAKE_GPG_SILENT) break; + const key = process.env.FAKE_GPG_SIGNER || ${JSON.stringify(OP_SIGNING_KEY)}; + const subkey = process.env.FAKE_GPG_SUBKEY || key; + process.stdout.write('[GNUPG:] GOODSIG AC2D62742012EA22 Code signing\\n[GNUPG:] VALIDSIG ' + subkey + ' 2026-11-04 1793825235 0 4 0 1 10 00 ' + key + '\\n'); + } + break; + } case 'getent': process.stdout.write('100.64.0.9 ' + args[1] + '\\n'); break; } `; -const TOOLS = ['op', 'curl', 'sudo', 'netbird', 'getent', 'ssh-agent', 'ssh-add', 'gpg', 'tee', 'apt-get']; +const TOOLS = ['op', 'curl', 'sudo', 'netbird', 'getent', 'ssh-agent', 'ssh-add', 'gpg', 'tee', 'apt-get', 'unzip']; /** One call a fake recorded. */ export interface Call { @@ -96,6 +153,8 @@ export interface Call { args: string[]; input?: string; seen: Record; + /** Where the tool that ran is: the fake on the PATH, or a copy of it that was unzipped. */ + path: string; } export interface Job { @@ -132,7 +191,23 @@ export function runJob( env?: Record; vault?: Record; netbirdFails?: boolean; + /** The runner has no vault CLI of its own: the one on its PATH is not found. */ + noOp?: boolean; + /** What the unzipped `op` says its version is. */ + opVersion?: string; + /** Members the downloaded zip holds besides `op` and `op.sig`, by name. */ + zipExtra?: string[]; + /** The fingerprint of the signing subkey gpg reports, where the primary key signs by a subkey. */ + gpgSubkey?: string; + /** gpg exits 0 and says nothing of the signature. */ + gpgSilent?: boolean; + /** Tools the runner lacks: not on its PATH at all. */ + without?: string[]; + /** What gpg says of the signature: `false` for a bad one, a fingerprint for one of another key. */ + gpgSigner?: string | false; apiStatus?: number; + cacheStatus?: number; + realCurl?: boolean; } = {}, ): Job { const dir = mkdtempSync(join(tmpdir(), 'plx-ci-setup-')); @@ -140,10 +215,15 @@ export function runJob( const temp = join(dir, 'temp'); mkdirSync(bin); mkdirSync(temp); - for (const tool of TOOLS) { + for (const tool of TOOLS.filter((t) => !options.without?.includes(t) && !(options.realCurl && t === 'curl'))) { writeFileSync(join(bin, tool), FAKE); chmodSync(join(bin, tool), 0o755); } + if (options.without) + for (const tool of [dirname(process.execPath), '/usr/bin'].flatMap((d) => + ['node', 'mkdir', 'chmod'].map((t) => join(d, t)), + )) + if (existsSync(tool) && !existsSync(join(bin, basename(tool)))) symlinkSync(tool, join(bin, basename(tool))); const vault = join(dir, 'vault.json'); writeFileSync(vault, JSON.stringify(options.vault ?? {})); const logPath = join(dir, 'log'); @@ -152,7 +232,8 @@ export function runJob( stdio: ['ignore', fd, fd], timeout: 60_000, env: { - PATH: `${bin}:${process.env.PATH}`, + // A runner lacking tools has the fakes, node, and the plain tools the command runs itself, nothing else. + PATH: options.without ? bin : `${bin}:${process.env.PATH}`, HOME: dir, GITHUB_ACTIONS: 'true', GITHUB_REPOSITORY: 'acme/web', @@ -165,8 +246,20 @@ export function runJob( RUNNER_TEMP: temp, FAKE_LOG: join(dir, 'calls'), FAKE_VAULT: vault, + FAKE_BIN: bin, + ...(options.zipExtra ? { FAKE_ZIP_EXTRA: JSON.stringify(options.zipExtra) } : {}), + ...(options.gpgSubkey ? { FAKE_GPG_SUBKEY: options.gpgSubkey } : {}), + ...(options.gpgSilent ? { FAKE_GPG_SILENT: '1' } : {}), + ...(options.noOp ? { FAKE_NO_OP: '1' } : {}), + ...(options.opVersion ? { FAKE_OP_VERSION: options.opVersion } : {}), + ...(options.gpgSigner === false + ? { FAKE_GPG_BAD: '1' } + : options.gpgSigner + ? { FAKE_GPG_SIGNER: options.gpgSigner } + : {}), ...(options.netbirdFails ? { FAKE_NETBIRD_FAILS: '1' } : {}), ...(options.apiStatus ? { FAKE_API_STATUS: String(options.apiStatus) } : {}), + ...(options.cacheStatus ? { FAKE_CACHE_STATUS: String(options.cacheStatus) } : {}), ...options.env, }, }); diff --git a/packages/cli-template/src/boundary.test.ts b/packages/cli-template/src/boundary.test.ts index cff3e65e..b68f468a 100644 --- a/packages/cli-template/src/boundary.test.ts +++ b/packages/cli-template/src/boundary.test.ts @@ -132,3 +132,22 @@ test("no source file but the shell's imports the filesystem, processes, the OS o [], ); }); + +/** The entries that hand the shell to a caller: the library's and the command's. */ +const ENTRIES = ['src/index.ts', 'src/bin.ts']; + +test('no source file of the core imports the shell, but the entries that hand it on', () => { + const files = sources(join(root, 'src')).map((f) => relative(root, f)); + const core = files.filter( + (f) => !f.endsWith('.test.ts') && !f.startsWith('src/testing/') && !SHELL.includes(f) && !ENTRIES.includes(f), + ); + assert.ok(core.includes('src/merge.ts'), 'the scan reaches the core'); + assert.deepEqual( + core.flatMap((f) => + specifiers(readFileSync(join(root, f), 'utf8')) + .filter((s) => SHELL.includes(relative(root, resolve(dirname(join(root, f)), s)))) + .map((s) => `${f}: ${s}`), + ), + [], + ); +}); diff --git a/packages/cli-template/src/checked-merge-file.test.ts b/packages/cli-template/src/checked-merge-file.test.ts new file mode 100644 index 00000000..478c776b --- /dev/null +++ b/packages/cli-template/src/checked-merge-file.test.ts @@ -0,0 +1,163 @@ +// checkedMergeFile around the real merge of one file: these tests run git. The +// checks are toys over lines, since the engine knows no format. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { checkedMergeFile, gitMergeFile, type MergeCheck } from './index.ts'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +/** Refuses a file in which a line's key, what precedes its `:`, stands twice. */ +const keysOnce: MergeCheck = (_path, bytes) => { + const keys = decoder + .decode(bytes) + .split('\n') + .filter((line) => line.includes(':')) + .map((line) => line.split(':')[0]); + return new Set(keys).size === keys.length; +}; + +/** The checked merge of three texts, the result as text. */ +async function mergeTexts(check: MergeCheck, old: string, next: string, current: string) { + const { bytes, conflicted } = await checkedMergeFile( + gitMergeFile, + check, + )({ path: 'fruit.cfg', old: encoder.encode(old), new: encoder.encode(next), current: encoder.encode(current) }); + return { text: decoder.decode(bytes), conflicted }; +} + +test('checkedMergeFile puts the change of the template that the check refuses between conflict markers, and keeps the rest merged', async () => { + assert.deepEqual( + await mergeTexts( + keysOnce, + 'a: 1\nb: 2\nc: 3\nd: 4\n', + 'a: 1\nb: 2\nc: 9\nd: 4\nx: 1\n', + 'a: 1\nx: 0\nb: 2\nc: 3\nd: 4\n', + ), + { + text: 'a: 1\nx: 0\nb: 2\nc: 9\nd: 4\n<<<<<<< current\n=======\nx: 1\n>>>>>>> new render\n', + conflicted: true, + }, + ); +}); + +test('checkedMergeFile returns a merge the check accepts as git made it, and asks the check with the path', async () => { + const asked: string[] = []; + const check: MergeCheck = (path, bytes) => { + asked.push(path); + return keysOnce(path, bytes); + }; + assert.deepEqual(await mergeTexts(check, 'a: 1\nb: 2\nc: 3\n', 'a: 1\nb: 2\nc: 9\n', 'a: 0\nb: 2\nc: 3\n'), { + text: 'a: 0\nb: 2\nc: 9\n', + conflicted: false, + }); + assert.deepEqual(asked, ['fruit.cfg']); +}); + +test('checkedMergeFile leaves a merge alone where the check refuses the current side or the new render already', async () => { + const twice = 'a: 1\na: 2\nb: 2\nc: 3\n'; + assert.deepEqual(await mergeTexts(keysOnce, 'a: 1\nb: 2\nc: 3\n', 'a: 1\nb: 2\nc: 9\n', twice), { + text: 'a: 1\na: 2\nb: 2\nc: 9\n', + conflicted: false, + }); + assert.deepEqual(await mergeTexts(keysOnce, 'a: 1\nb: 2\nc: 3\n', 'a: 1\nb: 2\nc: 3\nc: 4\n', 'a: 0\nb: 2\nc: 3\n'), { + text: 'a: 0\nb: 2\nc: 3\nc: 4\n', + conflicted: false, + }); +}); + +test('checkedMergeFile puts every change of the template between markers where no one of them alone makes the merge refused', async () => { + // Refused: a file that holds the user's `u` beside either of the template's `y` and `z`. + const check: MergeCheck = (_path, bytes) => { + const lines = decoder.decode(bytes).split('\n'); + return !(lines.includes('u') && (lines.includes('y') || lines.includes('z'))); + }; + assert.deepEqual(await mergeTexts(check, 'a\nb\nc\nd\n', 'a\ny\nb\nc\nd\nz\n', 'a\nb\nu\nc\nd\n'), { + text: 'a\n<<<<<<< current\n=======\ny\n>>>>>>> new render\nb\nu\nc\nd\n<<<<<<< current\n=======\nz\n>>>>>>> new render\n', + conflicted: true, + }); +}); + +test('checkedMergeFile returns a conflicted merge as it is where either resolution of its conflicts is taken', async () => { + // git's conflict: the repo and the template both moved `n`; nothing else is doubled. + assert.deepEqual(await mergeTexts(keysOnce, 'n: 1\nb: 2\n', 'n: 3\nb: 2\n', 'n: 2\nb: 2\n'), { + text: '<<<<<<< current\nn: 2\n=======\nn: 3\n>>>>>>> new render\nb: 2\n', + conflicted: true, + }); + // Taking the new render's side of it leaves `x` twice, the current side's does not: the person resolving it meets that. + assert.deepEqual(await mergeTexts(keysOnce, 'n: 1\nb: 2\n', 'n: 3\nx: 1\nb: 2\n', 'n: 2\nb: 2\nx: 0\n'), { + text: '<<<<<<< current\nn: 2\n=======\nn: 3\nx: 1\n>>>>>>> new render\nb: 2\nx: 0\n', + conflicted: true, + }); +}); + +test('checkedMergeFile also marks a clean change the check refuses in a merge that git conflicts on elsewhere', async () => { + // The repo moved the `node` line the template moves, and has the key the template adds already. + assert.deepEqual( + await mergeTexts( + keysOnce, + 'node: 24\nhk: latest\nuv: latest\nansible: latest\n', + 'node: 26\nhk: latest\nuv: latest\nansible: latest\nterraform: 1\n', + 'node: 22\nhk: latest\nterraform: 1.9\nuv: latest\nansible: latest\n', + ), + { + text: [ + '<<<<<<< current', + 'node: 22', + '=======', + 'node: 26', + '>>>>>>> new render', + 'hk: latest', + 'terraform: 1.9', + 'uv: latest', + 'ansible: latest', + '<<<<<<< current', + '=======', + 'terraform: 1', + '>>>>>>> new render', + '', + ].join('\n'), + conflicted: true, + }, + ); +}); + +test('checkedMergeFile writes its markers in the line ending of the file', async () => { + const crlf = (text: string) => text.replaceAll('\n', '\r\n'); + assert.deepEqual( + await mergeTexts( + keysOnce, + crlf('a: 1\nb: 2\nc: 3\nd: 4\n'), + crlf('a: 1\nb: 2\nc: 3\nd: 4\nx: 1\n'), + crlf('a: 1\nx: 0\nb: 2\nc: 3\nd: 4\n'), + ), + { + text: crlf('a: 1\nx: 0\nb: 2\nc: 3\nd: 4\n<<<<<<< current\n=======\nx: 1\n>>>>>>> new render\n'), + conflicted: true, + }, + ); +}); + +test('checkedMergeFile diffs no more than 2000 lines: above, everything between the first and the last change goes between one pair of markers', async () => { + let asked = 0; + const check: MergeCheck = (path, bytes) => { + asked++; + return keysOnce(path, bytes); + }; + const rest = Array.from({ length: 1100 }, (_, i) => `k${i + 1}: ${i + 1}\n`).join(''); + const old = `a: 1\nk0: 0\n${rest}z: 1\n`; + const next = `a: 2\nk0: 0\n${rest}z: 1\nx: 1\n`; + const current = `a: 1\nk0: 0\nx: 0\n${rest}z: 1\n`; + const { text, conflicted } = await mergeTexts(check, old, next, current); + const merged = `a: 2\nk0: 0\nx: 0\n${rest}z: 1\nx: 1\n`; + assert.ok(conflicted); + assert.ok(text === `<<<<<<< current\n${current}=======\n${merged}>>>>>>> new render\n`, text.slice(0, 120)); + assert.equal(asked, 3, 'the merge, the current side and the new render; no change is tried alone'); +}); + +test('checkedMergeFile closes a last line without a newline before a marker', async () => { + assert.deepEqual(await mergeTexts(keysOnce, 'a: 1\nb: 2\nc: 3', 'a: 1\nb: 2\nc: 3\nx: 1', 'x: 0\na: 1\nb: 2\nc: 3'), { + text: 'x: 0\na: 1\nb: 2\n<<<<<<< current\nc: 3\n=======\nc: 3\nx: 1\n>>>>>>> new render\n', + conflicted: true, + }); +}); diff --git a/packages/cli-template/src/checked-merge-file.ts b/packages/cli-template/src/checked-merge-file.ts new file mode 100644 index 00000000..161f9663 --- /dev/null +++ b/packages/cli-template/src/checked-merge-file.ts @@ -0,0 +1,194 @@ +// checkedMergeFile: a `MergeFile` whose merges are held to a check its caller +// gives. git merges lines and knows nothing of what they mean: where the +// template adds a line that the user already added elsewhere in the file, a key +// that a format allows once for one, the two changes lie apart, git merges them +// without a conflict, and the file is no longer one its reader takes. The +// engine knows no format, so what a reader takes is the caller's to say, as a +// function of the file's path and its merged bytes; `planMerge` applies it to +// every file it merges where it is given one. +// +// A merge is refused where the check refuses it; one that git conflicts on +// where the check refuses it with git's conflicts resolved to either side, each +// conflict to the current side and each to the new render. A merge that is not +// refused is returned as git made it. A refused merge is returned as git made it +// too where the check refuses the current side or the new render already: that +// is not the merge's doing. So is a conflicted merge whose conflicts are not +// closed as git closes them. +// +// Otherwise the template's changes that the check refuses are put between +// conflict markers. They are the hunks of a line diff from the current side to +// the merge, in which each of git's conflicts stands as one line of its own, so +// that it falls into a hunk and never matches a line of the current side. A +// hunk whose undoing alone makes the check accept the merge, git's conflicts +// resolved to the current side, is one the check refuses; where no hunk alone +// does, every hunk is. Each such hunk goes between the markers `gitMergeFile` +// writes, the current side's lines first and the merge's after them, with any of +// git's conflicts inside it taken at its new render's side; every other hunk +// stays merged, and git's conflicts outside them stay as git wrote them. The +// markers end in the line ending of the current side's first line; a side's last +// line that lacks one gains it before the marker that follows. The file is then +// reported conflicted, like any conflict, and its markers tell a later merge that +// it is (git-merge-file.ts). +// +// The diff is the longest common subsequence of the lines between the two +// sides' common head and tail, which costs memory as the product of their +// lengths and a check per hunk. Above DIFF_LIMIT lines between head and tail, +// nothing is diffed and no hunk is tried: all of them go between one pair of +// markers. Bytes are taken as latin1, one character each, so that any bytes +// split into lines and come back as they were. +// +// What is not caught: a conflicted merge that the check takes with git's +// conflicts resolved to one side, though not to the other, is returned as git +// made it; the person who resolves it to the refused side meets the refusal. +// And where two changes each refuse the merge, no one of them alone undoes the +// refusal, so every hunk goes between markers, innocent ones included. +import { LABELS } from './labels.ts'; +import type { MergeFile } from './types.ts'; + +/** Whether the merged content of the file at `path` is one its reader takes. */ +export type MergeCheck = (path: string, bytes: Uint8Array) => boolean; + +/** Lines from the current side's `a` to `aEnd`, exclusive, became the merge's from `b` to `bEnd`. */ +interface Hunk { + readonly a: number; + readonly aEnd: number; + readonly b: number; + readonly bEnd: number; +} + +/** Above this many lines between the two sides' common head and tail, nothing is diffed (header). */ +export const DIFF_LIMIT = 2000; + +/** Stands for one of git's conflicts among the merge's lines: a character no latin1 text holds, and its index. */ +const token = (k: number): string => `\u0100${k}\n`; + +/** One of git's conflicts in the merge: its two sides, and its lines as git wrote them, markers included. */ +interface Conflict { + readonly current: string; + readonly new: string; + readonly raw: string; +} + +/** `mergeFile`, its merges held to `check` as the header says. */ +export function checkedMergeFile(mergeFile: MergeFile, check: MergeCheck): MergeFile { + return async (sides) => { + const accepts = (text: string) => check(sides.path, bytes(text)); + const merged = await mergeFile(sides); + const result = lines(merged.bytes); + const parsed = merged.conflicted ? conflicts(result) : { units: result, conflicts: [] }; + if (parsed === undefined) return merged; + const { units, conflicts: found } = parsed; + const resolve = (text: string, side: 'current' | 'new' | 'raw') => + text.replace(/\u0100(\d+)\n/g, (_, k: string) => found[Number(k)]?.[side] ?? ''); + const whole = units.join(''); + if ( + merged.conflicted + ? accepts(resolve(whole, 'current')) || accepts(resolve(whole, 'new')) + : check(sides.path, merged.bytes) + ) + return merged; + if (!check(sides.path, sides.current) || !check(sides.path, sides.new)) return merged; + const current = lines(sides.current); + const eol = current.find((line) => line.endsWith('\n'))?.endsWith('\r\n') ? '\r\n' : '\n'; + const { hunks: all, bounded } = diff(current, units); + const refused = bounded ? [] : all.filter((h) => accepts(resolve(undo(current, units, h), 'current'))); + const marked = new Set(refused.length > 0 ? refused : all); + let text = ''; + let at = 0; + for (const h of all) { + text += resolve(units.slice(at, h.b).join(''), 'raw'); + const theirs = units.slice(h.b, h.bEnd).join(''); + if (!marked.has(h)) text += resolve(theirs, 'raw'); + else + text += + `<<<<<<< ${LABELS.current}${eol}${closed(current.slice(h.a, h.aEnd).join(''), eol)}=======${eol}` + + `${closed(resolve(theirs, 'new'), eol)}>>>>>>> ${LABELS.new}${eol}`; + at = h.bEnd; + } + text += resolve(units.slice(at).join(''), 'raw'); + return { bytes: bytes(text), conflicted: true }; + }; +} + +/** The merge's lines with one hunk undone, its conflicts left as tokens. */ +function undo(current: readonly string[], units: readonly string[], h: Hunk): string { + return [...units.slice(0, h.b), ...current.slice(h.a, h.aEnd), ...units.slice(h.bEnd)].join(''); +} + +/** + * The merge's lines with each of git's conflicts as one token, and the + * conflicts; nothing where a conflict is not closed as git closes it. + */ +function conflicts(result: readonly string[]): { units: string[]; conflicts: Conflict[] } | undefined { + const units: string[] = []; + const found: Conflict[] = []; + const bare = (line: string) => line.replace(/\r?\n$/, ''); + for (let i = 0; i < result.length; i++) { + const line = result[i] ?? ''; + if (bare(line) !== `<<<<<<< ${LABELS.current}`) { + units.push(line); + continue; + } + const separator = result.findIndex((l, j) => j > i && bare(l) === '======='); + const end = result.findIndex((l, j) => j > separator && bare(l) === `>>>>>>> ${LABELS.new}`); + if (separator < 0 || end < 0) return undefined; + found.push({ + current: result.slice(i + 1, separator).join(''), + new: result.slice(separator + 1, end).join(''), + raw: result.slice(i, end + 1).join(''), + }); + units.push(token(found.length - 1)); + i = end; + } + return { units, conflicts: found }; +} + +/** The hunks of a line diff from `a` to `b`, in order; one hunk over the whole middle where it exceeds DIFF_LIMIT. */ +function diff(a: readonly string[], b: readonly string[]): { hunks: Hunk[]; bounded: boolean } { + let head = 0; + while (head < a.length && head < b.length && a[head] === b[head]) head++; + let [aEnd, bEnd] = [a.length, b.length]; + while (aEnd > head && bEnd > head && a[aEnd - 1] === b[bEnd - 1]) [aEnd, bEnd] = [aEnd - 1, bEnd - 1]; + const [n, m] = [aEnd - head, bEnd - head]; + if (n + m > DIFF_LIMIT) return { hunks: [{ a: head, aEnd, b: head, bEnd }], bounded: true }; + // The length of the longest common subsequence of the two middles from their lines i and j on. + const common = new Uint32Array((n + 1) * (m + 1)); + const lcs = (i: number, j: number) => common[i * (m + 1) + j] ?? 0; + for (let i = n - 1; i >= 0; i--) + for (let j = m - 1; j >= 0; j--) + common[i * (m + 1) + j] = + a[head + i] === b[head + j] ? lcs(i + 1, j + 1) + 1 : Math.max(lcs(i + 1, j), lcs(i, j + 1)); + const found: Hunk[] = []; + let open: { a: number; b: number } | undefined; + let [i, j] = [0, 0]; + const close = () => { + if (open) found.push({ a: open.a, aEnd: head + i, b: open.b, bEnd: head + j }); + open = undefined; + }; + while (i < n || j < m) { + if (i < n && j < m && a[head + i] === b[head + j]) { + close(); + [i, j] = [i + 1, j + 1]; + continue; + } + open ??= { a: head + i, b: head + j }; + if (j < m && (i === n || lcs(i, j + 1) >= lcs(i + 1, j))) j++; + else i++; + } + close(); + return { hunks: found, bounded: false }; +} + +/** The lines of `bytes`, each with its newline, the last one without where the file ends without. */ +function lines(bytes: Uint8Array): string[] { + return ( + Buffer.from(bytes) + .toString('latin1') + .match(/[^\n]*\n|[^\n]+$/g) ?? [] + ); +} + +const bytes = (text: string): Uint8Array => new Uint8Array(Buffer.from(text, 'latin1')); + +/** `text` with a line ending after its last line where that lacks one. */ +const closed = (text: string, eol: string): string => (text === '' || text.endsWith('\n') ? text : `${text}${eol}`); diff --git a/packages/cli-template/src/directories.test.ts b/packages/cli-template/src/directories.test.ts index c1229fd0..8792a404 100644 --- a/packages/cli-template/src/directories.test.ts +++ b/packages/cli-template/src/directories.test.ts @@ -168,3 +168,31 @@ test('readTemplateDirectory returns the manifest and the tree of a template dire s.remove(); } }); + +test('planMerge holds each merged file to the check it is given: a merge the check refuses is a conflict', async () => { + const s = scratch(); + try { + put(s.dir, { 'a.txt': 'x\none\ny\n', 'b.txt': 'x\none\ny\n' }); + const old = literal({ 'a.txt': 'x\ny\n', 'b.txt': 'x\ny\n' }); + const next = literal({ 'a.txt': 'x\ny\none\n', 'b.txt': 'x\ny\none\n' }); + // The one line `one` stands once in a.txt; b.txt is free. + const once = (path: string, bytes: Uint8Array) => + path !== 'a.txt' || + Buffer.from(bytes) + .toString() + .split('\n') + .filter((l) => l === 'one').length <= 1; + const plan = await planMerge(s.dir, old, next, once); + assert.deepEqual(plan.report, [ + { path: 'a.txt', outcome: 'conflicted' }, + { path: 'b.txt', outcome: 'clean' }, + ]); + await plan.apply(); + assert.deepEqual(read(s.dir), { + 'a.txt': 'x\none\ny\n<<<<<<< current\n=======\none\n>>>>>>> new render\n', + 'b.txt': 'x\none\ny\none\n', + }); + } finally { + s.remove(); + } +}); diff --git a/packages/cli-template/src/directory.ts b/packages/cli-template/src/directory.ts index de916f8e..f38889d4 100644 --- a/packages/cli-template/src/directory.ts +++ b/packages/cli-template/src/directory.ts @@ -61,8 +61,11 @@ // returns the report with `apply`, which makes the directory hold the result. // Nothing is written before `apply`, so a caller can show the report first; the // merge of the command `plx-template merge` is the same plan applied at once. +// A caller that knows what its files must be gives `planMerge` a check, and each +// file's merge is then held to it (checked-merge-file.ts); the command gives none. import { chmod, lstat, mkdir, readdir, readFile, readlink, rmdir, unlink, writeFile } from 'node:fs/promises'; import { join, resolve } from 'node:path'; +import { checkedMergeFile, type MergeCheck } from './checked-merge-file.ts'; import { InputError, messageOf } from './errors.ts'; import { gitMergeFile } from './git-merge-file.ts'; import { readTemplate } from './manifest.ts'; @@ -363,11 +366,16 @@ export interface MergePlan { } /** The merge of `old` and `next` into the directory `target`, as the header says. */ -export async function planMerge(target: string, old: RenderedSide, next: RenderedSide): Promise { +export async function planMerge( + target: string, + old: RenderedSide, + next: RenderedSide, + check?: MergeCheck, +): Promise { const current = await readCurrent(target, new Set([...old.tree.keys(), ...next.tree.keys()])); const { tree, report } = await merge( { old: old.tree, new: next.tree, current, files: { old: old.policies, new: next.policies } }, - gitMergeFile, + check ? checkedMergeFile(gitMergeFile, check) : gitMergeFile, ); const changes = new Map(); for (const { path, outcome } of report) { diff --git a/packages/cli-template/src/git-merge-file.ts b/packages/cli-template/src/git-merge-file.ts index dd27b129..99808569 100644 --- a/packages/cli-template/src/git-merge-file.ts +++ b/packages/cli-template/src/git-merge-file.ts @@ -41,11 +41,9 @@ import { spawn } from 'node:child_process'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { devNull, tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { LABELS } from './labels.ts'; import type { FileSides, MergedFile } from './types.ts'; -/** The labels of the three sides, in the order git merge-file takes them. */ -const LABELS = { current: 'current', old: 'old render', new: 'new render' } as const; - /** The lines that open and close a conflict, without their line ending. */ const MARKERS = new Set([`<<<<<<< ${LABELS.current}`, `>>>>>>> ${LABELS.new}`]); diff --git a/packages/cli-template/src/index.ts b/packages/cli-template/src/index.ts index cfb0599b..ffbd2748 100644 --- a/packages/cli-template/src/index.ts +++ b/packages/cli-template/src/index.ts @@ -6,9 +6,11 @@ // meaning are in types.ts: `render` and `merge`. It reads and writes no // directory and runs no command (boundary.test.ts). `gitMergeFile`, the real // merge of one file that the caller hands to `merge`, is the one function -// that does: it writes temporary files and runs git. The functions that touch +// that does: it writes temporary files and runs git; `checkedMergeFile` holds +// its merges to a check of the caller's. The functions that touch // a directory for a caller of the library are exported beside them, `readTree`, // `readManifest`, `readRender` and `planMerge` (directory.ts). +export { checkedMergeFile, type MergeCheck } from './checked-merge-file.ts'; export { type MergePlan, planMerge, diff --git a/packages/cli-template/src/labels.ts b/packages/cli-template/src/labels.ts new file mode 100644 index 00000000..3af4c166 --- /dev/null +++ b/packages/cli-template/src/labels.ts @@ -0,0 +1,7 @@ +// The labels of a merge's three sides: `gitMergeFile` hands them to git, which +// writes the first and the last into a conflict's marker lines, and +// `checkedMergeFile` writes the same marker lines itself, so that a conflict +// reads the same whoever made it. + +/** The labels of the three sides, in the order git merge-file takes them. */ +export const LABELS = { current: 'current', old: 'old render', new: 'new render' } as const; diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index 5984dd4d..574cba6a 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -22,7 +22,15 @@ // plx deploy deploy@1.2.3.4 website --image … --commit-sha // # the app shows it, where its file uses ${PLEXUS_COMMIT_SHA} import { resolve } from 'node:path'; -import { deploy, deployEnvironment, describeDeploy, environmentOf, imagePrefix, UsageError } from '@plexus-ms/lib'; +import { + deploy, + deployEnvironment, + describeDeploy, + ENVIRONMENT_BRANCHES, + environmentOf, + imagePrefix, + UsageError, +} from '@plexus-ms/lib'; import type { Command } from 'commander'; import { contextOf } from '../program.ts'; @@ -96,7 +104,9 @@ export function register(program: Command): void { const env = process.env; const environment = environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment); if (!environment) - throw new UsageError('no environment: pass --environment, or run on a push to main or develop'); + throw new UsageError( + `no environment: pass --environment, or run on a push to ${Object.keys(ENVIRONMENT_BRANCHES).join(' or ')}`, + ); const result = await deployEnvironment(ctx, { environment, inventory: resolve(opts.inventory), diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index b4b60fc9..4c3be8a9 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -4,7 +4,9 @@ // renders the report: which repo was checked when the directory is inside // one; a failing check is one line, `✗ : `, and a file holding a conflict marker, which is no requirement's, -// `✗ : holds a conflict marker`; a unit with none is `✓ `, with its profile and the +// `✗ : holds a conflict marker`, and an app +// whose compose file still uses the retired display-version variable, which is +// no requirement's either, `✗ : still uses PLEXUS_DISPLAY_VERSION, …`; a unit with none is `✓ `, with its profile and the // deviations its marker lists; a hint, which fails nothing, as `• : // `; in a workspace, one line naming the git roots // that are not Plexus repos; one naming the symbolic links not followed (an diff --git a/packages/lib/package.json b/packages/lib/package.json index 3a905af7..72f4b12c 100644 --- a/packages/lib/package.json +++ b/packages/lib/package.json @@ -35,6 +35,7 @@ "dependencies": { "@plexus-ms/cli-template": "workspace:*", "semver": "^7.8.6", + "smol-toml": "^1.9.1", "yaml": "^2.9.1" }, "devDependencies": { diff --git a/packages/lib/src/ciRoot.test.ts b/packages/lib/src/ciRoot.test.ts new file mode 100644 index 00000000..63edaf6e --- /dev/null +++ b/packages/lib/src/ciRoot.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { renderBundled, textOf } from './testing/bundled.ts'; + +// The root ci/ of repo-operations, rendered and run by Terraform against the +// workspace's own module and a mocked provider: no token, no network (the +// provider comes from the plugin cache `mise check` fills). What a hosts file +// born at an older version means to the root is held here, since `validate` +// does not read values. +const REPO = join(import.meta.dirname, '../../..'); +const CACHE = process.env.TF_PLUGIN_CACHE_DIR ?? join(REPO, 'node_modules/.cache/terraform-plugins'); + +const FILLED = [ + [/^ {2}iam_admins = \[\]$/m, ' iam_admins = [{ name = "alice", ssh_keys = ["ssh-ed25519 AAAA alice"] }]'], + [/^ {2}ssh_keys {3}= \[\]$/m, ' ssh_keys = ["key-a"]'], +] as const; + +// The binary the repo pins, found from the repo: a shim finds no version in a temporary directory. +const TERRAFORM = + spawnSync('mise', ['which', 'terraform'], { cwd: REPO, encoding: 'utf8' }).stdout.trim() || 'terraform'; + +let dir = ''; +let usual = ''; + +const tf = (...args: string[]) => + spawnSync(TERRAFORM, args, { + cwd: join(dir, 'ci'), + encoding: 'utf8', + env: { + ...process.env, + TF_IN_AUTOMATION: '1', + TF_CLI_CONFIG_FILE: join(dir, 'terraformrc'), + HTTP_PROXY: 'http://127.0.0.1:9', + HTTPS_PROXY: 'http://127.0.0.1:9', + }, + }); + +/** The hosts file as rendered, filled in so that the module accepts it, with `hosts`; `without` removes the lines naming an attribute. */ +function hostsFile(hosts: string, without: string[] = []): string { + let text = usual; + for (const [pattern, filled] of FILLED) text = text.replace(pattern, filled); + for (const key of without) text = text.replace(new RegExp(`^ {2}${key}\\s+=.*\\n`, 'm'), ''); + return text.replace(/^hosts = \{\}$/m, `hosts = {\n${hosts}\n}`); +} + +before(async () => { + const result = await renderBundled(['repo-operations'], { tenant: 'acme', ci_strategy: 'byom' }); + dir = mkdtempSync(join(tmpdir(), 'ci-root-')); + mkdirSync(join(dir, 'ci/tests'), { recursive: true }); + for (const name of ['main.tf', 'variables.tf', 'backend.tf', 'hosts.auto.tfvars']) + writeFileSync(join(dir, 'ci', name), textOf(result, `ci/${name}`)); + usual = textOf(result, 'ci/hosts.auto.tfvars'); + const main = readFileSync(join(dir, 'ci/main.tf'), 'utf8').replace( + /git::[^"]*\/\/terraform\/hcloud_ci_runner_host\?ref=[^"]+/, + '../terraform/hcloud_ci_runner_host', + ); + // A local module must stay inside its package: the workspace's two modules are copied beside the root. + for (const module of ['hcloud_ci_runner_host', 'ci_runner_host_user_data']) + cpSync(join(REPO, 'terraform', module), join(dir, 'terraform', module), { + recursive: true, + filter: (path) => !/\.terraform|tests/.test(path.slice(REPO.length)), + }); + writeFileSync(join(dir, 'ci/main.tf'), main); + writeFileSync( + join(dir, 'ci/tests/root.tftest.hcl'), + `mock_provider "hcloud" {} +variables { + op_service_account_token = "ops_Example-0123456789" +} + +run "settings_of_the_hosts" { + command = plan + assert { + condition = jsonencode(output.settings["ci-1"]) == jsonencode(merge(var.defaults, { connect_server = false })) + error_message = "ci-1 takes the usual values and connect_server false" + } + assert { + condition = output.settings["ci-2"].connect_server == true + error_message = "ci-2 turns the Connect server on for itself" + } +} +`, + ); + // The provider is installed from the plugin cache and nowhere else. + writeFileSync( + join(dir, 'terraformrc'), + `provider_installation {\n filesystem_mirror {\n path = "${CACHE}"\n }\n}\n`, + ); + const init = tf('init', '-input=false', '-backend=false'); + assert.equal( + init.status, + 0, + `${init.stdout}${init.stderr}\nThe provider is installed from the plugin cache, ${CACHE}, which \`mise check\` fills: run it first.`, + ); +}); + +after(() => rmSync(dir, { recursive: true, force: true })); + +const plans = (hosts: string, without: string[] = []) => { + writeFileSync(join(dir, 'ci/hosts.auto.tfvars'), hostsFile(hosts, without)); + return tf('test', '-no-color'); +}; + +const HOSTS = ' "ci-1" = {}\n "ci-2" = { connect_server = true }'; + +test('a hosts file born before connect_server existed plans, and the host takes false', () => { + const ran = plans(HOSTS, ['connect_server']); + assert.equal(ran.status, 0, ran.stdout + ran.stderr); +}); + +test('a hosts file that states connect_server = false plans the same', () => { + const ran = plans(HOSTS); + assert.equal(ran.status, 0, ran.stdout + ran.stderr); +}); + +test('a misspelt key and a null are still refused by name', () => { + const typoHost = plans(' "ci-1" = { conect_server = true }', ['connect_server']); + assert.notEqual(typoHost.status, 0); + assert.match(typoHost.stdout + typoHost.stderr, /ci-1\.conect_server/); + const nullHost = plans(' "ci-1" = { connect_server = null }', ['connect_server']); + assert.notEqual(nullHost.status, 0); + assert.match(nullHost.stdout + nullHost.stderr, /ci-1\.connect_server is null/); + writeFileSync( + join(dir, 'ci/hosts.auto.tfvars'), + hostsFile(' "ci-1" = {}', ['connect_server']).replace(/^defaults = \{/m, 'defaults = {\n conect_server = true'), + ); + const typoDefault = tf('test', '-no-color'); + assert.notEqual(typoDefault.status, 0); + assert.match(typoDefault.stdout + typoDefault.stderr, /unknown: \[conect_server\]/); + writeFileSync( + join(dir, 'ci/hosts.auto.tfvars'), + hostsFile(' "ci-1" = {}', ['connect_server']).replace(/^defaults = \{/m, 'defaults = {\n connect_server = null'), + ); + const nullDefault = tf('test', '-no-color'); + assert.notEqual(nullDefault.status, 0); + assert.match(nullDefault.stdout + nullDefault.stderr, /defaults\.connect_server is null/); +}); + +test('an attribute other than a fallback still has to be in defaults', () => { + const ran = plans(HOSTS, ['connect_server', 'location']); + assert.notEqual(ran.status, 0); + assert.match(ran.stdout + ran.stderr, /missing: \[location\]/); +}); + +test('the user-data module’s header states once the rule for a setting added later that is written only where it differs from the role’s default', () => { + const main = readFileSync(join(REPO, 'terraform/ci_runner_host_user_data/main.tf'), 'utf8'); + const header = main.slice(0, main.indexOf('locals {')); + assert.match( + header.replace(/\n# /g, ' '), + /a setting added after the module first shipped is written only where it differs from the role's default, so that taking it replaces no host.*the values from the start are always written/i, + ); + assert.match(header.replace(/\n# /g, ' '), /credentials and the token/); +}); diff --git a/packages/lib/src/compose.ts b/packages/lib/src/compose.ts index 0d42f47d..81d47a2e 100644 --- a/packages/lib/src/compose.ts +++ b/packages/lib/src/compose.ts @@ -70,6 +70,36 @@ export const IMAGE_PLACEHOLDER = /\$\{PLEXUS_DEPLOYMENT_IMAGE(:[^}]*)?\}/g; */ export const COMMIT_SHA_PLACEHOLDER = /\$\{PLEXUS_COMMIT_SHA(:[^}]*)?\}/g; +/** + * Whether a compose text interpolates the display-version variable the deploy + * verb pins no more, in either of compose's forms: `${NAME…}` with a default, + * an error or none, and `$NAME`; `$$` escapes the dollar. The one definition: + * the deploy verb refuses such a file, and `plx doctor` reports it first. + * The text is read as text, so a comment that spells the form counts. + */ +export const holdsRetiredDisplayVersion = (text: string): boolean => + /(? Promise, + source: string, +): Promise<{ path: string; text: string } | undefined> { + for (const path of COMPOSE_FILES) { + try { + return { path, text: await read(`${source}/${path}`) }; + } catch {} + } + return undefined; +} + /** An image as the deploy verb will run it: every spelling of the placeholder as one. */ export const normalImage = (image: string): string => image.replace(IMAGE_PLACEHOLDER, '${PLEXUS_DEPLOYMENT_IMAGE}'); diff --git a/packages/lib/src/deploy.test.ts b/packages/lib/src/deploy.test.ts index 69423ffa..eb259ad7 100644 --- a/packages/lib/src/deploy.test.ts +++ b/packages/lib/src/deploy.test.ts @@ -257,7 +257,7 @@ test('a compose file that interpolates the old version placeholder fails with on error instanceof UsageError && !error.message.includes('\n') && error.message.includes('apps/web/docker/compose.yaml') && - error.message.includes('PLEXUS_DISPLAY_VERSION') && + error.message.includes('uses PLEXUS_DISPLAY_VERSION,') && /does not pin/.test(error.message), line, ); diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index 934557d1..f78e2f6f 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -79,9 +79,11 @@ import { COMMIT_SHA_PLACEHOLDER, declaresHealthcheck, healthcheckOf, + holdsRetiredDisplayVersion, IMAGE_PLACEHOLDER, type Mapping, parseCompose, + readComposeFile, } from './compose.ts'; import { Context } from './context.ts'; import { @@ -138,13 +140,6 @@ export interface Deploy { const INCOMING = '.incoming'; -/** - * A variable compose would interpolate that the verb pins no more, in either - * of compose's forms: `${NAME…}` with a default, an error or none, and `$NAME`; - * `$$` escapes the dollar. - */ -const INTERPOLATES_RETIRED = /(? ctx.readFile(join(dir, path)), source); + if (found === undefined) throw new UsageError(`no compose.yaml under ${source}; run from the app's source repo (§ 2 PLX-App)`); - if (INTERPOLATES_RETIRED.test(text)) - throw new UsageError(`${compose} uses \${PLEXUS_DISPLAY_VERSION}, which the deploy verb does not pin; remove it`); + const { text } = found; + const compose = `${source}/${found.path}`; + if (holdsRetiredDisplayVersion(text)) + throw new UsageError(`${compose} uses PLEXUS_DISPLAY_VERSION, which the deploy verb does not pin; remove it`); const withImage = renderCompose(text, image, compose); const rendered = renderCommitSha(withImage, options.commitSha || undefined, compose); const pinned: Shown = rendered === withImage ? {} : { commitSha: options.commitSha }; diff --git a/packages/lib/src/deployTargets.test.ts b/packages/lib/src/deployTargets.test.ts index 13ecfe0b..e2d52c72 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -4,6 +4,7 @@ import { Context } from './context.ts'; import { deployLegs, deploymentSlug, + ENVIRONMENT_BRANCHES, environmentOf, parseInventoryFile, readDeployTargets, @@ -177,3 +178,14 @@ test('the environment follows the branch on a push or a run by hand, and a given assert.equal(environmentOf('pull_request', 'main'), ''); assert.equal(environmentOf('pull_request', '12/merge', 'staging'), 'staging'); }); + +test('the branches that deploy are the ones environmentOf maps to an environment', () => { + for (const [branch, environment] of Object.entries(ENVIRONMENT_BRANCHES)) + assert.equal(environmentOf('push', branch), environment); + assert.deepEqual(Object.keys(ENVIRONMENT_BRANCHES), ['main', 'develop']); +}); + +test('a branch named like a property of every object deploys nowhere', () => { + for (const ref of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) + assert.equal(environmentOf('push', ref), '', ref); +}); diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index 9f4928ab..c9948b6d 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -43,9 +43,13 @@ export const DEFAULT_ENVIRONMENT = 'production'; export function environmentOf(event: string, ref: string, given = ''): string { if (given) return given; if (event !== 'push' && event !== 'workflow_dispatch') return ''; - return ref === 'main' ? DEFAULT_ENVIRONMENT : ref === 'develop' ? 'staging' : ''; + // Own keys only: a branch can be named constructor or toString. + return Object.hasOwn(ENVIRONMENT_BRANCHES, ref) ? (ENVIRONMENT_BRANCHES[ref] ?? '') : ''; } +/** The branches that deploy, each into its environment: the rule `environmentOf` applies, and the list a refusal names. */ +export const ENVIRONMENT_BRANCHES: Readonly> = { main: DEFAULT_ENVIRONMENT, develop: 'staging' }; + /** App name → environment → deploy target. */ export type DeployTargets = Record>; diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 4ff9c6a1..6a9436c1 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli-template'; -import { type Compose, type Mapping, parseCompose } from './compose.ts'; +import { type Compose, holdsRetiredDisplayVersion, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts } from './doctor.ts'; import { REQUIREMENT_NAME } from './lints.ts'; @@ -1434,6 +1434,170 @@ test('doctor reads which tracked files hold a conflict marker, and fails the rep ); }); +// --- the retired display-version placeholder --------------------------------------------- + +/** The compose file of the fixtures with `extra` lines under the app service's `environment`. */ +const composeWith = (...extra: string[]): string => + `${COMPOSE} environment:\n${extra.map((line) => ` ${line}\n`).join('')}`; + +/** The workspace's `web` repo with its apps' compose files replaced: by app name, a text, or a path under the app to a text. */ +function webWith(composes: Record>): { tree: Tree; tracked: string[] } { + const tree = ws(); + const apps = (tree.web as Tree).apps as Tree; + for (const [name, files] of Object.entries(composes)) { + const site = (apps[name] ?? {}) as Tree; + site['PLEXUS.md'] = '---\nprofile: stateless\n---\n'; + site['package.json'] = '{"scripts":{}}'; + site.docker = { Dockerfile: 'FROM node' }; + for (const [path, text] of Object.entries(typeof files === 'string' ? { 'docker/compose.yaml': files } : files)) { + if (path.startsWith('docker/')) (site.docker as Tree)[path.slice('docker/'.length)] = text; + else site[path] = text; + } + apps[name] = site; + } + return { tree, tracked: ['PLEXUS.md', ...Object.keys(composes).map((n) => `apps/${n}/PLEXUS.md`)] }; +} + +const retired = (file: string) => + `\`${file}\` still uses PLEXUS_DISPLAY_VERSION, which the deploy verb refuses: remove it`; + +async function placeholderFindings(composes: Record>) { + const { tree, tracked } = webWith(composes); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, { '/ws/web': tracked }); + // Only what belongs to no requirement: the report of the placeholder is one. + return report.units.map((u) => [u.path, u.findings.filter((f) => !f.requirement).map((f) => f.problem)] as const); +} + +test('an app whose compose file carries the commit and no display version is reported for nothing', async () => { + const text = composeWith('PLEXUS_COMMIT_SHA: ${PLEXUS_COMMIT_SHA:-}'); + assert.deepEqual(await placeholderFindings({ site: text }), [ + ['.', []], + ['apps/site', []], + ]); +}); + +test('an app with a compose file of its own that still interpolates the display version is reported, one line naming the file', async () => { + const text = composeWith('PLEXUS_DISPLAY_VERSION: ${PLEXUS_DISPLAY_VERSION:-}'); + assert.deepEqual(await placeholderFindings({ site: text }), [ + ['.', []], + ['apps/site', [retired('apps/site/docker/compose.yaml')]], + ]); +}); + +test('the file is the one the deploy verb reads: docker/compose.yaml first, then compose.yaml in the app directory', async () => { + const bad = composeWith('V: $PLEXUS_DISPLAY_VERSION'); + assert.deepEqual(await placeholderFindings({ site: { 'docker/compose.yaml': COMPOSE, 'compose.yaml': bad } }), [ + ['.', []], + ['apps/site', []], + ]); + assert.deepEqual(await placeholderFindings({ site: { 'compose.yaml': bad } }), [ + ['.', []], + ['apps/site', [retired('apps/site/compose.yaml')]], + ]); +}); + +test('an app with no compose file at either place is reported for nothing here', async () => { + const { tree, tracked } = webWith({ site: { 'package.json': '{"scripts":{}}' } }); + const site = ((tree.web as Tree).apps as Tree).site as Tree; + delete (site.docker as Tree)['compose.yaml']; + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, { '/ws/web': tracked }); + assert.deepEqual( + report.units.map((u) => [u.path, u.findings.filter((f) => !f.requirement)]), + [ + ['.', []], + ['apps/site', []], + ], + ); +}); + +test('a docker/compose.yaml that cannot be read leaves the compose.yaml beside it to be read, as the verb does', async () => { + assert.deepEqual( + await placeholderFindings({ + site: { 'docker/compose.yaml': UNREADABLE, 'compose.yaml': composeWith('V: $PLEXUS_DISPLAY_VERSION') }, + }), + [ + ['.', []], + ['apps/site', [retired('apps/site/compose.yaml')]], + ], + ); +}); + +test('what the verb lets through is not reported: a name that merely holds the words, an escaped dollar, a longer name', async () => { + const quiet = [ + '# PLEXUS_DISPLAY_VERSION was dropped', + 'PLEXUS_DISPLAY_VERSION: "1.0"', + 'V: $$PLEXUS_DISPLAY_VERSION', + 'V: $PLEXUS_DISPLAY_VERSION_X', + ]; + for (const line of quiet) + assert.deepEqual( + await placeholderFindings({ site: line.startsWith('#') ? `${COMPOSE}${line}\n` : composeWith(line) }), + [ + ['.', []], + ['apps/site', []], + ], + line, + ); +}); + +test('what the verb refuses is reported the same, a comment that spells the dollar form included', async () => { + const text = `${COMPOSE}# was $\{PLEXUS_DISPLAY_VERSION:-}\n`; + assert.deepEqual(await placeholderFindings({ site: text }), [ + ['.', []], + ['apps/site', [retired('apps/site/docker/compose.yaml')]], + ]); +}); + +test('the one definition tells the spellings compose interpolates from the ones it does not', () => { + for (const spelling of [ + '${PLEXUS_DISPLAY_VERSION}', + '${PLEXUS_DISPLAY_VERSION:-}', + '${PLEXUS_DISPLAY_VERSION?x}', + '$PLEXUS_DISPLAY_VERSION', + ]) + assert.equal(holdsRetiredDisplayVersion(`V: ${spelling}\n`), true, spelling); + for (const other of ['$$PLEXUS_DISPLAY_VERSION', '$PLEXUS_DISPLAY_VERSION_X', 'PLEXUS_DISPLAY_VERSION: "1"']) + assert.equal(holdsRetiredDisplayVersion(`V: ${other}\n`), false, other); +}); + +test('every app is judged on its own file, and no deviation silences the report', async () => { + const bad = composeWith('V: ${PLEXUS_DISPLAY_VERSION}'); + const good = composeWith('V: ${PLEXUS_COMMIT_SHA:-}'); + const { tree, tracked } = webWith({ one: bad, two: good, three: bad }); + const web = tree.web as Tree; + const silenced = ((web.apps as Tree).three as Tree)['PLEXUS.md'] as string; + assert.ok(silenced); + (web.apps as Tree).three = { + ...((web.apps as Tree).three as Tree), + 'PLEXUS.md': `---\nprofile: stateless\ndeviations: [${UNCHECKED}]\n---\n\n${reasoned([UNCHECKED])}\n`, + }; + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, { '/ws/web': tracked }); + assert.deepEqual( + report.units.map((u) => [u.path, u.findings.map((f) => [f.requirement, f.problem])]), + [ + ['.', []], + ['apps/one', [[undefined, retired('apps/one/docker/compose.yaml')]]], + ['apps/site', []], + ['apps/three', [[undefined, retired('apps/three/docker/compose.yaml')]]], + ['apps/two', []], + ], + ); +}); + +test('a third-party app of an operations repo is reported too', async () => { + const tree = ws(); + const id = (((tree.ops as Tree).apps as Tree).id as Tree).docker as Tree; + id['compose.yaml'] = `${String(id['compose.yaml'])}\n# $PLEXUS_DISPLAY_VERSION\n`; + const report = await doctorOver(tree, '/ws/ops', ALL_TASKS, { + '/ws/ops': ['PLEXUS.md', 'apps/id/PLEXUS.md'], + }); + const found = report.units.find((u) => u.path === 'apps/id'); + assert.deepEqual( + found?.findings.filter((f) => f.requirement === undefined).map((f) => f.problem), + [retired('apps/id/docker/compose.yaml')], + ); +}); + // --- the marker against the templates this plx bundles ------------------------------------- /** A template as the engine reads it: its manifest, which names the template, and no files. */ diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 4defd79f..e2df2d5a 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -22,6 +22,13 @@ // one per file, whatever the marker lists; it names no requirement, and // nothing excludes a file from it. // +// Also of no requirement, and no deviation silences it: an app whose compose +// file still interpolates the display-version variable the deploy verb no +// longer pins (`holdsRetiredDisplayVersion`, compose.ts, the very test by which the verb refuses) +// is a failing finding of the app, one per file, which says to remove it. The +// file is the one the verb reads (`readComposeFile`, compose.ts): +// `docker/compose.yaml` in the app's directory, else `compose.yaml` there. +// // Also of no requirement, and no deviation silences them: the checks of the // markers as configuration (sites.ts, `markerConfig` below). The root marker's // `version` equals the repo's `plx` pin (and is set where any marker lists @@ -77,11 +84,13 @@ import { type Compose, declaresHealthcheck, healthcheckOf, + holdsRetiredDisplayVersion, isMapping, labelsOf, type Mapping, normalImage, parseCompose, + readComposeFile, truthy, } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; @@ -151,6 +160,8 @@ export interface AppFacts { /** `docker/compose.yaml`; neither field set when there is none. */ compose?: Compose; composeProblem?: string; + /** The compose file the deploy verb would read, relative to the repo, when it holds the retired display-version variable. */ + retiredDisplayVersionIn?: string; /** Whether `docker/Dockerfile` exists. */ dockerfile: boolean; /** `package.json`; neither field set when there is none. */ @@ -482,7 +493,7 @@ function versionOfRoot(repo: RepoFacts): string[] { // --- the diagnosis -------------------------------------------------------------- export interface Finding { - /** The requirement's name, e.g. `PLX-App/LoopbackPort`; none for a conflict marker, which belongs to no requirement. */ + /** The requirement's name, e.g. `PLX-App/LoopbackPort`; none for a conflict marker or a compose file holding the retired display-version variable, which belong to no requirement. */ requirement?: string; problem: string; } @@ -535,6 +546,10 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { if (deviations.includes(name)) continue; for (const problem of run(c, unit, profile)) findings.push({ requirement: name, problem }); } + if (unit.kind === 'app' && unit.retiredDisplayVersionIn) + findings.push({ + problem: `\`${unit.retiredDisplayVersionIn}\` still uses PLEXUS_DISPLAY_VERSION, which the deploy verb refuses: remove it`, + }); if (unit.kind !== 'app') { for (const file of unit.conflicted ?? []) findings.push({ problem: `\`${file}\` holds a conflict marker` }); for (const problem of markerConfig(unit)) findings.push({ problem }); @@ -870,6 +885,10 @@ async function readApp(ctx: Context, dir: Directory, path: string, inRepo: strin ), }; const compose = await ctx.readFile(join(dir.path, 'docker/compose.yaml')).catch(() => undefined); + // The file the deploy verb would read (readComposeFile), which holds the placeholder or not. + const verbs = await readComposeFile((path) => ctx.readFile(path), dir.path); + if (verbs !== undefined && holdsRetiredDisplayVersion(verbs.text)) + app.retiredDisplayVersionIn = join(inRepo, verbs.path); if (compose !== undefined) { try { app.compose = parseCompose(compose, 'docker/compose.yaml'); diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index f808bcaf..d2d1be13 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -62,6 +62,7 @@ export { type DeployTargets, deployLegs, deploymentSlug, + ENVIRONMENT_BRANCHES, type EnvironmentTargets, environmentOf, type InventoryFile, diff --git a/packages/lib/src/mergeCheck.test.ts b/packages/lib/src/mergeCheck.test.ts new file mode 100644 index 00000000..9eaf54b8 --- /dev/null +++ b/packages/lib/src/mergeCheck.test.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { readable } from './mergeCheck.ts'; + +const bytes = (text: string) => new TextEncoder().encode(text); + +test('readable refuses a TOML file with any key twice in one table, and takes the same key in two tables', () => { + assert.equal(readable('mise.toml', bytes('[tools]\nnode = "24"\nnode = "22"\n')), false); + assert.equal(readable('a/pyproject.toml', bytes('[project]\nname = "a"\n[project]\nversion = "1"\n')), false); + assert.equal(readable('mise.toml', bytes('[tools]\nnode = "24"\n[env]\nnode = "x"\n')), true); +}); + +test('readable takes every file that is not TOML, whatever it holds', () => { + assert.equal(readable('list.txt', bytes('a = 1\na = 2\n')), true); + assert.equal(readable('mise.toml.bak', bytes('<<<<<<<\n')), true); +}); + +test('readable refuses a TOML file that is not UTF-8, as TOML is', () => { + assert.equal(readable('mise.toml', Uint8Array.from([...bytes('a = "'), 0xff, ...bytes('"\n')])), false); +}); diff --git a/packages/lib/src/mergeCheck.ts b/packages/lib/src/mergeCheck.ts new file mode 100644 index 00000000..fc4cc1a5 --- /dev/null +++ b/packages/lib/src/mergeCheck.ts @@ -0,0 +1,24 @@ +// mergeCheck: what plx holds each merged file to (sync.ts), through the +// engine's check of a merge (`checkedMergeFile` of +// @plexus-ms/cli-template). git merges lines, and a template that starts to +// render a key a repo already has elsewhere in the file merges clean into a +// file that holds the key twice; mise refuses such a mise.toml, and every task +// of the repo fails. Held to this check, that merge is a conflict between +// markers instead, at the template's line, which a person resolves. +// +// A file named `*.toml` must be UTF-8 and parse as TOML, which refuses a key defined twice +// in one table among other errors; every other file passes. It holds for every +// TOML file a template renders and for every key, not for one tool. +import type { MergeCheck } from '@plexus-ms/cli-template'; +import { parse } from 'smol-toml'; + +/** Whether a merged file is one its reader takes: a TOML file parses. */ +export const readable: MergeCheck = (path, bytes) => { + if (!path.endsWith('.toml')) return true; + try { + parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + return true; + } catch { + return false; + } +}; diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index a2de7de8..fc827f08 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -200,6 +200,9 @@ test('the job deploy reads no mise.toml of the repo: its config paths are ignore const tool = (name: string) => `'npm:@plexus-ms/${name}[allow_low_downloads=true]@${VERSION}'`; assert.equal(deploy?.steps?.[2]?.['working-directory'], '${{ runner.temp }}'); assert.equal(deploy?.steps?.[2]?.run, `mise use -g node@${node} ${tool('cli')} ${tool('cli-ci')}`); + // On a slot mise finds the image's plx-ci at this version and rebuilds the image's shims, which only root can + // write: the step's are written into its own temp directory. + assert.deepEqual(deploy?.steps?.[2]?.env, { MISE_SYSTEM_SHIMS_DIR: '${{ runner.temp }}/mise-system-shims' }); assert.deepEqual( stepsOf(deploy) .slice(0, 3) diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index 4796f029..87e8bade 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -1,8 +1,12 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { test } from 'node:test'; -import { generatedFrom, pathsOf, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; +import { merge, readTree } from '@plexus-ms/cli-template'; +import { CURRENT, PLAIN_BACKEND, templatesBefore } from './testing/before.ts'; +import { generatedFrom, pathsOf, renderAt, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ const toolsOf = (mise: string): string[] => @@ -89,10 +93,10 @@ test('the answers are the questions’ defaults, and the org follows the tenant' test('the tenant is required, and the error carries its help', async () => { const result = await renderBundled(['repo-operations'], {}); - // The org defaults to the tenant, so its question fails with it. + // The org and the key of the state default to the tenant, so their questions fail with it. assert.deepEqual( result.errors.map((e) => e.question), - ['tenant', 'github_org'], + ['tenant', 'github_org', 'ci_state_key'], ); assert.match(result.errors[0]?.message ?? '', /Tenant slug/); }); @@ -292,6 +296,49 @@ test('a host is a name and what the module takes, the tenant’s usual values it assert.match(tfvars, /ci-runner-unregister/, 'a person removing an entry is told to unregister first'); }); +test('a host turns its Connect server on by connect_server, off in the usual values, and the root passes it the way it passes turbo_cache_overlay', async () => { + const result = await render({ ci_strategy: 'byom' }); + assert.match(textOf(result, 'ci/hosts.auto.tfvars'), /^ {2}connect_server\s+= false$/m); + assert.match(textOf(result, 'ci/variables.tf'), /attributes = \[[^\]]*"connect_server"/); + assert.match(textOf(result, 'ci/main.tf'), /connect_server\s+= local\.settings\[each\.key\]\.connect_server/); +}); + +test('the root’s list of attributes is the module’s inputs and no more', async () => { + const root = textOf(await render({ ci_strategy: 'byom' }), 'ci/variables.tf'); + const listed = + /attributes = \[([^\]]*)\]/ + .exec(root)?.[1] + ?.match(/"([^"]+)"/g) + ?.map((name) => name.slice(1, -1)) ?? []; + const module = readFileSync( + join(import.meta.dirname, '../../../terraform/hcloud_ci_runner_host/variables.tf'), + 'utf8', + ); + const inputs = [...module.matchAll(/^variable "(\w+)"/gm)] + .map((m) => m[1] ?? '') + .filter((name) => !['name', 'owner', 'plexus_version', 'op_service_account_token'].includes(name)); + assert.deepEqual([...listed].sort(), inputs.sort()); +}); + +test('where a tenant decides on connect_server, it says what the host then holds and what is untried', async () => { + const result = await render({ ci_strategy: 'byom' }); + const tfvars = textOf(result, 'ci/hosts.auto.tfvars'); + const above = /((?:^ {2}#.*\n)+)^ {2}connect_server\s+=/m.exec(tfvars)?.[1] ?? ''; + assert.match(above, /every slot[^\n]*(repo|delivery)[\s\S]*deploy key/i); + assert.match(above, /untried/); + const variables = textOf(result, 'ci/variables.tf'); + assert.match(variables, /connect_server[\s\S]*deploy key[\s\S]*untried/); +}); + +test('the root gives an attribute added after a hosts file was born a fallback, by one rule, and never a key that is no attribute', async () => { + const result = await render({ ci_strategy: 'byom' }); + const variables = textOf(result, 'ci/variables.tf'); + const main = textOf(result, 'ci/main.tf'); + assert.match(variables, /fallbacks\s+= \{ connect_server = false \}/); + assert.match(variables, /byte for byte/); + assert.match(main, /merge\(local\.fallbacks, var\.defaults, host\)/); +}); + test('the files hold no secret: the provider’s token and the bootstrap token are pointers, the rest names nothing of a tenant but its answers', async () => { const result = await render({ ci_strategy: 'byom' }); const secrets = textOf(result, 'ci/secrets.env') @@ -323,13 +370,23 @@ test('the state and the plans of ci/ stay out of git, whose lock file stays in', assert.doesNotMatch(textOf(await render(), '.gitignore'), /tfstate/); }); -test('Terraform is pinned in mise.toml at the version tooling checks its modules with', async () => { - const workspace = readFileSync(join(import.meta.dirname, '..', '..', '..', 'mise.toml'), 'utf8'); - const wanted = /^terraform = "([^"]+)"/m.exec(workspace)?.[1]; - assert.ok(wanted); +test('Terraform is pinned in mise.toml by the major of the version tooling checks its modules with, which every module accepts', async () => { + const root = join(import.meta.dirname, '..', '..', '..'); + const checked = /^terraform = "(\d+)\.\d+\.\d+"/m.exec(readFileSync(join(root, 'mise.toml'), 'utf8'))?.[1]; + assert.ok(checked, "tooling's own pin is a version"); assert.ok(toolsOf(textOf(await render({ ci_strategy: 'byom' }), 'mise.toml')).includes('terraform')); - assert.match(textOf(await render({ ci_strategy: 'byom' }), 'mise.toml'), new RegExp(`^terraform = "${wanted}"`, 'm')); + assert.match( + textOf(await render({ ci_strategy: 'byom' }), 'mise.toml'), + new RegExp(`^terraform = "${checked}"`, 'm'), + ); assert.ok(!toolsOf(textOf(await render(), 'mise.toml')).includes('terraform')); + // The newest release of the major, which mise installs for it, satisfies each module's floor of the same major. + for (const module of ['hcloud_ci_runner_host', 'ci_runner_host_user_data']) { + const floor = /required_version = ">= (\d+)\.\d+"/.exec( + readFileSync(join(root, 'terraform', module, 'terraform.tf'), 'utf8'), + )?.[1]; + assert.equal(floor, checked, module); + } }); test('the task ci-hosts runs the wrapper, and check holds the root to format and validation', async () => { @@ -378,7 +435,7 @@ test('the hosts file and the root say which edit of defaults replaces a host, wh assert.doesNotMatch(text, /edit of `defaults` replaces every host|never updated/, path); assert.match( text, - /slots, turbo_cache_overlay, overlay_management_url or iam_admins[^\n]*or location[^\n]*replaces every host that does not set it itself/, + /slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins[^\n]*or location[^\n]*replaces every host that does not set it itself/, path, ); assert.match(text, /server_type[^\n]*resized in place, which powers the host off: power it on afterwards/, path); @@ -433,3 +490,241 @@ test('the hosts and the defaults refuse an attribute the module does not take, n assert.match(block, /error_message\s+= [^\n]*\$\{/, `${name}: the message names the keys`); } }); + +// --- where the state of ci/ is kept --------------------------------------------------------- + +const BUCKET = { + ci_strategy: 'byom', + ci_state_bucket: 'acme-state', + ci_state_endpoint: 'https://s3.storage.example.test', + ci_state_region: 'eu-one', +}; + +/** What Terraform says of `backend.tf` alone in a directory of its own: the three verbs the check of ci/ runs, none of them reaching a backend or a registry. */ +function terraformHolds(backend: string): void { + const dir = mkdtempSync(join(tmpdir(), 'plx-255-')); + try { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'backend.tf'), backend); + for (const args of [['fmt', '-check', '-diff'], ['init', '-backend=false', '-input=false'], ['validate']]) + execFileSync('terraform', [`-chdir=${dir}`, ...args], { stdio: 'pipe', encoding: 'utf8', timeout: 120_000 }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +test('a tenant that names no bucket gets the local backend with its warning, and no pointer for a bucket', async () => { + const result = await render({ ci_strategy: 'byom' }); + assert.deepEqual(result.errors, []); + const backend = textOf(result, 'ci/backend.tf'); + assert.match(backend, /backend "local" \{\n\s+path = "terraform\.tfstate"/); + assert.doesNotMatch(backend, /"s3"/); + assert.match(backend, /only record of which hosts exist/); + assert.doesNotMatch(textOf(result, 'ci/secrets.env'), /AWS_/); + terraformHolds(backend); +}); + +test('a tenant that names a bucket gets the s3 backend for a store that is not AWS, which init and validate take without reaching it', async () => { + const result = await render(BUCKET); + assert.deepEqual(result.errors, []); + const backend = textOf(result, 'ci/backend.tf'); + assert.match(backend, /backend "s3" \{/); + assert.doesNotMatch(backend, /backend "local"/); + assert.match(backend, /bucket\s+= "acme-state"/); + assert.match(backend, /region\s+= "eu-one"/); + assert.match(backend, /key\s+= "acme\/ci\/terraform\.tfstate"/); + assert.match(backend, /endpoints = \{ s3 = "https:\/\/s3\.storage\.example\.test" \}/); + for (const flag of [ + 'use_path_style', + 'skip_credentials_validation', + 'skip_region_validation', + 'skip_requesting_account_id', + 'skip_metadata_api_check', + ]) + assert.match(backend, new RegExp(`${flag}\\s+= true`), flag); + assert.doesNotMatch(backend, /access_key|secret_key|AKIA/, 'the credentials are never in the file'); + terraformHolds(backend); +}); + +test('the state header says what the state holds, for either backend, and that the tenant owns the file', async () => { + for (const answers of [{ ci_strategy: 'byom' }, BUCKET]) { + const backend = textOf(await render(answers), 'ci/backend.tf'); + const shape = JSON.stringify(answers); + assert.match(backend, /plx update never changes/i, shape); + assert.match(backend, /only record of which hosts exist/, shape); + assert.match(backend, /hash of each host's user-data/, shape); + assert.match(backend, /plan file[^\n]*holds the (bootstrap )?token in clear/, shape); + } +}); + +test('the bucket’s credentials are two pointers beside the provider’s, only where a bucket is named', async () => { + const secrets = textOf(await render(BUCKET), 'ci/secrets.env') + .split('\n') + .filter((line) => line !== '' && !line.startsWith('#')); + assert.deepEqual( + secrets.map((line) => line.split('=')[0]), + ['HCLOUD_TOKEN', 'TF_VAR_op_service_account_token', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'], + ); + for (const line of secrets) assert.match(line, /^[A-Za-z_]+=op:\/\/acme\/[\w-]+\/[\w-]+$/, line); + assert.match( + textOf(await render(BUCKET), 'ci/secrets.env'), + /^AWS_ACCESS_KEY_ID=op:\/\/acme\/bucket-ci-state\/access-key-id$/m, + ); + assert.match( + textOf(await render(BUCKET), 'ci/secrets.env'), + /^AWS_SECRET_ACCESS_KEY=op:\/\/acme\/bucket-ci-state\/secret-access-key$/m, + ); + assert.match(textOf(await render(BUCKET), 'ci/terraformw'), /op run --env-file secrets\.env -- terraform "\$@"/); + for (const answers of [{ ci_strategy: 'byom' }, { ci_strategy: 'github' }, {}]) + assert.doesNotMatch(textOf(await render(answers), 'secrets.env'), /AWS_/, JSON.stringify(answers)); +}); + +test('the key defaults to one no other tenant’s root shares, and may be answered', async () => { + assert.match(textOf(await render(BUCKET), 'ci/backend.tf'), /key\s+= "acme\/ci\/terraform\.tfstate"/); + assert.match( + textOf(await render({ ...BUCKET, tenant: 'zeta' }), 'ci/backend.tf'), + /key\s+= "zeta\/ci\/terraform\.tfstate"/, + ); + assert.match( + textOf(await render({ ...BUCKET, ci_state_key: 'hosts/state' }), 'ci/backend.tf'), + /key\s+= "hosts\/state"/, + ); +}); + +test('a bucket without its endpoint or its region is refused, each named; no bucket asks for neither', async () => { + const noEndpoint = await render({ ...BUCKET, ci_state_endpoint: '' }); + assert.match(JSON.stringify(noEndpoint.errors), /ci_state_endpoint/); + const noRegion = await render({ ...BUCKET, ci_state_region: '' }); + assert.match(JSON.stringify(noRegion.errors), /ci_state_region/); + const none = await render({ ci_strategy: 'byom' }); + assert.deepEqual(none.errors, []); + assert.equal(none.answers.ci_state_bucket, ''); +}); + +test('an update leaves a backend the tenant wrote by hand, whatever the next version renders, and a repo that deleted it stays without', async () => { + const mine = { bytes: new TextEncoder().encode('terraform {\n backend "http" {}\n}\n'), mode: 0o100644 }; + const noMerge = async () => { + throw new Error('no file of these merges is merged by content'); + }; + for (const answers of [{ ci_strategy: 'byom' }, BUCKET]) { + const [old, next] = [await render({ ci_strategy: 'byom' }), await render(answers)]; + const current = new Map(old.tree).set('ci/backend.tf', mine); + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.deepEqual(merged.tree.get('ci/backend.tf')?.bytes, mine.bytes, JSON.stringify(answers)); + // Left alone where the two renders agree, kept where they differ; never conflicted, clean or deleted. + for (const entry of merged.report.filter((e) => e.path === 'ci/backend.tf')) assert.equal(entry.outcome, 'kept'); + assert.equal(merged.report.filter((e) => e.path === 'ci/backend.tf').length, answers === BUCKET ? 1 : 0); + const without = new Map(old.tree); + without.delete('ci/backend.tf'); + const gone = await merge( + { old: old.tree, new: next.tree, current: without, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.equal(gone.tree.has('ci/backend.tf'), false, 'a deleted backend stays deleted'); + } +}); + +test('the s3 backend locks its state, and the header says what to edit where the store differs', async () => { + const backend = textOf(await render(BUCKET), 'ci/backend.tf'); + assert.match(backend, /use_lockfile\s+= true/); + const header = backend.split('\n').filter((line) => line.startsWith('#')); + assert.ok(header.length <= 6, 'the header stays short'); + const text = header.join('\n'); + assert.match(text, /conditional writes[^\n]*use_lockfile|use_lockfile[^\n]*conditional writes/); + assert.match(text, /use_path_style/); + assert.match(text, /skip_s3_checksum/); + assert.match(text, /AWS_REQUEST_CHECKSUM_CALCULATION/); + assert.match(text, /AWS_RESPONSE_CHECKSUM_VALIDATION/); + terraformHolds(backend); +}); + +test('the free text of the state is refused where it would break the file, each answer named, and an empty answer where no bucket is named is no error', async () => { + for (const [question, value] of [ + ['ci_state_bucket', 'a"b'], + ['ci_state_bucket', 'a${b}'], + ['ci_state_region', 'eu"one'], + ['ci_state_region', '${x}'], + ['ci_state_key', 'k"x'], + ['ci_state_key', 'k${path.module}'], + ['ci_state_endpoint', 's3.storage.example.test'], + ['ci_state_endpoint', 'ftp://s3.storage.example.test'], + ['ci_state_endpoint', 'https://s3.example.test/"x'], + ['ci_state_endpoint', 'https://s3.example.test/${x}'], + ] as const) + assert.match( + JSON.stringify((await render({ ...BUCKET, [question]: value })).errors), + new RegExp(question), + `${question}=${value}`, + ); + assert.deepEqual((await render({ ...BUCKET, ci_state_endpoint: 'http://127.0.0.1:9000' })).errors, []); + for (const answers of [ + { ci_strategy: 'byom', ci_state_endpoint: '', ci_state_region: '', ci_state_key: '' }, + { ci_state_bucket: '', ci_state_endpoint: '', ci_state_region: '' }, + ]) { + const result = await render(answers); + assert.deepEqual(result.errors, [], JSON.stringify(answers)); + } +}); + +test('the help of the state’s questions says the tenant fills in the vault item, and cites no planning document', () => { + const part = TEMPLATE.slice(TEMPLATE.indexOf('ci_state_bucket:'), TEMPLATE.indexOf('housekeeping:')); + assert.match(part, /vault item/); + assert.doesNotMatch(part, /§ 7\.14|pointers[^\n]*fills in/); +}); + +test('an update from the version where backend.tf was a plain file keeps it in each of its three states, and gives a bucket answer only its pointers', async () => { + const before = mkdtempSync(join(tmpdir(), 'plx-255-before-')); + try { + const root = templatesBefore(before, CURRENT, PLAIN_BACKEND); + const noMerge = async () => { + throw new Error('no file of these merges is merged by content'); + }; + const old = renderAt([await readTree(join(root, 'repo-operations'))], { tenant: 'acme', ci_strategy: 'byom' }); + assert.deepEqual(old.errors, []); + const mine = { bytes: new TextEncoder().encode('terraform {\n backend "http" {}\n}\n'), mode: 0o100644 }; + const hand = new Map(old.tree).set('ci/backend.tf', mine); + const gone = new Map(old.tree); + gone.delete('ci/backend.tf'); + for (const answers of [{ ci_strategy: 'byom' }, BUCKET]) { + const next = await render(answers); + for (const [state, current] of [ + ['untouched', old.tree], + ['hand-written', hand], + ['deleted', gone], + ] as const) { + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + noMerge, + ); + const shape = `${state} ${JSON.stringify(answers)}`; + assert.deepEqual(merged.tree.get('ci/backend.tf')?.bytes, current.get('ci/backend.tf')?.bytes, shape); + const secrets = new TextDecoder().decode(merged.tree.get('ci/secrets.env')?.bytes); + assert.equal( + /^AWS_ACCESS_KEY_ID=op:\/\/acme\/bucket-ci-state\/access-key-id$/m.test(secrets), + answers === BUCKET, + shape, + ); + assert.equal( + /^AWS_SECRET_ACCESS_KEY=op:\/\/acme\/bucket-ci-state\/secret-access-key$/m.test(secrets), + answers === BUCKET, + shape, + ); + assert.equal( + merged.report.some((e) => e.path === 'ci/backend.tf' && e.outcome !== 'kept'), + false, + shape, + ); + assert.equal( + merged.report.some((e) => e.outcome === 'conflicted'), + false, + shape, + ); + } + } + } finally { + rmSync(before, { recursive: true, force: true }); + } +}); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 17d7c782..fdda8737 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -446,6 +446,40 @@ test('in a job, a trusted server without the trusted token fails build, e2e and } }); +test('in a job where plx-ci setup found no trusted server that answers, build, e2e and publish use the job’s local cache, need no token, and say so in one line', async () => { + const dir = checkout(REMOTE); + // setup hands the job PLX_TURBO_TRUSTED=local, over a slot's own address and the cache host alike. + for (const named of [{}, HOST(), { ...HOST(), PLX_TURBO_TRUSTED: answering }]) + for (const tokens of [{}, TOKENS]) { + const ran = await turbowIn(dir, 'trusted', { ...STRAY, ...JOB, ...named, ...tokens, PLX_TURBO_TRUSTED: 'local' }); + const label = `${JSON.stringify(named)} ${JSON.stringify(tokens)}`; + assert.equal(ran.status, 0, `${label}\n${ran.said.join('\n')}`); + assert.deepEqual(ran.turbo?.env, uncached('local:rw'), label); + assert.deepEqual(ran.turbo?.args, ARGS); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /^turbow: without a remote cache: plx-ci setup .*the job's local cache/, label); + } +}); + +test('PLX_TURBO_TRUSTED=local changes nothing for check and test in a job, nor for any verb outside one', async () => { + const dir = checkout(REMOTE); + for (const [where, cache] of [ + [JOB, 'shared'], + [{}, 'shared'], + [{}, 'trusted'], + ] as const) { + const ran = await turbowIn(dir, cache, { ...where, ...HOST(), ...TOKENS, PLX_TURBO_TRUSTED: 'local' }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, { + TURBO_API: hostShared(), + TURBO_TEAM: 'acme-web', + TURBO_TEAMID: '', + TURBO_TOKEN: SHARED_TOKEN, + TURBO_CACHE: 'local:rw,remote:rw', + }); + } +}); + test('CI alone is no job: build and e2e on a machine with CI=true use the shared server, and need no trusted token', async () => { const dir = checkout(REMOTE); for (const ci of ['true', '1', 'yes']) { diff --git a/packages/lib/src/sync.test.ts b/packages/lib/src/sync.test.ts index 02fa914c..0b5bd830 100644 --- a/packages/lib/src/sync.test.ts +++ b/packages/lib/src/sync.test.ts @@ -3,12 +3,16 @@ // written into the root marker with the defaults. `apply`'s use of it is // tested through `apply` (apply.test.ts). import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { after, test } from 'node:test'; import { type Answers, readTree, render } from '@plexus-ms/cli-template'; import { planSync, type Source } from './index.ts'; -import { resolvedAnswers } from './sync.ts'; -import { quietContext, repoWith, scratchDir, templatesAt, text } from './testing/siteRepo.ts'; +import { type RenderTemplates, resolvedAnswers, type Templates } from './sync.ts'; +import { templatesRoot } from './templatesRoot.ts'; +import { CURRENT, REUSED, templatesBefore } from './testing/before.ts'; +import { renderAt } from './testing/bundled.ts'; +import { git, quietContext, repoWith, scratchDir, templatesAt, text, write } from './testing/siteRepo.ts'; const scratch = scratchDir('sync'); after(scratch.remove); @@ -198,6 +202,139 @@ test('planSync names the paths a version drops that the user edited, which are k assert.deepEqual(plan.dropped, { '.': ['old.txt'] }, 'the edited file the version drops, not the text conflict'); }); +/** A template whose next version starts to pin a tool, at the end of its tools. */ +const TOOLS = (tools: string) => ({ + manifest: 'name: tools\n', + files: { 'mise.toml': `[tools]\nnode = "24"\nhk = "latest"\n${tools}\n[tasks.check]\nrun = "true"\n` }, +}); + +test('planSync conflicts where the merge would leave a TOML file with a key that a repo already has twice', async () => { + const old = templatesAt(scratch.fresh('v1'), { tools: TOOLS('') }); + const next = templatesAt(scratch.fresh('v2'), { tools: TOOLS('terraform = "1"\n') }); + const repo = repoWith(scratch.fresh('repo'), { + 'PLEXUS.md': marker('version: 0.1.0\ntemplates: [tools]\n'), + 'mise.toml': '[tools]\nnode = "24"\nterraform = "1.9.0" # ours\nhk = "latest"\n\n[tasks.check]\nrun = "true"\n', + }); + const tools: Source = { templates: ['tools'], answers: {} }; + const plan = await planSync(quietContext(), repo, { old: { root: old }, new: { root: next } }, [ + { dir: '.', old: tools, new: tools }, + ]); + await plan.perform(); + assert.deepEqual(plan.sites[0]?.report, [{ path: 'mise.toml', outcome: 'conflicted' }], text(repo, 'mise.toml')); + assert.equal(plan.conflicted, 1); + assert.equal( + text(repo, 'mise.toml'), + [ + '[tools]', + 'node = "24"', + 'terraform = "1.9.0" # ours', + 'hk = "latest"', + '<<<<<<< current', + '=======', + 'terraform = "1"', + '>>>>>>> new render', + '', + '[tasks.check]', + 'run = "true"', + '', + ].join('\n'), + "the template's line between markers, the repo's own where it was", + ); +}); + +/** The templates below `root` rendered as a version's plx renders them, with the variables of this workspace's version. */ +const renderFrom = + (root: string, version = CURRENT): RenderTemplates => + async (names, answers) => { + const result = renderAt(await Promise.all(names.map((n) => readTree(join(root, n)))), answers, version); + return { + rendered: { tree: result.tree, policies: result.files, answers: result.answers }, + errors: result.errors.map((e) => e.message), + }; + }; + +test('planSync conflicts in mise.toml where repo-operations starts to pin terraform after 0.134.1 and the repo pins it already', async () => { + const into = scratch.fresh('before'); + mkdirSync(into); + const before = templatesBefore(into, CURRENT, REUSED); + const answers = { tenant: 'acme', ci_strategy: 'on-prem' }; + const old = await renderFrom(before)(['repo-operations'], answers); + assert.deepEqual(old.errors, []); + const files = Object.fromEntries( + [...(old.rendered?.tree ?? [])].map(([path, entry]) => [path, Buffer.from(entry.bytes).toString()]), + ); + const ours = 'terraform = "1.9.8" # ours'; + files['mise.toml'] = files['mise.toml']?.replace('node = "24"\n', `node = "24"\n${ours}\n`) ?? ''; + assert.ok(files['mise.toml'].includes(ours)); + files['PLEXUS.md'] = marker( + `version: ${CURRENT}\ntemplates: [repo-operations]\ntenant: acme\nci_strategy: on-prem\n`, + ); + const repo = repoWith(scratch.fresh('repo'), files); + const site: Source = { templates: ['repo-operations'], answers }; + const plan = await planSync( + quietContext(), + repo, + { + old: { root: before, render: renderFrom(before) }, + new: { root: templatesRoot(), render: renderFrom(templatesRoot()) }, + }, + [{ dir: '.', old: site, new: site }], + ); + await plan.perform(); + const mise = text(repo, 'mise.toml'); + assert.deepEqual( + plan.sites[0]?.report.filter((e) => e.path === 'mise.toml'), + [{ path: 'mise.toml', outcome: 'conflicted' }], + mise, + ); + const [outside, between] = mise + .split(/^<<<<<<< current\n|^>>>>>>> new render\n/m) + .reduce<[string, string]>(([o, b], part, i) => (i % 2 === 0 ? [o + part, b] : [o, b + part]), ['', '']); + assert.deepEqual(outside.match(/^terraform = .*$/gm), [ours], "the repo's own pin, once, outside the markers"); + assert.match( + between, + /^=======\n(?:.*\n)*terraform = /m, + "the template's pin between them, on the new render's side", + ); +}); + +test('a repo that kept its own terraform line at the crossing after 0.134.1 takes the next version with mise.toml clean', async () => { + const into = scratch.fresh('before'); + mkdirSync(into); + // The pins of 0.134.1 left as they were, so that the crossing moves them as a real one does. + const before = templatesBefore(into, REUSED, REUSED); + const answers = { tenant: 'acme', ci_strategy: 'on-prem' }; + const old = await renderFrom(before)(['repo-operations'], answers); + const files = Object.fromEntries( + [...(old.rendered?.tree ?? [])].map(([path, entry]) => [path, Buffer.from(entry.bytes).toString()]), + ); + const ours = 'terraform = "1.9.8" # ours'; + files['mise.toml'] = files['mise.toml']?.replace('node = "24"\n', `node = "24"\n${ours}\n`) ?? ''; + files['PLEXUS.md'] = marker(`version: ${REUSED}\ntemplates: [repo-operations]\ntenant: acme\nci_strategy: on-prem\n`); + const repo = repoWith(scratch.fresh('repo'), files); + const site: Source = { templates: ['repo-operations'], answers }; + const cross = async (from: Templates, to: Templates) => { + const plan = await planSync(quietContext(), repo, { old: from, new: to }, [{ dir: '.', old: site, new: site }]); + await plan.perform(); + return plan.sites[0]?.report.find((e) => e.path === 'mise.toml')?.outcome; + }; + const here = { root: templatesRoot(), render: renderFrom(templatesRoot()) }; + assert.equal(await cross({ root: before, render: renderFrom(before) }, here), 'conflicted'); + // Resolved as a person who keeps the repo's own pin does: the new render's side, without the template's terraform. + const resolved = text(repo, 'mise.toml') + .replace(/^<<<<<<< current\n(?:.*\n)*?=======\n((?:.*\n)*?)>>>>>>> new render\n/gm, '$1') + .replace(/^terraform = (?!"1\.9\.8").*\n/m, ''); + assert.deepEqual(resolved.match(/^terraform = .*$/gm), [ours]); + write(repo, { 'mise.toml': resolved }); + git(repo, 'commit', '-qam', 'resolved'); + const next = { root: templatesRoot(), render: renderFrom(templatesRoot(), '0.999.0') }; + const outcome = await cross(here, next); + const mise = text(repo, 'mise.toml'); + assert.equal(outcome, 'clean', mise); + assert.match(mise, /^"npm:@plexus-ms\/cli" = \{ version = "0\.999\.0"/m); + assert.deepEqual(mise.match(/^terraform = .*$/gm), [ours]); +}); + test('planSync renders each side with the variables its templates carry, in this process', async () => { const stamped = { manifest: ['name: basket', 'questions:', ' fruit:', ' type: str', ''].join('\n'), diff --git a/packages/lib/src/sync.ts b/packages/lib/src/sync.ts index c42ce820..f0b1e95d 100644 --- a/packages/lib/src/sync.ts +++ b/packages/lib/src/sync.ts @@ -45,6 +45,9 @@ // template asks any more, update.ts) are taken out in the same splice // (`removeMarkerKeys`), which leaves every other byte as it was. // +// Each site's merge holds its files to `readable` (mergeCheck.ts): a merge +// that leaves a TOML file with a key twice is a conflict at the template's line. +// // Performing a plan writes the merges, each site's in turn, then the markers. // A conflicted path is left in the file between the engine's markers, or kept // as it is where the template removed a file the user edited; either way the @@ -66,6 +69,7 @@ import type { Context } from './context.ts'; import { type Plan, write } from './effects.ts'; import { engine } from './engine.ts'; import { MARKER_FILE, removeMarkerKeys, setMarkerKeys } from './marker.ts'; +import { readable } from './mergeCheck.ts'; /** Templates, by name below a root, and the answers to render them with. */ export interface Source { @@ -259,7 +263,7 @@ export async function planSync( markers.push(write(path, removeMarkerKeys(setMarkerKeys(await ctx.readFile(path), keys), removed))); } if (contextOnly) continue; - const plan = await planMerge(join(repo, dir), entry.old, entry.new); + const plan = await planMerge(join(repo, dir), entry.old, entry.new, readable); merges.push({ dir, plan }); planned.push({ dir, report: plan.report, defaults }); dropped[dir] = plan.report diff --git a/packages/lib/src/testing/before.ts b/packages/lib/src/testing/before.ts index 2e112519..ae7ecb93 100644 --- a/packages/lib/src/testing/before.ts +++ b/packages/lib/src/testing/before.ts @@ -8,6 +8,8 @@ // 0.134.1 repo-turbo, repo-operations and updates of the last version whose // app repos called the reusable workflows of tooling for their // pipeline, and whose templates knew the strategy `hybrid` +// 0.135.0 repo-operations of the last version whose ci/backend.tf was a +// plain file and not a template // // Each holds those directories of the commit the version is tagged on, made in // this repository with @@ -16,6 +18,8 @@ // 0.132.0 templates/repo-turbo templates/repo-operations // git archive --format=tar.gz -o packages/lib/src/testing/templates-0.134.1.tar.gz \ // 0.134.1 templates/repo-turbo templates/repo-operations templates/updates +// git archive --format=tar.gz -o packages/lib/src/testing/templates-0.135.0.tar.gz \ +// 0.135.0 templates/repo-operations // // which makes the same bytes again with the same git; `gunzip -c` of it piped // to `git get-tar-commit-id` names the commit. It is an archive and not a tree @@ -37,6 +41,9 @@ export const BEFORE = '0.132.0'; /** The version of the archive of the last pipeline of reusable workflows. */ export const REUSED = '0.134.1'; +/** The version of the archive of the last operations template whose backend.tf was a plain file. */ +export const PLAIN_BACKEND = '0.135.0'; + /** The version of this workspace's packages, which is the Plexus version the templates of this checkout render at. */ export const CURRENT: string = (createRequire(import.meta.url)('../../package.json') as { version: string }).version; diff --git a/packages/lib/src/testing/templates-0.135.0.tar.gz b/packages/lib/src/testing/templates-0.135.0.tar.gz new file mode 100644 index 00000000..29a99b61 Binary files /dev/null and b/packages/lib/src/testing/templates-0.135.0.tar.gz differ diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index e041be74..d51368a5 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -45,10 +45,13 @@ // fails the run, which pushes nothing. // 2. The two renders are merged into each site by the engine's rules // (sync.ts): a local edit merges, a conflict stays in the file between -// `<<<<<<< current` and `>>>>>>> new render`, a file the version drops and -// the user edited is kept without markers, named by the commit and the -// pull request since nothing in the file shows it, and a born-once file -// the old render holds stays as the user left it. The defaults of +// `<<<<<<< current` and `>>>>>>> new render`, a merge that leaves a +// TOML file unreadable (a key the template starts to render that the repo +// has already, mergeCheck.ts) is such a conflict at the template's line, +// a file the version drops and the user edited is kept without markers, +// named by the commit and the pull request since nothing in the file +// shows it, and a born-once file the old render holds stays as the user +// left it. The defaults of // questions that became applicable and the new `version` are spliced // into the markers, and the answers no template asks any more taken out // of them, in one write each; the commit names each default it set, a diff --git a/packages/lib/turbo.json b/packages/lib/turbo.json index 0f0696d1..f3f8f5f2 100644 --- a/packages/lib/turbo.json +++ b/packages/lib/turbo.json @@ -2,7 +2,7 @@ "extends": ["//"], "tasks": { "test": { - "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**"] + "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**", "../../terraform/**"] } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9d2d59ee..15f423cc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -290,6 +290,9 @@ importers: semver: specifier: ^7.8.6 version: 7.8.6 + smol-toml: + specifier: ^1.9.1 + version: 1.9.1 yaml: specifier: ^2.9.1 version: 2.9.1 @@ -752,6 +755,10 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} + smol-toml@1.9.1: + resolution: {integrity: sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==} + engines: {node: '>= 18'} + turbo@2.11.13: resolution: {integrity: sha512-2EZ8StW6tqaj71HGF60oUOmJrPQHidmZ5dcwv2VORofya9JthVrfZhxbzRMx/QxjPwYi754i2h5RFsZSDzpnaQ==} hasBin: true @@ -1096,6 +1103,8 @@ snapshots: signal-exit@4.1.0: {} + smol-toml@1.9.1: {} + turbo@2.11.13: optionalDependencies: '@turbo/darwin-64': 2.11.13 diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index 3e8e491f..9a2a2533 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -13,15 +13,15 @@ hk = "latest" python = "3.14" uv = "latest" ansible = { version = "latest", uvx = true } +{%- if ci_jobs_strategy == 'byom' %} +terraform = "1" # the runner hosts' root, ci/ +{%- endif %} # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "{{ _plexus_version }}", allow_low_downloads = true } {%- if housekeeping %} "npm:@plexus-ms/cli-ci" = { version = "{{ _plexus_version }}", allow_low_downloads = true } {%- endif %} -{%- if ci_jobs_strategy == 'byom' %} -terraform = "1.17.2" # the runner hosts' root, ci/ -{%- endif %} [hooks] # hk is absent on a CI runner whose mise installs only the tools a job names. diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf deleted file mode 100644 index 9e7d35e9..00000000 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf +++ /dev/null @@ -1,7 +0,0 @@ -# Born from plexus-ms/tooling, templates/repo-operations, and the tenant's: plx update never changes it. The state is the only record of which hosts exist, so a lost one leaves billed machines nobody manages: keep it somewhere durable and private, and replace this local backend with that place. -# It holds a hash of each host's user-data, not the bootstrap token; a saved plan file (plan -out) holds the token in clear, so keep none. Commit .terraform.lock.hcl, which init writes. -terraform { - backend "local" { - path = "terraform.tfstate" - } -} diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf.jinja new file mode 100644 index 00000000..7213c272 --- /dev/null +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf.jinja @@ -0,0 +1,28 @@ +# Born from plexus-ms/tooling, templates/repo-operations, and the tenant's: plx update never changes it. The state is the only record of which hosts exist, so a lost one leaves billed machines nobody manages and a second developer sees none of them: keep it somewhere durable and private. +# It holds a hash of each host's user-data, not the bootstrap token; a saved plan file (plan -out) holds the token in clear, so keep none. Commit .terraform.lock.hcl, which init writes. +{%- if ci_state_bucket %} +# The bucket's keys come from secrets.env through terraformw. use_lockfile needs a store with conditional writes: remove it where there are none. For a store that wants virtual-hosted URLs set use_path_style = false; for one that refuses checksums add skip_s3_checksum = true and export AWS_REQUEST_CHECKSUM_CALCULATION=when_required and AWS_RESPONSE_CHECKSUM_VALIDATION=when_required. +terraform { + backend "s3" { + bucket = "{{ ci_state_bucket }}" + key = "{{ ci_state_key }}" + region = "{{ ci_state_region }}" + + endpoints = { s3 = "{{ ci_state_endpoint }}" } + + use_path_style = true + skip_credentials_validation = true + skip_region_validation = true + skip_requesting_account_id = true + skip_metadata_api_check = true + use_lockfile = true + } +} +{%- else %} +# This backend is local, the state on one disk. To keep it in a bucket instead, answer ci_state_bucket, ci_state_endpoint and ci_state_region in a render of this template, copy its backend block over this one, and run `terraform init -migrate-state`. +terraform { + backend "local" { + path = "terraform.tfstate" + } +} +{%- endif %} diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars index c5d6cab5..98469506 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars @@ -1,5 +1,5 @@ # Born from plexus-ms/tooling, templates/repo-operations, and the tenant's: plx update never changes it. The runner hosts that exist, and the tenant's usual values. -# A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. Leaving byom removes the root's other files but not this file, the state or the hosts: destroy them first. +# A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. Leaving byom removes the root's other files but not this file, the state or the hosts: destroy them first. defaults = { slots = { repo = { count = 2, memory = "4g" } @@ -13,6 +13,8 @@ defaults = { # The people who administer a host, [{ name, ssh_keys }], and the names of the project's SSH keys that open it until the first run. iam_admins = [] ssh_keys = [] + # A 1Password Connect server of the host's own, which its slots read the CI vault through: every slot of the host, repo and delivery, then holds a token that reads the whole vault, the deploy key included. Whether one set of Connect credentials serves several hosts at once is untried. Its credentials are the item 1password-connect of the vault -ci-host. + connect_server = false } # A host is its name and what it sets differently from the defaults: hosts = { "ci-1" = {}, "ci-2" = { location = "nbg1" } } diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja index 95f7ade0..c8d9e184 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja @@ -1,5 +1,5 @@ # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. +# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. A host mails the tenant through the relay of the item mail-relay in the vault {{ github_org }}-ci-host; plexus.ci's playbooks/vars/vault.yml states its fields. terraform { required_providers { hcloud = { @@ -13,7 +13,7 @@ provider "hcloud" {} locals { # Each host's own values over the tenant's usual ones. - settings = { for name, host in var.hosts : name => merge(var.defaults, host) } + settings = { for name, host in var.hosts : name => merge(local.fallbacks, var.defaults, host) } } module "runner_host" { @@ -30,6 +30,7 @@ module "runner_host" { location = local.settings[each.key].location ssh_source_ips = local.settings[each.key].ssh_source_ips turbo_cache_overlay = local.settings[each.key].turbo_cache_overlay + connect_server = local.settings[each.key].connect_server overlay_management_url = local.settings[each.key].overlay_management_url iam_admins = local.settings[each.key].iam_admins ssh_keys = local.settings[each.key].ssh_keys diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/secrets.env.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/secrets.env.jinja index 724fc790..529f9a7d 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/secrets.env.jinja +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/secrets.env.jinja @@ -1,4 +1,8 @@ # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# The pointers terraformw resolves for Terraform's environment: the provider's token and the bootstrap token, the service account token of the vault {{ github_org }}-ci-host. +# The pointers terraformw resolves for Terraform's environment: the provider's token and the bootstrap token, the service account token of the vault {{ github_org }}-ci-host{% if ci_state_bucket %}, and the keys of the bucket that keeps the state{% endif %}. HCLOUD_TOKEN=op://{{ tenant }}/hcloud/credential TF_VAR_op_service_account_token=op://{{ tenant }}/ci-host/credential +{%- if ci_state_bucket %} +AWS_ACCESS_KEY_ID=op://{{ tenant }}/bucket-ci-state/access-key-id +AWS_SECRET_ACCESS_KEY=op://{{ tenant }}/bucket-ci-state/secret-access-key +{%- endif %} diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf index cecbddfe..e895fa0f 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf @@ -8,11 +8,14 @@ variable "op_service_account_token" { locals { # The attributes of a host, each the module's input of the same name; the module checks their types. - attributes = ["slots", "server_type", "location", "ssh_source_ips", "turbo_cache_overlay", "overlay_management_url", "iam_admins", "ssh_keys"] + attributes = ["slots", "server_type", "location", "ssh_source_ips", "turbo_cache_overlay", "connect_server", "overlay_management_url", "iam_admins", "ssh_keys"] + + # What a hosts file that lacks an attribute means by it: an attribute may get a fallback only where its fallback leaves the user-data of the hosts that exist byte for byte as it was, so that taking a version replaces none of them. A file born before the attribute existed then plans as it is; every other attribute must be in defaults. + fallbacks = { connect_server = false } } variable "defaults" { - description = "The tenant's usual values, taken by a host that names none of its own: every attribute, and no other key, and none null." + description = "The tenant's usual values, taken by a host that names none of its own: every attribute but those with a fallback, and no other key, and none null. connect_server turns on a 1Password Connect server of the host's own: every slot of the host, repo and delivery, then reads the whole CI vault through it, the deploy key included, and whether one set of Connect credentials serves several hosts at once is untried." type = any validation { @@ -21,8 +24,8 @@ variable "defaults" { } validation { - condition = can(keys(var.defaults)) ? length(setsubtract(keys(var.defaults), local.attributes)) == 0 && length(setsubtract(local.attributes, keys(var.defaults))) == 0 : true - error_message = "defaults holds exactly the attributes ${join(", ", local.attributes)}; unknown: [${join(", ", try(setsubtract(keys(var.defaults), local.attributes), []))}], missing: [${join(", ", try(setsubtract(local.attributes, keys(var.defaults)), []))}]." + condition = can(keys(var.defaults)) ? length(setsubtract(keys(var.defaults), local.attributes)) == 0 && length(setsubtract(setsubtract(local.attributes, keys(local.fallbacks)), keys(var.defaults))) == 0 : true + error_message = "defaults holds exactly the attributes ${join(", ", local.attributes)}; unknown: [${join(", ", try(setsubtract(keys(var.defaults), local.attributes), []))}], missing: [${join(", ", try(setsubtract(setsubtract(local.attributes, keys(local.fallbacks)), keys(var.defaults)), []))}]." } validation { diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 839910f5..0488665a 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -48,6 +48,49 @@ questions: - netbird default: none + # Where the state of ci/ is kept: the only record of which runner hosts exist. An S3-compatible store of the tenant's + # choice, so no provider is assumed and the endpoint and the region have no default. The answers write ci/backend.tf + # once, at birth; the file is the tenant's after it (born-once), so a later answer changes nothing in it. Each + # validator is guarded by the bucket: it runs on a given answer even where the question is skipped. + ci_state_bucket: + type: str + help: "The bucket that keeps the state of the Terraform root ci/ (an S3-compatible store: its name; empty: the state stays on the disk of whoever runs Terraform, which loses the record of the runner hosts with it). Its keys are read from the vault item bucket-ci-state, fields access-key-id and secret-access-key, which the tenant creates" + default: "" + when: "{{ ci_jobs_strategy == 'byom' }}" + validator: >- + {% if ci_state_bucket and ('"' in ci_state_bucket or '${' in ci_state_bucket or '%{' in ci_state_bucket or + '\\' in ci_state_bucket) %}A bucket name without quote, backslash, dollar-brace or percent-brace{% endif %} + + ci_state_endpoint: + type: str + help: "The S3 endpoint of the bucket, a URL starting with http:// or https:// (the tenant's store, none assumed)" + default: "" + when: "{{ ci_jobs_strategy == 'byom' and ci_state_bucket != '' }}" + validator: >- + {% if ci_state_bucket %}{% if not (ci_state_endpoint.startswith('http://') or + ci_state_endpoint.startswith('https://')) %}is needed where a bucket is named, a URL starting with http:// or + https://{% elif '"' in ci_state_endpoint or '${' in ci_state_endpoint or '%{' in ci_state_endpoint or '\\' in + ci_state_endpoint %}without quote, backslash, dollar-brace or percent-brace{% endif %}{% endif %} + + ci_state_region: + type: str + help: "The region of the bucket as its store names it (the s3 backend needs one; a store without regions takes any name it accepts)" + default: "" + when: "{{ ci_jobs_strategy == 'byom' and ci_state_bucket != '' }}" + validator: >- + {% if ci_state_bucket %}{% if ci_state_region == '' %}is needed where a bucket is named{% elif '"' in + ci_state_region or '${' in ci_state_region or '%{' in ci_state_region or '\\' in ci_state_region %}without quote, + backslash, dollar-brace or percent-brace{% endif %}{% endif %} + + ci_state_key: + type: str + help: "The key of the state within the bucket; the default holds the tenant, so that the roots of two tenants in one bucket never meet" + default: "{{ tenant }}/ci/terraform.tfstate" + when: "{{ ci_jobs_strategy == 'byom' and ci_state_bucket != '' }}" + validator: >- + {% if ci_state_bucket and (ci_state_key == '' or '"' in ci_state_key or '${' in ci_state_key or '%{' in + ci_state_key or '\\' in ci_state_key) %}A key without quote, backslash, dollar-brace or percent-brace, not empty{% endif %} + # Stays for the transition of the consumers that have not migrated; the issues labelled Contraction track its # removal. housekeeping: @@ -66,7 +109,7 @@ policies: # its frontmatter is plx's. PLEXUS.md.jinja: born-once # The state's place and the hosts are the tenant's facts: created once, never re-synced, never deleted. - "{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf": born-once + "{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/backend.tf.jinja": born-once "{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars": born-once birth: 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 05e43ec7..116f0aee 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -106,6 +106,8 @@ jobs: # checkout, and installs plx and what it runs on from the versions named here. # The install step runs outside the checkout, whose file tasks mise would have to trust; the action puts no # tool directory of the runner image ahead of the shims, so the tools run are the ones installed here. + # On a runner host's slot the image's plx-ci is the one named here, so mise rebuilds the image's shims, which only + # root can write; the step has it write them into its own temp directory, which nothing runs from. env: MISE_IGNORED_CONFIG_PATHS: ${{ github.workspace }} steps: @@ -116,6 +118,8 @@ jobs: cache: false export_path: false - working-directory: ${{ runner.temp }} + 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 %}' - id: setup{% endraw %}{% if ci_service_account %}{% raw %} env: diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow index 66572c77..2c9ab7cb 100755 --- a/templates/repo-turbo/files/turbow +++ b/templates/repo-turbo/files/turbow @@ -20,13 +20,18 @@ unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_LOGIN TURBO_CACHE TURB # Which server (§ 8 PLX-Delivery): check and test call turbow with `shared`, build, e2e and publish with `trusted`. # In a job of the forge (GITHUB_ACTIONS=true, which the forge's runner sets and CI alone does not), a trusted verb uses -# the trusted server and never the local cache, which a shared run of this checkout may have filled, and a shared verb -# the shared server. Outside a job every verb uses the shared server: no machine but CI holds the trusted token. +# the trusted server and no local cache, and a shared verb the shared server. Outside a job every verb uses the shared +# server: no machine but CI holds the trusted token. # the shared server PLX_TURBO_SHARED, else http://:8585 # the trusted server PLX_TURBO_TRUSTED, else http://:8586 # their tokens PLX_TURBO_SHARED_TOKEN, PLX_TURBO_TRUSTED_TOKEN # PLX_TURBO_CACHE_HOST is the answer turbo_cache_host, which mise sets from mise.toml. A slot of a runner host names its # own host's servers in PLX_TURBO_SHARED and PLX_TURBO_TRUSTED, which come first. An empty variable names nothing. +# In a job, PLX_TURBO_TRUSTED=local is plx-ci setup's word that the job reaches no trusted server that answers: build, +# e2e and publish then share the local cache of the job's checkout and need no token, so that the step build builds +# each app once and e2e and publish replay that build, which the image is made from. Every build and e2e in that cache +# is the job's own: what the shared verbs put there before, from the shared bucket too, is an app repo's check and +# test, verdicts that build nothing and leave no files (§ 8 PLX-Delivery). Only an app repo's job runs setup. # # It runs without a remote cache, and says why in one line, where no server is named, where the shared token is # missing, where no node is on PATH to ask the server with, where the server refuses the token or does not answer @@ -44,6 +49,9 @@ fi reason= if [ -z "$server" ]; then reason="the repo names no cache host (turbo_cache_host), and the environment no $from server" +elif [ "$from" = trusted ] && [ "$server" = local ]; then + reason="plx-ci setup found no trusted server that answers, so build, e2e and publish share the job's local cache" + without=local:rw elif [ -z "$token" ] && [ "$from" = trusted ]; then echo "turbow: in a job of the forge, build, e2e and publish need a token for the trusted remote cache at $server, and this job has none (PLX_TURBO_TRUSTED_TOKEN is unset)" >&2 exit 1 diff --git a/terraform/ci_runner_host_user_data/main.tf b/terraform/ci_runner_host_user_data/main.tf index 55949897..32f057a7 100644 --- a/terraform/ci_runner_host_user_data/main.tf +++ b/terraform/ci_runner_host_user_data/main.tf @@ -14,8 +14,15 @@ # - installs the collections, then runs plexus.ci.playbook on the host. # # The role is the implementation: the playbook installs the vault's CLI and -# reads every other secret from the vault itself. The user-data states the -# host and holds no logic. +# reads every other secret from the vault itself, among them the credentials +# and the token of a Connect server (connect_server) and the tenant's mail +# relay, the item mail-relay, without which the host sends no mail and says +# so in its journal. The user-data states the host and holds no logic. +# +# A setting added after the module first shipped is written only where it +# differs from the role's default, so that taking it replaces no host: the +# overlay's management server and connect_server are in the values file when +# set and absent otherwise. The values from the start are always written. # # The output carries the one secret, so it is sensitive, and so is the state # or plan file of a caller that keeps it. The text is a function of the @@ -30,5 +37,8 @@ locals { turbo_cache_overlay = var.turbo_cache_overlay }, var.overlay_management_url == "" ? {} : { netbird_management_url = var.overlay_management_url }, + # Named only when on, so that the text of a host without a Connect server + # is what it always was: a changed user-data is a new machine. + var.connect_server ? { actions_runners_connect = true } : {}, ) } diff --git a/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl b/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl index 668722ae..67fb87c0 100644 --- a/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl +++ b/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl @@ -98,6 +98,61 @@ run "serves_the_caches_on_the_overlay" { } } +# A host that leaves the Connect server off is the host that exists today: a +# changed user-data replaces the machine, so its text is held byte for byte +# (the hash is of the text as it was before the variable existed). +run "leaves_the_text_of_a_host_without_connect_as_it_was" { + command = plan + + assert { + condition = nonsensitive(sha256(output.user_data)) == "f7d497a15b34bca2e302326db206b044efc5d0abe39fbe90d62657588326e19f" + error_message = "The user-data of a host with the Connect server off must not change by a byte, or taking a version replaces it." + } + + assert { + condition = !contains(keys(jsondecode([for f in yamldecode(output.user_data).write_files : f.content if f.path == "/etc/plexus-ci/values.yml"][0])), "actions_runners_connect") + error_message = "With the Connect server off the values file must leave the role's default alone." + } +} + +run "turns_the_connect_server_on_as_a_boolean" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = jsondecode([for f in yamldecode(output.user_data).write_files : f.content if f.path == "/etc/plexus-ci/values.yml"][0]).actions_runners_connect == true + error_message = "actions_runners_connect must be the boolean true: the playbook refuses a string." + } + + assert { + condition = output.user_data != run.is_cloud_config.user_data + error_message = "Turning the Connect server on must reach the user-data." + } +} + +# The credentials and the access token are read from the host's vault by the +# playbook: the user-data carries the one token and nothing of Connect's. +run "carries_no_credential_of_the_connect_server" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = [for f in yamldecode(output.user_data).write_files : f.path if strcontains(f.content, var.op_service_account_token)] == ["/etc/plexus-ci/token.env"] + error_message = "The token must still be in token.env and in no other file." + } + + assert { + condition = !strcontains(output.user_data, "op://") && !strcontains(output.user_data, "1password-credentials") && !strcontains(output.user_data, "OP_CONNECT") + error_message = "No pointer, credentials file or Connect token belongs in the user-data." + } +} + run "names_the_overlays_management_server_only_when_given" { command = plan diff --git a/terraform/ci_runner_host_user_data/variables.tf b/terraform/ci_runner_host_user_data/variables.tf index 0a535549..82ce2f44 100644 --- a/terraform/ci_runner_host_user_data/variables.tf +++ b/terraform/ci_runner_host_user_data/variables.tf @@ -54,6 +54,12 @@ variable "turbo_cache_overlay" { default = false } +variable "connect_server" { + description = "Whether the host runs a 1Password Connect server of its own, which its slots read the vault -ci through. The playbook reads the credentials and the token from the item 1password-connect of the vault -ci-host. With it, a slot's token reads everything the Connect server's vault holds, the deploy key too." + type = bool + default = false +} + variable "overlay_management_url" { description = "The overlay's management server, where it is not NetBird's own; empty leaves the role's default." type = string diff --git a/terraform/hcloud_ci_runner_host/main.tf b/terraform/hcloud_ci_runner_host/main.tf index 12926633..ac59a5a9 100644 --- a/terraform/hcloud_ci_runner_host/main.tf +++ b/terraform/hcloud_ci_runner_host/main.tf @@ -8,12 +8,18 @@ # plexus.ci at the Plexus version and runs plexus.ci.playbook on the machine # itself, with the slots and the owner as values and one secret, a service # account token for the vault -ci-host, from which the playbook reads -# the rest. The role is the implementation; the user-data holds no logic, and +# the rest, the credentials of the host's Connect server (connect_server) +# among them. The role is the implementation; the user-data holds no logic, and # is rendered by ../ci_runner_host_user_data, which a machine of another kind # can use alone. The user-data holds the token, so a plan file of the caller # does too, and the state keeps a hash of it: the module marks it sensitive, # which keeps it out of the plan's text, not out of the files. # +# The host mails the tenant through the relay that the vault's item +# mail-relay names; plexus.ci's playbooks/vars/vault.yml states its fields. +# Without the item a host is set up all the same, sends no mail, and says so +# in its journal; a host takes a new item only when it is replaced. +# # What the module creates: the machine, and a firewall attached to it at # creation. A runner host needs nothing inbound at the provider: the slots # poll the forge, and the cache servers listen on loopback and, with @@ -54,6 +60,7 @@ module "user_data" { plexus_version = var.plexus_version slots = var.slots turbo_cache_overlay = var.turbo_cache_overlay + connect_server = var.connect_server overlay_management_url = var.overlay_management_url iam_admins = var.iam_admins op_service_account_token = var.op_service_account_token diff --git a/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl b/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl index dd4e7e79..73a04564 100644 --- a/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl +++ b/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl @@ -204,6 +204,28 @@ run "passes_the_overlay_values_to_the_user_data" { } } +run "leaves_the_connect_server_out_of_the_user_data_when_off" { + command = plan + + assert { + condition = !strcontains(nonsensitive(hcloud_server.host.user_data), "actions_runners_connect") + error_message = "A host with the Connect server off must get the user-data it always got." + } +} + +run "passes_the_connect_server_on_to_the_user_data" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = strcontains(nonsensitive(hcloud_server.host.user_data), "\"actions_runners_connect\":true") + error_message = "connect_server must reach the playbook's values as actions_runners_connect." + } +} + # The keys and the image only matter when the machine is created: a later # change must not replace a machine that works. The machine of the first run # is the one the state holds. diff --git a/terraform/hcloud_ci_runner_host/variables.tf b/terraform/hcloud_ci_runner_host/variables.tf index 17fcf334..6372fbbc 100644 --- a/terraform/hcloud_ci_runner_host/variables.tf +++ b/terraform/hcloud_ci_runner_host/variables.tf @@ -24,6 +24,12 @@ variable "turbo_cache_overlay" { default = false } +variable "connect_server" { + description = "Whether the host runs a 1Password Connect server of its own, which its slots read the vault -ci through, so that their reads spend none of the service account's budget. The playbook reads the credentials and the token from the item 1password-connect of the vault -ci-host. With it, a slot's token reads everything the Connect server's vault holds, the deploy key too; whether one set of credentials serves several hosts at once is untried. A change replaces the machine." + type = bool + default = false +} + variable "overlay_management_url" { description = "The overlay's management server, where it is not NetBird's own; empty leaves the role's default." type = string