#!/usr/bin/env bash
# security-audit-sandbox - OS-enforced Docker sandbox for the security-audit skill.
#
# Copies target code into a scratch directory and runs it in a locked-down
# container: no network, read-only root, scratch-only writes, dropped
# capabilities, no-new-privileges, and CPU/memory/PID limits.
#
# Usage:
#   security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
#   security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
#   security-audit-sandbox stop <app> [--keep]
#   security-audit-sandbox status <app>
#   security-audit-sandbox --help
#
# Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
#   IMAGE=node:22-bookworm
#   EXCLUDE="node_modules dist coverage"
#
# Default exclusions: .git, .env*, and the top-level /data directory.
# The original app directory is never mounted into the container.
set -euo pipefail

PROG=security-audit-sandbox
RUN_PARENT="$HOME/security-audit-runs"
STATE_ROOT="${XDG_STATE_HOME:-$HOME/.local/state}/security-audit-sandbox"
CONF_NAME=security-audit.conf
DEFAULT_TIMEOUT=600

die() {
  printf '%s: %s\n' "$PROG" "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
Copy target code into a scratch directory and run it in a locked-down Docker
container: no network, read-only root, scratch-only writes, dropped
capabilities, no-new-privileges, and CPU/memory/PID limits.

Usage:
  security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
      Copy <app> to $HOME/security-audit-runs/<slug>.XXXXXX and start the
      container. Repeat --exclude to add rsync exclusions.

  security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
      Run <command> inside the running container from /scratch/app under
      `timeout --signal=KILL`. Default timeout: 600 seconds.

  security-audit-sandbox stop <app> [--keep]
      Remove the container and state file. Remove the run directory too,
      unless --keep is given.

  security-audit-sandbox status <app>
      Print the container name, run directory, and whether it is running.

  security-audit-sandbox --help
      Show this help.

Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
  IMAGE=node:22-bookworm
  EXCLUDE="node_modules dist coverage"

Image resolution order:
  1. --image
  2. IMAGE= in security-audit.conf
  3. package.json -> node:22-bookworm
     pyproject.toml or requirements.txt -> python:3.12-slim
     go.mod -> golang:1.24-bookworm
     Cargo.toml -> rust:1-bookworm
     Gemfile -> ruby:3.3-bookworm

Always excluded from the copy: .git, .env*, and the top-level /data directory.
The original app directory is never mounted into the container.

Docker Desktop on macOS may refuse the fsize ulimit. The wrapper then starts
the container without that one limit and prints a warning; nofile stays in
place. On Linux hosts that accept fsize, the 100 MiB file-size cap is applied.
EOF
}

need_docker() {
  command -v docker >/dev/null 2>&1 || die "docker is not installed or not on PATH"
  docker info >/dev/null 2>&1 || die "cannot reach the Docker daemon; is Docker running?"
}

canonical_app() {
  local app=$1
  [ -d "$app" ] || die "app directory not found: $app"
  (cd -P "$app" && pwd -P)
}

app_slug() {
  local name
  name=$(basename "$1")
  name=${name//[^A-Za-z0-9_.-]/-}
  [ -n "$name" ] || name=app
  printf '%s' "$name"
}

app_hash() {
  printf '%s' "$1" | shasum -a 256 | cut -c1-8
}

state_file_for() {
  local app=$1 slug hash
  slug=$(app_slug "$app")
  hash=$(app_hash "$app")
  printf '%s/state-%s-%s' "$STATE_ROOT" "$slug" "$hash"
}

container_name_for() {
  local app=$1 slug hash
  slug=$(app_slug "$app")
  hash=$(app_hash "$app")
  printf 'security-audit-%s-%s' "$slug" "$hash"
}

strip_quotes() {
  local value=$1
  case $value in
    \"*\") value=${value#\"}; value=${value%\"} ;;
    \'*\') value=${value#\'}; value=${value%\'} ;;
  esac
  printf '%s' "$value"
}

trim() {
  local value=$1
  value=${value#"${value%%[![:space:]]*}"}
  value=${value%"${value##*[![:space:]]}"}
  printf '%s' "$value"
}

CONF_IMAGE=""
CONF_EXCLUDE=""
load_conf() {
  local app=$1 conf line key value
  conf="$app/$CONF_NAME"
  [ -f "$conf" ] || return 0
  while IFS= read -r line || [ -n "$line" ]; do
    line=${line%$'\r'}
    line=$(trim "$line")
    case $line in
      ''|'#'*) continue ;;
    esac
    case $line in
      *=*) ;;
      *) continue ;;
    esac
    key=$(trim "${line%%=*}")
    value=$(trim "${line#*=}")
    value=$(strip_quotes "$value")
    case $key in
      IMAGE) CONF_IMAGE=$value ;;
      EXCLUDE) CONF_EXCLUDE="${CONF_EXCLUDE:+$CONF_EXCLUDE }$value" ;;
    esac
  done < "$conf"
}

infer_image() {
  local app=$1
  if [ -f "$app/package.json" ]; then
    printf 'node:22-bookworm'
  elif [ -f "$app/pyproject.toml" ] || [ -f "$app/requirements.txt" ]; then
    printf 'python:3.12-slim'
  elif [ -f "$app/go.mod" ]; then
    printf 'golang:1.24-bookworm'
  elif [ -f "$app/Cargo.toml" ]; then
    printf 'rust:1-bookworm'
  elif [ -f "$app/Gemfile" ]; then
    printf 'ruby:3.3-bookworm'
  else
    printf ''
  fi
}

load_state() {
  local app=$1 file key value
  file=$(state_file_for "$app")
  [ -f "$file" ] || return 1
  STATE_CONTAINER=""
  STATE_RUN_DIR=""
  STATE_APP=""
  STATE_IMAGE=""
  STATE_FSIZE=""
  while IFS='=' read -r key value || [ -n "$key" ]; do
    case $key in
      CONTAINER) STATE_CONTAINER=$value ;;
      RUN_DIR) STATE_RUN_DIR=$value ;;
      APP) STATE_APP=$value ;;
      IMAGE) STATE_IMAGE=$value ;;
      FSIZE) STATE_FSIZE=$value ;;
    esac
  done < "$file"
  [ -n "$STATE_CONTAINER" ] && [ -n "$STATE_RUN_DIR" ]
}

container_running() {
  local name=$1 state
  state=$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null) || return 1
  [ "$state" = "true" ]
}

container_exists() {
  docker inspect "$1" >/dev/null 2>&1
}

WALL_CLOCK_PROBE_SECS=2

check_wall_clock_guard() {
  local container=$1 status elapsed out
  SECONDS=0
  set +e
  out=$(docker exec "$container" timeout --signal=KILL "$WALL_CLOCK_PROBE_SECS" sleep 10 2>&1)
  status=$?
  set -e
  elapsed=$SECONDS
  case $status in
    124|137) ;;
    *)
      [ -z "$out" ] || printf '%s\n' "$out" >&2
      die "image $STATE_IMAGE's 'timeout' does not enforce '--signal=KILL'; refusing to run without a wall-clock limit"
      ;;
  esac
  if [ "$elapsed" -lt 1 ] || [ "$elapsed" -gt $((WALL_CLOCK_PROBE_SECS + 4)) ]; then
    die "image $STATE_IMAGE's 'timeout' did not stop the probe after ${WALL_CLOCK_PROBE_SECS}s; refusing to run without a wall-clock limit"
  fi
}

check_run_dir() {
  local dir=$1
  case $dir in
    "$RUN_PARENT"/*) ;;
    *) die "refusing to remove unexpected run directory: $dir" ;;
  esac
}

rm_run_dir() {
  local dir=$1
  check_run_dir "$dir"
  rm -rf "$dir"
}

cleanup_failed_start() {
  local run_dir=$1 state_file=$2
  [ -n "$run_dir" ] && [ -d "$run_dir" ] && rm_run_dir "$run_dir"
  [ -n "$state_file" ] && rm -f "$state_file"
}

cmd_start() {
  local app_arg="" image_opt="" conf_image inferred
  local app app_dir run_dir container state_file fsize_note out
  local -a cli_excludes rsync_cmd docker_cmd
  cli_excludes=()

  while [ $# -gt 0 ]; do
    case $1 in
      --image)
        [ $# -ge 2 ] || die "--image needs a value"
        image_opt=$2
        shift 2
        ;;
      --image=*)
        image_opt=${1#--image=}
        shift
        ;;
      --exclude)
        [ $# -ge 2 ] || die "--exclude needs a value"
        cli_excludes+=("$2")
        shift 2
        ;;
      --exclude=*)
        cli_excludes+=("${1#--exclude=}")
        shift
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      -*)
        die "unknown option for start: $1"
        ;;
      *)
        [ -z "$app_arg" ] || die "unexpected argument for start: $1"
        app_arg=$1
        shift
        ;;
    esac
  done

  [ -n "$app_arg" ] || die "start needs an app directory"
  need_docker
  app_dir=$(canonical_app "$app_arg")

  load_conf "$app_dir"
  conf_image=$CONF_IMAGE

  if [ -n "$image_opt" ]; then
    image=$image_opt
  elif [ -n "$conf_image" ]; then
    image=$conf_image
  else
    inferred=$(infer_image "$app_dir")
    [ -n "$inferred" ] || die "cannot infer an image for $app_dir; pass --image or set IMAGE= in $CONF_NAME"
    image=$inferred
  fi

  state_file=$(state_file_for "$app_dir")
  container=$(container_name_for "$app_dir")

  if load_state "$app_dir"; then
    if container_running "$STATE_CONTAINER"; then
      die "a sandbox for $app_dir is already running (container $STATE_CONTAINER); run '$PROG stop $app_arg' first"
    fi
    if container_exists "$STATE_CONTAINER"; then
      docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
    fi
    rm -f "$state_file"
    printf '%s: removed stale state for stopped container %s\n' "$PROG" "$STATE_CONTAINER" >&2
  fi

  if container_exists "$container"; then
    die "container $container already exists but is not recorded in state; remove it with 'docker rm -f $container'"
  fi

  mkdir -p "$RUN_PARENT" || die "cannot create $RUN_PARENT"
  run_dir=$(mktemp -d "$RUN_PARENT/$(app_slug "$app_dir").XXXXXX") || die "cannot create run directory under $RUN_PARENT"
  mkdir -p "$run_dir/app" "$run_dir/home" "$run_dir/tmp" "$run_dir/cache" || {
    cleanup_failed_start "$run_dir" "$state_file"
    die "cannot prepare run directory $run_dir"
  }

  rsync_cmd=(rsync -a --exclude=.git --exclude='.env*' --exclude=/data)
  if [ -n "$CONF_EXCLUDE" ]; then
    local conf_pat
    local -a conf_pats
    read -r -a conf_pats <<< "$CONF_EXCLUDE"
    for conf_pat in "${conf_pats[@]}"; do
      rsync_cmd+=("--exclude=$conf_pat")
    done
  fi
  if [ ${#cli_excludes[@]} -gt 0 ]; then
    local cli_pat
    for cli_pat in "${cli_excludes[@]}"; do
      rsync_cmd+=("--exclude=$cli_pat")
    done
  fi

  if ! "${rsync_cmd[@]}" "$app_dir/" "$run_dir/app/"; then
    cleanup_failed_start "$run_dir" "$state_file"
    die "rsync failed while copying $app_dir"
  fi

  docker_cmd=(docker run -d --name "$container"
    --network none
    --read-only
    -v "$run_dir:/scratch"
    --tmpfs '/tmp:rw,nosuid,size=512m'
    -e HOME=/scratch/home
    -e TMPDIR=/scratch/tmp
    -e XDG_CACHE_HOME=/scratch/cache
    --user "$(id -u):$(id -g)"
    --memory 4g
    --cpus 2
    --pids-limit 256
    --cap-drop ALL
    --security-opt no-new-privileges
    --init
    --ulimit nofile=1024:1024
    --workdir /scratch/app)

  fsize_note=""
  if out=$("${docker_cmd[@]}" --ulimit fsize=104857600 "$image" sleep infinity 2>&1); then
    STATE_FSIZE=on
    fsize_note=on
  else
    case $out in
      *fsize*|*FSIZE*)
        printf '%s: Docker refused the fsize ulimit; starting without the file-size cap\n' "$PROG" >&2
        if out=$("${docker_cmd[@]}" "$image" sleep infinity 2>&1); then
          STATE_FSIZE=off
          fsize_note=off
        else
          cleanup_failed_start "$run_dir" "$state_file"
          die "docker run failed: $out"
        fi
        ;;
      *)
        cleanup_failed_start "$run_dir" "$state_file"
        die "docker run failed: $out"
        ;;
    esac
  fi

  mkdir -p "$STATE_ROOT" || {
    docker rm -f "$container" >/dev/null 2>&1 || true
    cleanup_failed_start "$run_dir" "$state_file"
    die "cannot create state directory $STATE_ROOT"
  }
  if ! {
    printf 'CONTAINER=%s\n' "$container"
    printf 'RUN_DIR=%s\n' "$run_dir"
    printf 'APP=%s\n' "$app_dir"
    printf 'IMAGE=%s\n' "$image"
    printf 'FSIZE=%s\n' "$STATE_FSIZE"
  } > "$state_file"; then
    docker rm -f "$container" >/dev/null 2>&1 || true
    cleanup_failed_start "$run_dir" "$state_file"
    die "cannot write state file $state_file"
  fi

  printf 'container: %s\n' "$container"
  printf 'run dir:   %s\n' "$run_dir"
  printf 'scratch:   %s\n' "$run_dir (mounted at /scratch)"
  printf 'app copy:  %s/app (mounted at /scratch/app)\n' "$run_dir"
  printf 'image:     %s\n' "$image"
  if [ "$fsize_note" = off ]; then
    printf 'note:      fsize ulimit refused by Docker; no file-size cap applied\n'
  fi
}

cmd_exec() {
  local app_arg="" timeout_secs=$DEFAULT_TIMEOUT saw_sep=0
  local app_dir container

  while [ $# -gt 0 ]; do
    case $1 in
      --timeout)
        [ $# -ge 2 ] || die "--timeout needs a value"
        timeout_secs=$2
        shift 2
        ;;
      --timeout=*)
        timeout_secs=${1#--timeout=}
        shift
        ;;
      --)
        shift
        saw_sep=1
        break
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      -*)
        die "unknown option for exec: $1"
        ;;
      *)
        [ -z "$app_arg" ] || die "unexpected argument for exec: $1"
        app_arg=$1
        shift
        ;;
    esac
  done

  [ -n "$app_arg" ] || die "exec needs an app directory"
  [ "$saw_sep" = 1 ] || die "exec needs -- before the command"
  [ $# -gt 0 ] || die "exec needs a command after --"
  case $timeout_secs in
    ''|*[!0-9]*) die "--timeout must be a positive integer number of seconds" ;;
  esac
  [ "$timeout_secs" -gt 0 ] || die "--timeout must be greater than zero"

  need_docker
  app_dir=$(canonical_app "$app_arg")
  load_state "$app_dir" || die "no sandbox recorded for $app_dir; run '$PROG start $app_arg' first"
  container=$STATE_CONTAINER
  container_running "$container" || die "container $container is not running; run '$PROG stop $app_arg' and start again"

  check_wall_clock_guard "$container"

  docker exec --workdir /scratch/app "$container" timeout --signal=KILL "$timeout_secs" "$@"
}

cmd_stop() {
  local app_arg="" keep=0 app_dir run_dir

  while [ $# -gt 0 ]; do
    case $1 in
      --keep)
        keep=1
        shift
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      -*)
        die "unknown option for stop: $1"
        ;;
      *)
        [ -z "$app_arg" ] || die "unexpected argument for stop: $1"
        app_arg=$1
        shift
        ;;
    esac
  done

  [ -n "$app_arg" ] || die "stop needs an app directory"
  app_dir=$(canonical_app "$app_arg")
  load_state "$app_dir" || die "no sandbox recorded for $app_dir"

  run_dir=$STATE_RUN_DIR
  [ "$keep" = 1 ] || check_run_dir "$run_dir"
  docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
  rm -f "$(state_file_for "$app_dir")"

  if [ "$keep" = 1 ]; then
    printf 'removed container %s; kept run dir %s\n' "$STATE_CONTAINER" "$run_dir"
  else
    rm_run_dir "$run_dir"
    printf 'removed container %s and run dir %s\n' "$STATE_CONTAINER" "$run_dir"
  fi
}

cmd_status() {
  local app_arg="" app_dir running

  while [ $# -gt 0 ]; do
    case $1 in
      -h|--help)
        usage
        exit 0
        ;;
      -*)
        die "unknown option for status: $1"
        ;;
      *)
        [ -z "$app_arg" ] || die "unexpected argument for status: $1"
        app_arg=$1
        shift
        ;;
    esac
  done

  [ -n "$app_arg" ] || die "status needs an app directory"
  app_dir=$(canonical_app "$app_arg")
  load_state "$app_dir" || die "no sandbox recorded for $app_dir"

  if container_running "$STATE_CONTAINER"; then
    running=running
  elif container_exists "$STATE_CONTAINER"; then
    running=stopped
  else
    running=missing
  fi

  printf 'container: %s\n' "$STATE_CONTAINER"
  printf 'run dir:   %s\n' "$STATE_RUN_DIR"
  printf 'app:       %s\n' "$STATE_APP"
  printf 'image:     %s\n' "$STATE_IMAGE"
  printf 'fsize cap: %s\n' "$STATE_FSIZE"
  printf 'state:     %s\n' "$running"
}

main() {
  [ $# -gt 0 ] || {
    usage >&2
    exit 1
  }
  local cmd=$1
  shift
  case $cmd in
    start) cmd_start "$@" ;;
    exec) cmd_exec "$@" ;;
    stop) cmd_stop "$@" ;;
    status) cmd_status "$@" ;;
    -h|--help|help) usage ;;
    *)
      die "unknown command: $cmd (try --help)"
      ;;
  esac
}

main "$@"
