Add support for running container-scanning with arbitrary userIDs (OpenShift)

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

Summary

Container-scanning image does not work in rootless environments with arbitrary user ids (OpenShift).

OpenShift runs containers with arbitrary user id's, but part of the root group. Trying to run the container scanning template without any modifications will for now return the following error message:

2024-06-12T14:31:37.967Z DEBUG There is no valid metadata file: unable to open a file: open /home/gitlab/.cache/trivy/ce/db/metadata.json: no such file or directory

This error happens due to any issues when extracting the compressed Trivy database from /tmp to /home/gitlab/.cache/trivy/{ee|ce}}/db at runtime. In this case it is caused by missing write-permissions on the /home/gitlab directory

$ ls -lh
total 0
drwxr-xr-x. 1 gitlab root 21 Jun 11 16:04 gitlab
drwxr-xr-x. 3 root   root 45 Jun 12 14:42 mobsf
$ id
uid=1004750000(1004750000) gid=0(root) groups=0(root),1004750000
$ touch /home/gitlab/test
touch: cannot touch '/home/gitlab/test': Permission denied

Steps to reproduce

Include the container-scanning templates in .gitlab-ci.yml, and try to run on Gitlab Runner in rootless environment with arbitrary user id (like OpenShift).

include:
- template: Jobs/Container-Scanning.gitlab-ci.yml

Possible fixes

Ref. OpenShift documentation, we can set directory and file permissions to be writeable by the root group:

# This is added somewhere in the Dockerfile
(...)
USER root

RUN chgrp -R 0 /home/gitlab && \
    chmod -R g+rwX /home/gitlab

RUN chgrp -R 0 /tmp && \
    chmod -R g+rwX /tmp

USER gitlab

(...)

The following example pipeline will then work in OpenShift/rootless environments:

stages:
#- build # build image step
- test
- container-scan

include:
- template: Jobs/Container-Scanning.gitlab-ci.yml
 
container_scanning:
  # needs: [ "build" ]
  stage: container-scan
  image: # container-scanning image with the fix
  before_script:
   - cp /home/gitlab/.bashrc /builds/.bashrc
  variables:
    CS_IMAGE: ${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA} # refer to the image youre building in previous steps

Note that an admin has set the runners default HOME directory to be /builds and mounted an emptyDir on it. If HOME is set to /home/gitlab, the runner helper image must also be wrapped, ref. this issue

The before_step is therefore required in this case, as the current extraction-method of the trivy-db assumes that HOME is /home/gitlab.

I wonder if you are willing to accept an MR to give the root-group execute/write permissions in the following directories: /home/gitlab, /tmp". Or if you have other plans to address this issue?

Edited by 🤖 GitLab Bot 🤖