#!/bin/sh
# logpulse-agent-upgrade — the privileged half of the agent self-upgrade.
#
# Started as root by logpulse-agent-upgrade.service when the unprivileged agent
# drops /var/lib/logpulse-agent/upgrade.env. That file is written by the
# `logpulse` user, so nothing in it is trusted (ADR-0167, issue #3112):
#
#   - it is never sourced or used as a systemd EnvironmentFile; this script
#     takes one bounded read of it, without following a link, into a root-only
#     directory and looks at nothing but those bytes;
#   - the only thing taken from it is a version string, matched against a
#     strict pattern and refused when older than MIN_VERSION, so the agent
#     cannot ask for a release that still ships the vulnerable root unit;
#   - the installer runs with an empty environment plus a fixed PATH, the
#     validated version and LOGPULSE_UPGRADE=1, which pins the download host.
#
# Nothing that LogPulse did not sign runs here (ADR-0242). The helper downloads
# the release package and its signature, has the agent binary that is already
# installed (root-owned, with the release keys compiled in) check them, and
# then runs the installer from inside that package on that package. Neither
# the download host nor the control plane can swap in something else, and the
# control plane cannot ask for a release older than the one installed.
#
# `logpulse-agent-upgrade --parse FILE` only validates FILE and prints the
# version. The tests use it; it changes nothing on the host.
set -eu
umask 077
PATH=/usr/sbin:/usr/bin:/sbin:/bin
# One meaning for the character ranges in the version checks, whatever locale
# the unit was started with.
LC_ALL=C
export PATH LC_ALL

TRIGGER=/var/lib/logpulse-agent/upgrade.env
# Root-only (StateDirectory= of the unit, mode 0700). Only files this script
# makes itself live in here: the bytes read from the trigger, the downloaded
# package and the installer taken out of it.
WORK_DIR=/var/lib/logpulse-agent-upgrade
INSTALL_URL=https://get.logpulse.io
DOWNLOADS_BASE=https://dl.logpulse.io
AGENT_BIN=/opt/logpulse-agent/bin/logpulse-agent
# Exit code of `logpulse-agent verify-package` for a build without release keys.
NO_RELEASE_KEYS=10
MAX_PACKAGE_BYTES=314572800
# Oldest release this helper installs. Releases before v0.8.1 ship the root
# unit that loaded upgrade.env as an EnvironmentFile (#3112); releases before
# v0.9.8 ship an installer that, as root, ran `install -d -o logpulse` on
# entries of the agent-owned state dir and so followed a symlink the agent
# left there (security report 2026-11-20). Installing one would reopen that.
# Raise this whenever a release fixes a hole in this path.
MIN_VERSION=v0.9.8
MAX_TRIGGER_BYTES=64

err() { printf 'logpulse-agent-upgrade: %s\n' "$1" >&2; exit 1; }

# fetch FILE URL MAX_BYTES SECONDS: download URL to FILE over https (redirects
# included), at most MAX_BYTES and SECONDS. curl's --max-filesize only works
# when the server announces the size; the shell's file size limit holds either
# way, so the download host cannot fill /var before a signature is checked.
fetch() {
  (
    ulimit -f $(($3 / 512 + 1)) 2>/dev/null || true
    exec curl -q -fsSL --proto '=https' --tlsv1.2 --max-time "$4" \
      --max-filesize "$3" -o "$1" "$2"
  )
}

# The agent's own versions are vMAJOR.MINOR.PATCH[-pre] (the API checks the
# same shape). No leading zeros and at most nine digits, so the numbers are
# safe in $(( )) — a leading zero would be read as octal.
VERSION_RE='v(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})(-[A-Za-z0-9_.]+)?'

# version_core vX.Y.Z[-pre] → "X Y Z"
version_core() {
  core=${1#v}
  core=${core%%-*}
  printf '%s\n' "$core" | tr '.' ' '
}

# version_pre vX.Y.Z[-pre] → "pre", empty for a release.
version_pre() {
  case $1 in
    *-*) printf '%s\n' "${1#*-}" ;;
    *)   printf '\n' ;;
  esac
}

# version_not_older A B: true when A is B itself or a later release than B.
# With equal numbers a pre-release comes before its release (v0.9.8-rc1 is
# older than v0.9.8), and two different pre-releases of the same numbers have
# no order this script relies on: going from one to the other is refused, like
# going back. The installer run by hand can still do either.
version_not_older() {
  vno_a=$1
  vno_b=$2
  # shellcheck disable=SC2046 # word splitting into the three parts is the point
  set -- $(version_core "$vno_a") $(version_core "$vno_b")
  [ "$1" -ne "$4" ] && { [ "$1" -gt "$4" ]; return; }
  [ "$2" -ne "$5" ] && { [ "$2" -gt "$5" ]; return; }
  [ "$3" -ne "$6" ] && { [ "$3" -gt "$6" ]; return; }
  vno_pa=$(version_pre "$vno_a")
  vno_pb=$(version_pre "$vno_b")
  [ "$vno_pa" = "$vno_pb" ] || [ -z "$vno_pa" ]
}

# parse_trigger FILE: print the requested version, or fail. The file content is
# never echoed, not even in an error: it is attacker-controlled.
parse_trigger() {
  f=$1
  if [ -L "$f" ] || [ ! -f "$f" ]; then
    err "trigger is not a regular file"
  fi
  # One bounded read; everything below looks only at these bytes, so growing
  # the file afterwards (e.g. through a hard link) changes nothing.
  content=$(dd if="$f" bs=$((MAX_TRIGGER_BYTES + 1)) count=1 2>/dev/null) \
    || err "could not read trigger"
  [ "${#content}" -le "$MAX_TRIGGER_BYTES" ] || err "trigger is too long"
  nl='
'
  cr=$(printf '\r')
  case $content in
    *"$nl"* | *"$cr"*) err "trigger must be a single line" ;;
    LOGPULSE_VERSION=*) version=${content#LOGPULSE_VERSION=} ;;
    *) err "trigger does not start with LOGPULSE_VERSION=" ;;
  esac
  printf '%s\n' "$version" | grep -Eqx "$VERSION_RE" \
    || err "trigger holds no valid version"
  version_not_older "$version" "$MIN_VERSION" \
    || err "refusing a version older than $MIN_VERSION"
  printf '%s\n' "$version"
}

if [ "${1:-}" = "--parse" ]; then
  [ $# -eq 2 ] || err "usage: logpulse-agent-upgrade --parse FILE"
  parse_trigger "$2"
  exit 0
fi
[ $# -eq 0 ] || err "unexpected arguments"
[ "$(id -u)" -eq 0 ] || err "must run as root"

if [ ! -d "$WORK_DIR" ] || [ -L "$WORK_DIR" ]; then
  err "$WORK_DIR is missing"
fi
[ "$(stat -c '%u %a' "$WORK_DIR")" = "0 700" ] \
  || err "$WORK_DIR must be owned by root with mode 0700"

request="$WORK_DIR/upgrade.request"
installer="$WORK_DIR/install.sh"
package_dir="$WORK_DIR/package"
trap 'rm -rf "$request" "$installer" "$package_dir"' EXIT
rm -rf "$request" "$installer" "$package_dir"
# One bounded read of the trigger into root's own directory. The agent owns the
# directory the trigger is in, so whatever sits at that name is the agent's
# choice: iflag=nofollow refuses a symlink, nonblock does not wait on a FIFO, a
# directory cannot be read, and bs/count take at most one short block from a
# file of any size. Everything after this looks only at the copy.
#
# Nothing of the agent's is moved in here. Earlier versions of this helper
# renamed the trigger into this directory: with the state directory on another
# file system
# that rename is a copy of whatever size the agent chose, made by root, and a
# directory tree left as "trigger" ended up under the `rm -rf` above.
if ! dd if="$TRIGGER" of="$request" iflag=nofollow,nonblock \
  bs=$((MAX_TRIGGER_BYTES + 1)) count=1 2>/dev/null; then
  rm -f "$TRIGGER" 2>/dev/null || true
  err "no usable upgrade trigger at $TRIGGER"
fi
# Gone before anything else happens: rm removes the name, never what it points
# at, and leaves a directory where it is.
rm -f "$TRIGGER" 2>/dev/null || true

version=$(parse_trigger "$request")

# Never back to an older release from here: that would bring its holes back.
installed=$("$AGENT_BIN" version 2>/dev/null | sed -n '1s/^logpulse-agent //p') || installed=""
if printf '%s\n' "$installed" | grep -Eqx "$VERSION_RE"; then
  version_not_older "$version" "$installed" \
    || err "refusing to go back from $installed to $version; run the installer by hand for that"
fi
printf 'logpulse-agent-upgrade: installing %s\n' "$version"

# Does the installed agent hold release keys? It answers without reading a file.
set +e
"$AGENT_BIN" verify-package --check >/dev/null 2>&1
keys=$?
set -e

if [ "$keys" -eq "$NO_RELEASE_KEYS" ]; then
  # A build from before signing was switched on: the installer from the
  # download host, as before.
  printf 'logpulse-agent-upgrade: the installed agent holds no release key; package signature not checked\n' >&2
  fetch "$installer" "$INSTALL_URL" 1048576 120 \
    || err "could not download the installer from $INSTALL_URL"
  env -i PATH="$PATH" LOGPULSE_VERSION="$version" LOGPULSE_UPGRADE=1 \
    /bin/sh "$installer"
  exit 0
fi
[ "$keys" -eq 0 ] || err "the installed agent cannot check package signatures"

case "$(uname -m)" in
  x86_64|amd64)  arch=amd64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) err "unsupported architecture" ;;
esac
name="logpulse-agent_${version}_linux_${arch}.tar.gz"
mkdir "$package_dir"
fetch "$package_dir/$name" "$DOWNLOADS_BASE/$version/$name" "$MAX_PACKAGE_BYTES" 720 \
  || err "could not download $name"
fetch "$package_dir/$name.ed25519" "$DOWNLOADS_BASE/$version/$name.ed25519" 8192 60 \
  || err "no signature for $name; refusing to install"
"$AGENT_BIN" verify-package --file "$package_dir/$name" \
  --signature "$package_dir/$name.ed25519" --name "$name" \
  || err "signature check failed for $name; refusing to install"

# Only the installer is taken out here; it unpacks the rest itself.
mkdir "$package_dir/unpack"
tar --no-same-owner -xzf "$package_dir/$name" -C "$package_dir/unpack" ./libexec/install.sh 2>/dev/null \
  || err "$name holds no installer"
packaged="$package_dir/unpack/libexec/install.sh"
if [ ! -f "$packaged" ] || [ -L "$packaged" ]; then
  err "$name holds no installer"
fi
env -i PATH="$PATH" LOGPULSE_VERSION="$version" LOGPULSE_UPGRADE=1 \
  LOGPULSE_PACKAGE_FILE="$package_dir/$name" \
  /bin/sh "$packaged"
