#!/usr/bin/env bash
# The tests that need what an ordinary run has not: root with every
# capability, namespaces, a cgroup hierarchy that can be written, and no
# system call filter. They are built here, as static binaries, and run in a
# container that has all of that:
#
#   docker run --privileged --cgroupns private
#
#   scripts/privileged.sh                 the targets this machine runs natively
#   scripts/privileged.sh TARGET...       these targets
#
# On x86_64 the default targets are the x86_64 and i686 ones of musl and of
# fullrust; on aarch64, aarch64 musl, and armv7 musl if the processor and
# the kernel run 32-bit code (GitHub's arm64 runners do). A fullrust target
# is built in its image ($FULLRUST_IMAGE), the others by the toolchain
# installed, with rust-lld as the linker.
#
# What is covered, which nothing else in scripts/check.sh or CI can:
# - a child created in a cgroup, by `clone3` and, in a helper whose own
#   filter takes `clone3` away, by writing to `cgroup.procs`;
# - what root alone may do: `unshare`, `setns` and the host name in the
#   initial user namespace, user maps of several ranges, the identity and
#   the capabilities of a thread and of a child, the bounding and ambient
#   sets, mounting without a user namespace, mounts whose identifiers are
#   mapped to other users;
# - the capabilities of a file, with a root that is another user's, and
#   what a program run by someone else gets from them;
# - system call filters with nothing filtering the tests themselves, and
#   with them what a container's own filter refuses (`pidfd_getfd`);
# - what a creation of a filesystem that must be new says of the one
#   cgroup hierarchy;
# - io_uring (OSCALL_REQUIRE_IO_URING=1), which Docker's default filter
#   refuses.
#
# The tests run with OSCALL_REQUIRE_PRIVILEGED=1, which makes a failure of
# what they would otherwise skip for want of privilege (`skipped: ...`).
# The checkout is mounted read-only and the tests' files go to a tmpfs:
# root leaves nothing behind. (`suid`, because docker mounts a tmpfs
# `nosuid`, and a filesystem mounted so gives a program nothing of the
# capabilities of its file.)
set -euo pipefail
cd "$(dirname "$0")/.."

export CARGO_TARGET_DIR="${OSCALL_TARGET_DIR:-$PWD/target}"
FULLRUST_IMAGE="${FULLRUST_IMAGE:-ghcr.io/karpeleslab/fullrust:latest}"
# Where the tests run: anything with a /bin/sh, `cat` and `readlink`.
RUN_IMAGE="${OSCALL_PRIVILEGED_IMAGE:-debian:trixie-slim}"
# The tests of what a container is made of, and those of io_uring, which
# the system call filter of an ordinary container refuses: this is where
# they run for the fullrust targets.
TESTS=(process process_linux process_linux_single process_linux_security
    process_linux_landlock process_linux_trace fs_linux io_linux)

if ! command -v docker >/dev/null; then
    echo "docker not found" >&2
    exit 1
fi

# Whether this machine runs a static program of 32-bit ARM: an aarch64
# processor may lack the 32-bit state, and a kernel CONFIG_COMPAT.
runs_arm32() {
    local probe="$CARGO_TARGET_DIR/oscall-arm32-probe"
    mkdir -p "$probe"
    echo 'fn main() {}' >"$probe/probe.rs"
    rustc --target armv7-unknown-linux-musleabihf -C linker=rust-lld \
        -C target-feature=+crt-static -C link-self-contained=yes \
        -o "$probe/probe" "$probe/probe.rs" 2>/dev/null && "$probe/probe" 2>/dev/null
}

targets=("$@")
if [ ${#targets[@]} -eq 0 ]; then
    case "$(uname -m)" in
        x86_64)
            targets=(x86_64-unknown-linux-musl i686-unknown-linux-musl
                x86_64-unknown-linux-fullrust i686-unknown-linux-fullrust)
            ;;
        aarch64)
            targets=(aarch64-unknown-linux-musl)
            if runs_arm32; then
                targets+=(armv7-unknown-linux-musleabihf)
            else
                echo "== this machine does not run 32-bit ARM programs: armv7 skipped"
            fi
            ;;
        *)
            echo "no default target for $(uname -m): name one" >&2
            exit 1
            ;;
    esac
fi

test_args=()
for test in "${TESTS[@]}"; do
    test_args+=(--test "$test")
done

# Builds the tests for the target $1 and prints the path of each test
# program, relative to the checkout.
build() {
    local target="$1" log
    log="$(mktemp)"
    # cargo names what it built on its standard error output:
    #   Executable tests/fs.rs (target/.../fs-0123456789abcdef)
    case "$target" in
        *fullrust*)
            docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/src -w /src \
                -e CARGO_TARGET_DIR=/src/target/fullrust \
                -e "CARGO_BUILD_TARGET=$target" \
                -e FULLRUST_NO_ECOSYSTEM=1 -e CARGO_TERM_COLOR=never \
                "$FULLRUST_IMAGE" test --no-run --all-features "${test_args[@]}" >"$log" 2>&1
            ;;
        *)
            local env_name
            env_name="$(tr 'a-z-' 'A-Z_' <<<"$target")"
            env "CARGO_TARGET_${env_name}_LINKER=rust-lld" \
                "CARGO_TARGET_${env_name}_RUSTFLAGS=-C target-feature=+crt-static -C link-self-contained=yes" \
                CARGO_TERM_COLOR=never \
                cargo test --no-run --all-features --target "$target" "${test_args[@]}" >"$log" 2>&1
            ;;
    esac || {
        cat "$log" >&2
        rm -f "$log"
        return 1
    }
    sed -n 's/^ *Executable .* (\(.*\))$/\1/p' "$log" |
        sed -e "s|^$PWD/||" -e 's|^/src/||'
    rm -f "$log"
}

mkdir -p "$CARGO_TARGET_DIR/oscall-tests"
status=0
for target in "${targets[@]}"; do
    echo "== build $target"
    mapfile -t programs < <(build "$target")
    if [ ${#programs[@]} -ne ${#TESTS[@]} ]; then
        echo "expected ${#TESTS[@]} test programs for $target, found ${#programs[@]}" >&2
        exit 1
    fi
    for program in "${programs[@]}"; do
        echo "== test privileged $target $(basename "$program")"
        docker run --rm --init --privileged --cgroupns private \
            -v "$PWD":/src:ro --tmpfs /src/target/oscall-tests:exec,suid,mode=1777 -w /src \
            -e OSCALL_REQUIRE_PRIVILEGED=1 -e OSCALL_REQUIRE_IO_URING=1 \
            "$RUN_IMAGE" "/src/$program" || status=1
    done
done
if [ "$status" -ne 0 ]; then
    echo "== privileged tests failed" >&2
    exit 1
fi
echo "== ok"
