---
variables:
  TRIVY_SEVERITIES: HIGH,CRITICAL # comma-separated list of severities to fail on (LOW,MEDIUM,HIGH,CRITICAL)
  TRIVY_USERNAME: ${CI_REGISTRY} # Needed for images only
  TRIVY_PASSWORD: ${CI_REGISTRY_USER} # Needed for images only

.trivy:
  image:
    name: aquasec/trivy
    entrypoint: [""]

.trivy:image:
  extends: .trivy
  script:
    - |
      if [ -z $TRIVY_TARGET ]; then
        TRIVY_TARGET=${IMAGE_NAME:-${CI_REGISTRY_IMAGE}}:${IMAGE_DEV_TAG:-${IMAGE_TAG:-latest}}
      fi
    - >
      echo "[*] Target image: ${TRIVY_TARGET}"
    - trivy image $TRIVY_IMAGE_ARGS $TRIVY_TARGET --output
      ${CI_PROJECT_DIR}/trivy.txt
    - cat ${CI_PROJECT_DIR}/trivy.txt
    - |
      if $(grep -qE ${TRIVY_DENYLIST_REGEX:-CVE-xxx} ${CI_PROJECT_DIR}/trivy.txt); then
        echo "[!] Detected vulnerability that matches provided TRIVY_DENYLIST_REGEX: ${TRIVY_DENYLIST_REGEX}."
        exit 1
      fi
    - |
      if ! trivy image $TRIVY_IMAGE_ARGS $TRIVY_TARGET --exit-code 1 --severity $TRIVY_SEVERITIES &>/dev/null; then
        echo "[!] Detected vulnerabilities with severity $TRIVY_SEVERITIES."
        exit 1
      fi
    - echo "[+] Found no vulnerabilities with severity $TRIVY_SEVERITIES."
  artifacts:
    paths:
      - trivy.txt

.trivy:sbom:
  extends: .trivy
  script:
    - trivy sbom $TRIVY_SBOM_ARGS $TRIVY_TARGET --output
      ${CI_PROJECT_DIR}/trivy.txt
    - cat ${CI_PROJECT_DIR}/trivy.txt
    - |
      if $(grep -qE ${TRIVY_DENYLIST_REGEX:-CVE-xxx} ${CI_PROJECT_DIR}/trivy.txt); then
        echo "[!] Detected vulnerability that matches provided TRIVY_DENYLIST_REGEX: ${TRIVY_DENYLIST_REGEX}."
        exit 1
      fi
    - |
      if ! trivy sbom $TRIVY_SBOM_ARGS $TRIVY_TARGET --exit-code 1 --severity $TRIVY_SEVERITIES &>/dev/null; then
        echo "[!] Detected vulnerabilities with severity $TRIVY_SEVERITIES."
        exit 1
      fi
    - echo "[+] Found no vulnerabilities with severity $TRIVY_SEVERITIES."
  artifacts:
    paths:
      - trivy.txt
