Gunnar

nordisk/heimdall

scripts/plain-tests.sh

#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
# heimdall-plain container tests (the #[ignore]d tests in
# crates/heimdall-plain/tests/container.rs). Heimdall is a defensive sandbox;
# these tests run real youki containers that attack only themselves.
#
# They need user namespaces and cgroup v2 with the memory, pids and cpu
# controllers delegated. The script runs them in a privileged toolchain
# container (rootless podman is enough), moves itself out of the container's
# root cgroup so controllers can be enabled for the job cgroups, then runs
#   cargo test -p nordisk-heimdall-plain --test container -- --ignored
#
# Usage, from the repo root on a Linux host with podman:
#   scripts/plain-tests.sh
# Environment:
#   HEIMDALL_TEST_IMAGE  toolchain image with libseccomp-dev and busybox-static
#                        (default localhost/nordisk-cargo-toolchain:heim-m0)
#   CARGO_TARGET_DIR     host target dir to mount (default ./target)
#   CARGO_HOME           host cargo home to mount (optional)
#   HEIMDALL_PLAIN_TEST_ARGS  extra arguments after `--` (e.g. a test name)
set -eu
cd "$(dirname "$0")/.."

if [ "${HEIMDALL_PLAIN_INNER:-}" != 1 ]; then
  img=${HEIMDALL_TEST_IMAGE:-localhost/nordisk-cargo-toolchain:heim-m0}
  tgt=${CARGO_TARGET_DIR:-$PWD/target}
  mkdir -p "$tgt"
  extra=""
  if [ -n "${CARGO_HOME:-}" ]; then extra="-v $CARGO_HOME:/ch -e CARGO_HOME=/ch"; fi
  # shellcheck disable=SC2086
  exec podman run --rm --privileged --cgroupns=private \
    -v "$PWD":/src -v "$tgt":/tgt -e CARGO_TARGET_DIR=/tgt $extra \
    -e HEIMDALL_PLAIN_INNER=1 -e HEIMDALL_PLAIN_TEST_ARGS="${HEIMDALL_PLAIN_TEST_ARGS:-}" \
    -e CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-8}" \
    -w /src "$img" scripts/plain-tests.sh
fi

# Inside the container: leave the root cgroup, enable the controllers.
cg=/sys/fs/cgroup
if [ ! -w "$cg/cgroup.subtree_control" ]; then
  echo "cgroup v2 is not writable here (need --privileged and cgroup v2)" >&2
  exit 2
fi
mkdir -p "$cg/init"
for p in $(cat "$cg/cgroup.procs"); do echo "$p" > "$cg/init/cgroup.procs" 2>/dev/null || true; done
for c in cpu memory pids; do
  if grep -qw "$c" "$cg/cgroup.controllers"; then
    echo "+$c" > "$cg/cgroup.subtree_control"
  else
    echo "controller $c is not delegated to this container" >&2
    exit 2
  fi
done
echo "controllers enabled: $(cat "$cg/cgroup.subtree_control")"

cargo build -p nordisk-heimdall-plain --features youki --bins
# shellcheck disable=SC2086
HEIMDALL_PLAIN_SHIM="$CARGO_TARGET_DIR/debug/heimdall-plain-shim" \
  cargo test -p nordisk-heimdall-plain --features youki --test container -- --ignored ${HEIMDALL_PLAIN_TEST_ARGS:-}