#!/usr/bin/env bash
# The DevSecOps pipeline: nine gates in order; the first gate that fails stops the release.
#   pipeline.sh SRC_DIR VERSION      (setup.sh runs it; verify.sh runs it again on broken copies)
# Needs: WORK (the capstone folder, holding .venv and cosign.key) and REG (the registry host:port).
source "$(dirname "$0")/../lib.sh"
work devsecops
SRC="$(cd "$1" && pwd)"; VERSION="$2"
LOGS="$SRC/.pipeline"; rm -rf "$LOGS"; mkdir -p "$LOGS"
VENV="$WORK/.venv/bin"
COSIGN_IMG=gcr.io/projectsigstore/cosign:v2.4.1
CONFTEST_IMG=openpolicyagent/conftest:v0.56.0
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -v "$SRC:/src" -w /w -e COSIGN_PASSWORD "$COSIGN_IMG" "$@"; }
conftest() { docker run --rm -u 0 -v "$SRC:/src" -v "$CAP_ROOT/05-devsecops/policy:/policy:ro" -w /src "$CONFTEST_IMG" "$@"; }

gate() {
  local n="$1" name="$2"; shift 2
  printf '  gate %s  %-34s ' "$n" "$name"
  # run the gate in a subshell with errexit on, so any failing command inside it fails the gate
  # (inside "if ...; then" bash would silently ignore set -e)
  local rc=0
  set +e; ( set -e; "$@" ) > "$LOGS/$n.log" 2>&1; rc=$?; set -e
  if [ "$rc" -eq 0 ]; then echo pass
  else
    echo "BLOCKED"; sed 's/^/        | /' "$LOGS/$n.log" | tail -12
    echo "PIPELINE BLOCKED at gate $n ($name)"; exit $((10 + n))
  fi
}

unit_tests() { cd "$SRC" && python3 -m unittest -q test_orders; }

static_scan() {
  # every suppression must name the rule and give a reason, like: # nosec B104 - why it is safe
  if grep -nE '#\s*nosec' "$SRC"/*.py | grep -vE '#\s*nosec B[0-9]{3} - .{8,}'; then
    echo "the nosec comment above has no rule id or no reason"; return 1
  fi
  "$VENV/bandit" -q -r "$SRC" -x "$SRC/test_orders.py,$SRC/.pipeline" --severity-level medium --confidence-level medium
}

dependency_audit() { "$VENV/pip-audit" --no-deps --disable-pip --progress-spinner off -r "$SRC/requirements-ci.txt"; }

secret_scan() { trivy fs --quiet --scanners secret --exit-code 1 --skip-dirs "$SRC/.pipeline" "$SRC"; }

build_and_scan() {
  docker build -q -t "cap-sec-orders:$VERSION" --build-arg "VERSION=$VERSION" "$SRC"
  trivy image --quiet --scanners vuln --severity CRITICAL --ignore-unfixed --exit-code 1 "cap-sec-orders:$VERSION"
}

sbom() {
  syft -q "cap-sec-orders:$VERSION" -o "cyclonedx-json=$SRC/sbom.cdx.json"
  jq -e '[.components[] | select(.name == "python")] | length > 0' "$SRC/sbom.cdx.json"
  jq -r '"\(.components | length) components recorded"' "$SRC/sbom.cdx.json"
}

push_sign_attest() {
  docker tag "cap-sec-orders:$VERSION" "$REG/orders:$VERSION"
  docker push -q "$REG/orders:$VERSION"
  docker image inspect "$REG/orders:$VERSION" --format '{{range .RepoDigests}}{{println .}}{{end}}' \
    | grep "^$REG/orders@" > "$SRC/digest.txt"
  cosign sign --key cosign.key --tlog-upload=false --allow-http-registry -y "$(cat "$SRC/digest.txt")"
  cosign attest --key cosign.key --type cyclonedx --predicate /src/sbom.cdx.json \
    --tlog-upload=false --allow-http-registry -y "$(cat "$SRC/digest.txt")"
}

policy() {
  sed "s|image: IMAGE|image: $(cat "$SRC/digest.txt")|" "$SRC/k8s/deploy.yaml" > "$SRC/k8s/deploy.rendered.yaml"
  conftest verify --no-color --policy /policy
  conftest test --no-color --policy /policy k8s/deploy.rendered.yaml
}

deploy() { bash "$CAP_ROOT/05-devsecops/deploy.sh" "$(cat "$SRC/digest.txt")"; }

set -e
say "Pipeline for orders $VERSION"
gate 1 "unit tests"                    unit_tests
gate 2 "static analysis (bandit)"      static_scan
gate 3 "dependency audit (pip-audit)"  dependency_audit
gate 4 "secret scan (trivy)"           secret_scan
gate 5 "build + image scan (CRITICAL)" build_and_scan
gate 6 "SBOM (syft, CycloneDX)"        sbom
gate 7 "push, sign, attest (cosign)"   push_sign_attest
gate 8 "policy (conftest)"             policy
gate 9 "deploy signed digest only"     deploy
echo "PIPELINE PASSED: $(cat "$SRC/digest.txt")"
