#!/usr/bin/env bash
# Checks capstone 2: the image is scanned and in the registry, and the container runs hardened.
source "$(dirname "$0")/../lib.sh"
need docker curl jq
work container
PORT="${PORT:-18082}"; REG_PORT="${REG_PORT:-5001}"
cd "$WORK"

say "Image and registry"
check "the scan report exists" test -s scan.json
crit=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity == "CRITICAL")] | length' scan.json)
[ "$crit" -eq 0 ] && ok "no CRITICAL vulnerabilities (gate)" || bad "$crit CRITICAL vulnerabilities: rebuild on a patched base image"
check "the registry lists the orders repository" bash -c "curl -fsS http://127.0.0.1:$REG_PORT/v2/_catalog | jq -e '.repositories | index(\"orders\")'"
check "tag 1.0.0 is in the registry" bash -c "curl -fsS http://127.0.0.1:$REG_PORT/v2/orders/tags/list | jq -e '.tags | index(\"1.0.0\")'"

say "Runtime"
img=$(docker inspect cap-orders --format '{{.Config.Image}}')
case "$img" in "localhost:$REG_PORT/orders@sha256:"*) ok "the container runs the registry image, by digest" ;; *) bad "the container runs $img, not the registry digest" ;; esac
check "the service answers through the published port" curl -fsS "http://127.0.0.1:$PORT/healthz"
uid=$(docker exec cap-orders id -u); [ "$uid" = 10001 ] && ok "runs as user 10001, not root" || bad "runs as uid $uid"
if docker exec cap-orders sh -c 'touch /app/x' 2>/dev/null; then bad "the filesystem is writable"; else ok "the root filesystem is read-only"; fi
mem=$(docker inspect cap-orders --format '{{.HostConfig.Memory}}'); [ "$mem" = 134217728 ] && ok "memory limited to 128 MiB" || bad "memory limit is $mem"
cpu=$(docker inspect cap-orders --format '{{.HostConfig.NanoCpus}}'); [ "$cpu" = 500000000 ] && ok "CPU limited to 0.5" || bad "CPU limit is $cpu"
pids=$(docker inspect cap-orders --format '{{.HostConfig.PidsLimit}}'); [ "$pids" = 64 ] && ok "at most 64 processes" || bad "pids limit is $pids"
caps=$(docker inspect cap-orders --format '{{.HostConfig.CapDrop}}'); [ "$caps" = "[ALL]" ] && ok "all Linux capabilities dropped" || bad "capabilities dropped: $caps"
for _ in $(seq 20); do [ "$(docker inspect cap-orders --format '{{.State.Health.Status}}')" = healthy ] && break; sleep 1; done
check "the image's health check reports healthy" bash -c "[ \"\$(docker inspect cap-orders --format '{{.State.Health.Status}}')\" = healthy ]"
summary
