# Illustrative example only.
# Build a reproducible, non-root toolbox image for post-build security tests.

FROM alpine:3.21

ARG TRIVY_VERSION=0.65.0
ARG GITLEAKS_VERSION=8.24.2
ARG HADOLINT_VERSION=2.12.0
ARG SEMGREP_VERSION=1.117.0
ARG CHECKOV_VERSION=3.2.390
ARG SYFT_VERSION=1.22.0
ARG GRYPE_VERSION=0.95.0

RUN apk add --no-cache \
    bash \
    ca-certificates \
    curl \
    git \
    jq \
    nodejs \
    npm \
    python3 \
    py3-pip \
    tar \
    unzip \
    wget

# Trivy
RUN wget -qO- "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz" \
  | tar -xz -C /usr/local/bin trivy

# Gitleaks
RUN wget -qO- "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" \
  | tar -xz -C /usr/local/bin gitleaks

# Hadolint
RUN wget -qO /usr/local/bin/hadolint \
  "https://github.com/hadolint/hadolint/releases/download/v${HADOLINT_VERSION}/hadolint-Linux-x86_64" \
  && chmod +x /usr/local/bin/hadolint

# Semgrep + Checkov
RUN pip3 install --no-cache-dir \
  "semgrep==${SEMGREP_VERSION}" \
  "checkov==${CHECKOV_VERSION}"

# Syft + Grype
RUN wget -qO- "https://raw.githubusercontent.com/anchore/syft/main/install.sh" | sh -s -- -b /usr/local/bin "v${SYFT_VERSION}" \
  && wget -qO- "https://raw.githubusercontent.com/anchore/grype/main/install.sh" | sh -s -- -b /usr/local/bin "v${GRYPE_VERSION}"

# Wrapper
RUN cat >/usr/local/bin/security-toolbox <<'SCRIPT' && chmod +x /usr/local/bin/security-toolbox
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="${1:-/workspace}"
OUT_DIR="${OUT_DIR:-/out}"
mkdir -p "$OUT_DIR"

semgrep scan --config auto --json --output "$OUT_DIR/semgrep.json" "$TARGET_DIR" || true

if git -C "$TARGET_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  gitleaks git --source "$TARGET_DIR" --report-format json --report-path "$OUT_DIR/gitleaks.json" || true
else
  gitleaks dir --source "$TARGET_DIR" --report-format json --report-path "$OUT_DIR/gitleaks.json" || true
fi

if [ -f "$TARGET_DIR/Dockerfile" ]; then
  hadolint "$TARGET_DIR/Dockerfile" -f json > "$OUT_DIR/hadolint.json" || true
fi

trivy fs --scanners vuln,misconfig,secret --format json --output "$OUT_DIR/trivy-fs.json" "$TARGET_DIR" || true
checkov -d "$TARGET_DIR" -o json > "$OUT_DIR/checkov.json" || true
syft "$TARGET_DIR" -o cyclonedx-json="$OUT_DIR/sbom.cdx.json" || true
grype sbom:"$OUT_DIR/sbom.cdx.json" -o json > "$OUT_DIR/grype.json" || true
SCRIPT

RUN addgroup -S scanner && adduser -S scanner -G scanner
USER scanner
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/security-toolbox"]
