Search code examples
gitlabgitlab-cimerge-requestgitleakssecrets

GitLab Secrets Detection - Pipeline doesn't fail - Only checks last commit


In order to implement secrets detector via pipeline on merge requests in my GitLab repository, I followed this document from GitLab here: "Enable Secret Detection | Edit the .gitlab.ci.yml file manually"

But the pipeline doesn't fail if any secrets are detected. Also, it just checks the last commit in the merge request which makes it useless.

How to handle both issues?


Solution

  • I created a file named .gitlab-ci.yml on the root level in the repository using the following code:

    include:
    - template: Security/Secret-Detection.gitlab-ci.yml
    
    secret_detection:
      extends: .secret-analyzer
      rules:
        - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      variables:
        GIT_DEPTH: 100
        SECRET_DETECTION_LOG_OPTIONS: ${CI_MERGE_REQUEST_DIFF_BASE_SHA}..${CI_COMMIT_SHA}
      script:
        - apk add jq
        - /analyzer run
        - NUMBER_OF_VULNERABILITIES=$(cat gl-secret-detection-report.json | jq --raw-output '.vulnerabilities | length')
        - if [[ $NUMBER_OF_VULNERABILITIES -gt 0 ]]; then exit "1"; fi
      allow_failure: false
    

    This code not only fails the pipeline if any secret is detected but also checks all the commits in the source branch of the merge request till last commit.


    Bonus: If you want to skip ignorable secrets, you can add .gitleaks.toml file on the root level of repository as follows:

    title = "Custom Gitleaks Config"
    
    [extend]
    # useDefault will extend the base configuration with the default gitleaks config:
    useDefault = true
    
    # This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
    # If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
    # secrets will be detected for said commit. The same logic applies for regexes and paths.
    [allowlist]
    description = "Global allowlist having paths, regexes and stopwords to skip"
    
    paths = [
      '''gitleaks\.toml''',
    ]
    
    regexes = [
      '''KeyToken=a12b3c456789d012''',
    ]
    
    stopwords = [
        '''123456789''',
    ]