#!/usr/bin/env bash
# Checks capstone 5: the release passed every gate, and each gate blocks the problem it exists for.
source "$(dirname "$0")/../lib.sh"
need docker jq curl
work devsecops
cd "$WORK"
export REG="localhost:${REG_PORT:-5002}" COSIGN_PASSWORD=""
PORT="${PORT:-18085}"
P="$CAP_ROOT/05-devsecops/pipeline.sh"
D="$CAP_ROOT/05-devsecops/deploy.sh"
COSIGN_IMG=gcr.io/projectsigstore/cosign:v2.4.1
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -w /w -e COSIGN_PASSWORD "$COSIGN_IMG" "$@"; }
DIGEST="$(cat src/digest.txt)"

say "The release"
check "the signed image is running and ready" curl -fsS "http://127.0.0.1:$PORT/readyz"
[ "$(docker inspect cap-sec-orders --format '{{.Config.User}} {{.HostConfig.ReadonlyRootfs}}')" = "10001:10001 true" ] \
  && ok "it runs as user 10001 with a read-only root filesystem" || bad "user or read-only setting is wrong"
[ "$(docker inspect cap-sec-orders --format '{{.Config.Image}}')" = "$DIGEST" ] \
  && ok "it runs the exact digest the pipeline signed" || bad "the running image is not the signed digest"
n=$(cosign verify-attestation --key cosign.pub --type cyclonedx --insecure-ignore-tlog=true --allow-http-registry "$DIGEST" 2>/dev/null \
  | jq -s '[.[0].payload | @base64d | fromjson | .predicate.components[]] | length')
[ "${n:-0}" -gt 0 ] && ok "the signed SBOM attestation verifies ($n components)" || bad "the SBOM attestation did not verify"

# each case copies the good source, breaks one thing, and expects the pipeline to stop at one gate
break_test()   { sed -i 's/self.send(200, {"status": "ok"})/self.send(500, {"status": "ok"})/' orders.py; }
break_shell()  { printf 'import subprocess\n\n\ndef run(name):\n    return subprocess.call("echo " + name, shell=True)\n' > tools.py; }
break_nosec()  { sed -i 's/# nosec B310 - .*/# nosec/' orders.py; }
break_dep()    { echo "requests==2.19.1" >> requirements-ci.txt; }
break_secret() { printf 'AWS_ACCESS_KEY_ID = "%s"\n' "AKIA$(head -c 400 /dev/urandom | tr -dc 'A-Z2-7' | head -c 16)" > settings.py; }
break_policy() {
  sed -i -e 's/runAsNonRoot: true/runAsNonRoot: false/' -e 's/readOnlyRootFilesystem: true/readOnlyRootFilesystem: false/' \
         -e '/limits:/d' k8s/deploy.yaml
}
expect_block() {
  local name="$1" want="$2" desc="$3" got=0
  rm -rf "bad-$name"; cp -r src "bad-$name"; rm -rf "bad-$name/.pipeline"
  ( cd "bad-$name" && "break_$name" )
  bash "$P" "bad-$name" "9.9.$want-$name" > "bad-$name.log" 2>&1 || got=$?
  if [ "$got" = $((10 + want)) ]; then ok "gate $want blocks $desc"
  else bad "gate $want did not block $desc (exit $got; see $WORK/bad-$name.log)"; tail -5 "bad-$name.log"; fi
}

say "Each gate blocks what it exists to block"
expect_block test   1 "a change that breaks the health check"
expect_block shell  2 "shell injection (subprocess with shell=True)"
expect_block nosec  2 "a suppression without a reason"
expect_block dep    3 "a dependency with known vulnerabilities (requests 2.19.1)"
expect_block secret 4 "a committed cloud access key"
expect_block policy 8 "a manifest that may run as root, writable, without limits"
n=$(grep -c "^FAIL" bad-policy/.pipeline/8.log || true)
[ "$n" -ge 4 ] && ok "the policy names each problem ($n violations listed)" || bad "the policy listed $n violations"

say "Deploy refuses anything not signed by our key"
docker build -q -t cap-sec-orders:unsigned --build-arg VERSION=unsigned src > /dev/null
docker tag cap-sec-orders:unsigned "$REG/orders:unsigned"
docker push -q "$REG/orders:unsigned" > /dev/null
U=$(docker image inspect "$REG/orders:unsigned" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^$REG/orders@")
refused() {  # refused "description" "expected message" REF
  local out got=0
  out=$(PORT=18095 bash "$D" "$3" 2>&1) || got=$?
  if [ "$got" -ne 0 ] && grep -q "$2" <<< "$out"; then ok "$1"; else bad "$1 (exit $got: $out)"; fi
}
refused "an unsigned digest is refused" "refused: no valid signature" "$U"
refused "a tag instead of a digest is refused" "not a tag" "$REG/orders:1.0.0"
cosign generate-key-pair --output-key-prefix other > /dev/null 2>&1
cosign sign --key other.key --tlog-upload=false --allow-http-registry -y "$U" > /dev/null 2>&1
refused "a digest signed with someone else's key is refused" "refused: no valid signature" "$U"
docker ps --format '{{.Ports}}' | grep -q 18095 && bad "something started on the test port" || ok "nothing refused was started"
[ "$(docker inspect cap-sec-orders --format '{{.Config.Image}}')" = "$DIGEST" ] \
  && ok "the signed release is still the one running" || bad "the running release changed"
summary
