# trivy is a vulnerability scanner for container images
# https://github.com/aquasecurity/trivy

# Optional variables:
# TRIVY_EXIT_CODE: defaults to 1; the exit code used for the HIGH,CRITICAL severity check

docker:trivy:
  stage: test
  image: docker:stable
  variables:
    IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
    DOCKER_DRIVER: overlay2  # Default vfs is slow
  services:
    - name: docker:dind
      entrypoint: ["env", "-u", "DOCKER_HOST"]
      command: ["dockerd-entrypoint.sh"]
  before_script:
    - export TRIVY_VERSION=$(wget -qO - "https://api.github.com/repos/aquasecurity/trivy/releases/latest" | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')
    - echo $TRIVY_VERSION
    - wget --no-verbose https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz -O - | tar -zxvf -
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - ./trivy --exit-code 0 --cache-dir .trivycache/ --no-progress --format template --template "@contrib/junit.tpl" -o junit-report.xml $IMAGE
    - ./trivy --exit-code ${TRIVY_EXIT_CODE:-1} --cache-dir .trivycache/ --no-progress --ignore-unfixed --severity HIGH,CRITICAL $IMAGE
  artifacts:
    reports:
      junit: junit-report.xml
  cache:
    key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
    paths:
      - .trivycache/
