#!/bin/sh
# Run `sdlc` with no `rev:` to pin: verify the image's signature, get the
# launcher from it, then run that.
#
# The launcher (bin/sdlc) ships inside quay.io/crunchtools/sdlc, so it floats
# with the image tag exactly as the tools in the image do: `:latest` by
# default, SDLC_IMAGE=main for what has merged and not been released, a
# release such as SDLC_IMAGE=0.9.0, or SDLC_IMAGE=@sha256:<digest>. Nothing
# else: this file runs whatever it pulls, so it pulls from that one repository.
# A seat trying a local build runs a python-sdlc clone's bin/sdlc instead. The
# image prints the launcher with its own ref written into it (`sdlc launcher
# <ref>`), so the launcher and the image it starts cannot disagree.
#
# A converted repo carries this file as .sdlc/bin/sdlc, and its hooks and its
# CI job run it (scripts/convert_repo.py writes it). Nothing in it names a
# release, so nothing ever bumps it, and the constitution pins its bytes. An
# `sdlc` RPM would install the same file as /usr/bin/sdlc.
#
# Host contract: podman and POSIX sh, nothing else. Never a pipe into `sh`: a
# failed pull would hand sh nothing, and nothing runs and exits 0. An image
# that cannot print its launcher is a 2 -- the gate could not run.
#
# Nothing from the image runs before its signature is checked (python-sdlc#81).
# The image decides every repo's required `sdlc ci` check, so a pushed tag is
# not enough: the digest the tag resolves to must carry a cosign signature by
# a key inlined below, so the file the gate trusts carries its own trust root.
# A release is signed by sdlc's own key; main, and the releases before 0.15.2,
# by the fleet key (see "Which key vouches" below). cosign runs from a digest-pinned image, as the host contract
# needs; podman's own sigstore policy would need a registries.d that podman
# cannot be pointed at without faking HOME, which moves its storage too. The
# launcher and every check then run by that digest, so a tag moving mid-run
# changes nothing. A digest verified once is remembered in the user's cache,
# so an offline seat keeps working on what it already verified. Unsigned is a
# 2, never a warning.

set -u

FLEET=quay.io/crunchtools/sdlc
refuse() {
  printf 'sdlc: GATE CANNOT RUN: SDLC_IMAGE=%s is not main, latest, X.Y.Z or @sha256:<64 hex> of %s\n' \
    "${SDLC_IMAGE:-}" "$FLEET" >&2
  exit 2
}
cannot() { printf 'sdlc: GATE CANNOT RUN: %s\n' "$*" >&2; exit 2; }

# The value, with the repository named in full or not at all.
want=${SDLC_IMAGE:-latest}
case $want in
  "$FLEET":*) want=${want#"$FLEET":} ;;
  "$FLEET"@*) want=${want#"$FLEET"} ;;
esac
case $want in
  main|latest) image=$FLEET:$want ;;
  @sha256:*)
    hex=${want#@sha256:}
    case $hex in *[!0-9a-f]*) refuse ;; esac
    [ "${#hex}" -eq 64 ] || refuse
    image=$FLEET$want ;;
  *[!0-9.]*|.*|*.|*..*|*.*.*.*) refuse ;;
  *.*.*) image=$FLEET:$want ;;
  *) refuse ;;
esac

# Two keys, each named in the cache path by its ID (the first 16 hex of the
# key's sha256), so a new key trusts nothing an old one verified; tests/test_bootstrap.sh
# checks each ID against its key.
#
# sdlc's own key: boot/keys/sdlc.pub, whose private half lives only in sdlc's
# sdlc-signing environment (scripts/self.sh's sign job). It signs every release
# from 0.15.2 on, and it is the only key sdlc-bootstrap trusts in CI.
SDLC_KEY_ID=06d55be78e4b1bac
# The fleet key: crunchtools/constitution keys/crunchtools-bootc.pub, whose
# private half promote signs with (ci.yml's promote job, via sdlc event). It
# still signs :main (container.yml) and signed the releases up to 0.15.1.
FLEET_KEY_ID=9c300eea7ce2867d
# cosign v2.6.5, the signer's version: v3 keeps signatures where podman and
# bootc cannot read them. The index digest, so every architecture gets it.
COSIGN=ghcr.io/sigstore/cosign/cosign@sha256:ad281047f85c5e1fc6ffbc30c2b55be3b07b4032bef715a12122ce5829619aca

dir=$(mktemp -d) || exit 2
trap 'rm -rf "$dir"' EXIT
trap 'exit 2' HUP INT TERM

cat > "$dir/sdlc.pub" <<'SDLC_KEY'
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIGts5za2uZSNyzQshbiqzKvyj0m0
aZrLhD5a78Iqn3JzcWT/Oqz0QDLHy40QgB9J4tn9Nj5LlTPBxng0j4NL+w==
-----END PUBLIC KEY-----
SDLC_KEY
cat > "$dir/fleet.pub" <<'FLEET_KEY'
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5TlIf0f5VMBaCLJGtmh9fL3C/xYM
nHVNg0KnBqqs/x+WThX8zEKaGmiZ2SM5336mPfJKZl68/lXBnoWlU0E9Tg==
-----END PUBLIC KEY-----
FLEET_KEY

# Which key vouches. A release (latest, X.Y.Z) only by sdlc's: every repo's
# promote job holds the fleet key's private half, so a fleet key that could
# vouch for :latest would let any fleet repo's CI forge the image every hook
# runs. main is still signed by the fleet key alone, and a digest is one the
# person typed, so either key will do for those two. A release before 0.15.2
# is reached by its digest.
case $want in
  main|@sha256:*) keys='sdlc fleet' who="sdlc's key or the crunchtools fleet key" ;;
  *)              keys=sdlc         who="sdlc's key" ;;
esac
key_id() { case $1 in sdlc) printf '%s' "$SDLC_KEY_ID" ;; fleet) printf '%s' "$FLEET_KEY_ID" ;; esac; }

# A tag is pulled every time: :latest moves, and a stale local copy is how a
# two-week-old reviewer once judged trentina. Offline, the copy it has stands,
# and is verified like any other. A digest is pulled only when it is missing.
case $image in
  *@sha256:*)
    digest=${image#*@}
    podman --events-backend=none image exists -- "$image" \
      || podman --events-backend=none pull -q -- "$image" > /dev/null \
      || cannot "$image could not be pulled" ;;
  *)
    podman --events-backend=none pull -q -- "$image" > /dev/null \
      || podman --events-backend=none image exists -- "$image" \
      || cannot "$image could not be pulled"
    digest=$(podman --events-backend=none image inspect \
               --format '{{.Digest}}' -- "$image" 2> "$dir/inspect.err") \
      || cannot "$image could not be inspected: $(cat "$dir/inspect.err")" ;;
esac
hex=${digest#sha256:}
case $digest in sha256:*) ;; *) cannot "$image has no sha256 digest to verify" ;; esac
case $hex in *[!0-9a-f]*) cannot "$image has no sha256 digest to verify" ;; esac
[ "${#hex}" -eq 64 ] || cannot "$image has no sha256 digest to verify"
pinned=$FLEET@$digest

# Verified once per digest and key, on a seat: the cache is the user's own,
# and whoever can write it can already edit this file. It is a convenience for
# an offline seat, never a verdict, so failing to write it is not a failure.
# CI always verifies: a self-hosted runner outlives the jobs it runs, and CI is
# never offline.
verified_dir=
if [ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ]; then :
elif [ -n "${XDG_CACHE_HOME:-}" ]; then verified_dir=$XDG_CACHE_HOME/sdlc/verified
elif [ -n "${HOME:-}" ]; then verified_dir=$HOME/.cache/sdlc/verified
fi
verified=
if [ -n "$verified_dir" ]; then
  for k in $keys; do
    [ ! -e "$verified_dir/$(key_id "$k")/$hex" ] || verified=$k
  done
fi
if [ -z "$verified" ]; then
  : > "$dir/verify"
  for k in $keys; do
    if podman --events-backend=none run --rm --log-driver=none --pull=missing \
         --cap-drop=all --security-opt=no-new-privileges --read-only \
         -v "$dir/$k.pub:/$k.pub:ro,Z" \
         -- "$COSIGN" verify --key "/$k.pub" --insecure-ignore-tlog=true "$pinned" \
         > /dev/null 2>> "$dir/verify"; then
      verified=$k
      break
    fi
  done
  if [ -z "$verified" ]; then
    sed 's/^/sdlc:   /' "$dir/verify" >&2
    cannot "$pinned ($image) could not be verified as signed by $who"
  fi
  [ -z "$verified_dir" ] || { _d=$verified_dir/$(key_id "$verified") \
    && mkdir -p "$_d" && : > "$_d/$hex"; } 2> /dev/null || :
fi

# By digest from here on, and never pulled again: the bytes verified above are
# the bytes that run.
if ! podman --events-backend=none run --rm --log-driver=none --network=none \
       --cap-drop=all --security-opt=no-new-privileges --pull=never \
       -- "$pinned" launcher "$pinned" > "$dir/sdlc" || [ ! -s "$dir/sdlc" ]; then
  cannot "$pinned ($image) could not print its launcher"
fi
# The launcher runs every check by the digest. SDLC_VERIFIED_FROM is the name
# the digest was resolved from, which its not-the-release banner asks about.
SDLC_IMAGE=$pinned SDLC_VERIFIED_FROM=$image sh "$dir/sdlc" "$@"
