Git Product home page Git Product logo

gitleaks-action's Introduction

Gitleaks

┌─○───┐
│ │╲  │
│ │ ○ │
│ ○ ░ │
└─░───┘

Github Test gitleaks badge Follow @zricethezav

Join our Discord! Discord

Gitleaks is a SAST tool for detecting and preventing hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an easy-to-use, all-in-one solution for detecting secrets, past or present, in your code.

➜  ~/code(master) gitleaks detect --source . -v

    ○
    │╲
    │ ○
    ○ ░
    ░    gitleaks


Finding:     "export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef",
Secret:      cafebabe:deadbeef
RuleID:      sidekiq-secret
Entropy:     2.609850
File:        cmd/generate/config/rules/sidekiq.go
Line:        23
Commit:      cd5226711335c68be1e720b318b7bc3135a30eb2
Author:      John
Email:       [email protected]
Date:        2022-08-03T12:31:40Z
Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/sidekiq.go:sidekiq-secret:23

Getting Started

Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the releases page. In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo or as a GitHub action using Gitleaks-Action.

Installing

# MacOS
brew install gitleaks

# Docker (DockerHub)
docker pull zricethezav/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]

# Docker (ghcr.io)
docker pull ghcr.io/gitleaks/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path ghcr.io/gitleaks/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]

# From Source (make sure `go` is installed)
git clone https://github.com/gitleaks/gitleaks.git
cd gitleaks
make build

GitHub Action

Check out the official Gitleaks GitHub Action

name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
  scan:
    name: gitleaks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}} # Only required for Organizations, not personal accounts.

Pre-Commit

  1. Install pre-commit from https://pre-commit.com/#install

  2. Create a .pre-commit-config.yaml file at the root of your repository with the following content:

    repos:
      - repo: https://github.com/gitleaks/gitleaks
        rev: v8.16.1
        hooks:
          - id: gitleaks
    

    for a native execution of GitLeaks or use the gitleaks-docker pre-commit ID for executing GitLeaks using the official Docker images

  3. Auto-update the config to the latest repos' versions by executing pre-commit autoupdate

  4. Install with pre-commit install

  5. Now you're all set!

➜ git commit -m "this commit contains a secret"
Detect hardcoded secrets.................................................Failed

Note: to disable the gitleaks pre-commit hook you can prepend SKIP=gitleaks to the commit command and it will skip running gitleaks

➜ SKIP=gitleaks git commit -m "skip gitleaks check"
Detect hardcoded secrets................................................Skipped

Usage

Usage:
  gitleaks [command]

Available Commands:
  completion  generate the autocompletion script for the specified shell
  detect      detect secrets in code
  help        Help about any command
  protect     protect secrets in code
  version     display gitleaks version

Flags:
  -b, --baseline-path string       path to baseline with issues that can be ignored
  -c, --config string              config file path
                                   order of precedence:
                                   1. --config/-c
                                   2. env var GITLEAKS_CONFIG
                                   3. (--source/-s)/.gitleaks.toml
                                   If none of the three options are used, then gitleaks will use the default config
      --exit-code int              exit code when leaks have been encountered (default 1)
  -h, --help                       help for gitleaks
  -l, --log-level string           log level (trace, debug, info, warn, error, fatal) (default "info")
      --max-target-megabytes int   files larger than this will be skipped
      --no-color                   turn off color for verbose output
      --no-banner                  suppress banner
      --redact                     redact secrets from logs and stdout
  -f, --report-format string       output format (json, csv, junit, sarif) (default "json")
  -r, --report-path string         report file
  -s, --source string              path to source (default ".")
  -v, --verbose                    show verbose output from scan

Use "gitleaks [command] --help" for more information about a command.

Commands

There are two commands you will use to detect secrets; detect and protect.

Detect

The detect command is used to scan repos, directories, and files. This command can be used on developer machines and in CI environments.

When running detect on a git repository, gitleaks will parse the output of a git log -p command (you can see how this executed here). git log -p generates patches which gitleaks will use to detect secrets. You can configure what commits git log will range over by using the --log-opts flag. --log-opts accepts any option for git log -p. For example, if you wanted to run gitleaks on a range of commits you could use the following command: gitleaks detect --source . --log-opts="--all commitA..commitB". See the git log documentation for more information.

You can scan files and directories by using the --no-git option.

If you want to run only specific rules you can do so by using the --enable-rule option (with a rule ID as a parameter), this flag can be used multiple times. For example: --enable-rule=atlassian-api-token will only apply that rule. You can find a list of rules here.

Protect

The protect command is used to scan uncommitted changes in a git repo. This command should be used on developer machines in accordance with shifting left on security. When running protect on a git repository, gitleaks will parse the output of a git diff command (you can see how this executed here). You can set the --staged flag to check for changes in commits that have been git added. The --staged flag should be used when running Gitleaks as a pre-commit.

NOTE: the protect command can only be used on git repos, running protect on files or directories will result in an error message.

Creating a baseline

When scanning large repositories or repositories with a long history, it can be convenient to use a baseline. When using a baseline, gitleaks will ignore any old findings that are present in the baseline. A baseline can be any gitleaks report. To create a gitleaks report, run gitleaks with the --report-path parameter.

gitleaks detect --report-path gitleaks-report.json # This will save the report in a file called gitleaks-report.json

Once as baseline is created it can be applied when running the detect command again:

gitleaks detect --baseline-path gitleaks-report.json --report-path findings.json

After running the detect command with the --baseline-path parameter, report output (findings.json) will only contain new issues.

Verify Findings

You can verify a finding found by gitleaks using a git log command. Example output:

Finding:     aws_secret="AKIAIMNOJVGFDXXXE4OA"
RuleID:      aws-access-token
Secret       AKIAIMNOJVGFDXXXE4OA
Entropy:     3.65
File:        checks_test.go
Line:        37
Commit:      ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
Author:      Zachary Rice
Email:       [email protected]
Date:        2018-01-28T17:39:00Z
Fingerprint: ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29:checks_test.go:aws-access-token:37

We can use the following format to verify the leak:

git log -L {StartLine,EndLine}:{File} {Commit}

So in this example it would look like:

git log -L 37,37:checks_test.go ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29

Which gives us:

commit ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
Author: zricethezav <[email protected]>
Date:   Sun Jan 28 17:39:00 2018 -0500

    [update] entropy check

diff --git a/checks_test.go b/checks_test.go
--- a/checks_test.go
+++ b/checks_test.go
@@ -28,0 +37,1 @@
+               "aws_secret= \"AKIAIMNOJVGFDXXXE4OA\"":          true,

Pre-Commit hook

You can run Gitleaks as a pre-commit hook by copying the example pre-commit.py script into your .git/hooks/ directory.

Configuration

Gitleaks offers a configuration format you can follow to write your own secret detection rules:

# Title for the gitleaks configuration file.
title = "Gitleaks title"

# Extend the base (this) configuration. When you extend a configuration
# the base rules take precedence over the extended rules. I.e., if there are
# duplicate rules in both the base configuration and the extended configuration
# the base rules will override the extended rules.
# Another thing to know with extending configurations is you can chain together
# multiple configuration files to a depth of 2. Allowlist arrays are appended
# and can contain duplicates.
# useDefault and path can NOT be used at the same time. Choose one.
[extend]
# useDefault will extend the base configuration with the default gitleaks config:
# https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml
useDefault = true
# or you can supply a path to a configuration. Path is relative to where gitleaks
# was invoked, not the location of the base config.
path = "common_config.toml"

# An array of tables that contain information that define instructions
# on how to detect secrets
[[rules]]

# Unique identifier for this rule
id = "awesome-rule-1"

# Short human readable description of the rule.
description = "awesome rule 1"

# Golang regular expression used to detect secrets. Note Golang's regex engine
# does not support lookaheads.
regex = '''one-go-style-regex-for-this-rule'''

# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''

# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]

# Int used to extract secret from regex match and used as the group that will have
# its entropy checked if `entropy` is set.
secretGroup = 3

# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
entropy = 3.5

# Keywords are used for pre-regex check filtering. Rules that contain
# keywords will perform a quick string compare check to make sure the
# keyword(s) are in the content being scanned. Ideally these values should
# either be part of the idenitifer or unique strings specific to the rule's regex
# (introduced in v8.6.0)
keywords = [
  "auth",
  "password",
  "token",
]

# You can include an allowlist table for a single rule to reduce false positives or ignore commits
# with known/rotated secrets
[rules.allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = [
  '''go\.mod''',
  '''go\.sum'''
]
# note: (rule) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
  '''process''',
  '''getenv''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
  '''client''',
  '''endpoint''',
]


# 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 allow list"
commits = [ "commit-A", "commit-B", "commit-C"]
paths = [
  '''gitleaks\.toml''',
  '''(.*?)(jpg|gif|doc)'''
]

# note: (global) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"

regexes = [
  '''219-09-9999''',
  '''078-05-1120''',
  '''(9[0-9]{2}|666)-\d{2}-\d{4}''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
  '''client''',
  '''endpoint''',
]

Refer to the default gitleaks config for examples or follow the contributing guidelines if you would like to contribute to the default configuration. Additionally, you can check out this gitleaks blog post which covers advanced configuration setups.

Additional Configuration

gitleaks:allow

If you are knowingly committing a test secret that gitleaks will catch you can add a gitleaks:allow comment to that line which will instruct gitleaks to ignore that secret. Ex:

class CustomClass:
    discord_client_secret = '8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ'  #gitleaks:allow

.gitleaksignore

You can ignore specific findings by creating a .gitleaksignore file at the root of your repo. In release v8.10.0 Gitleaks added a Fingerprint value to the Gitleaks report. Each leak, or finding, has a Fingerprint that uniquely identifies a secret. Add this fingerprint to the .gitleaksignore file to ignore that specific secret. See Gitleaks' .gitleaksignore for an example. Note: this feature is experimental and is subject to change in the future.

Sponsorships

CodeRabbit.ai Sponsorship

Tines Sponsorship

Exit Codes

You can always set the exit code when leaks are encountered with the --exit-code flag. Default exit codes below:

0 - no leaks present
1 - leaks or error encountered
126 - unknown flag

gitleaks-action's People

Contributors

adamdecaf avatar codykhon avatar crazy-matt avatar ericcornelissen avatar gmti-bwhyle avatar hehex9 avatar niall-byrne avatar spaze avatar weineran avatar yuasabe avatar zricethezav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gitleaks-action's Issues

Action version 1.1.4 still uses --pretty flag with gitleaks 7.0.0+

Hi 👋
Looks like the gitleaks v7.0.0 removed the --pretty flag. Unfortunately the action version 1.1.4 uses the latest image version but still includes the --pretty flag, so it breaks:

running gitleaks v7.1.0 with the following command👇
gitleaks --pretty --repo-path=/github/workspace --verbose --redact --commit=e0ec22ec6c76b425ad7c49ebb559f93a6520d966
unknown flag `pretty'
Usage:
  gitleaks [OPTIONS]
...

Sample run: https://github.com/giantswarm/hyperkube/runs/1525377670?check_suite_focus=true

edit: As a side note, I'm not sure if this is intentional behavior but it surprised me that this didn't fail the build

not working when creating pull request from different repository

shows a message in output (and not exit the job)

fatal: ambiguous argument 'remotes/origin/master...remotes/origin/gitleaks': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Because when creating pull request through a different repository, there won't be any remote/origin/gitleaks. This line is the source of the problem.

My suggestion are below, already tested on my local machine (but not very sure if there are any other edge cases that i missed), what do you think ?

-git --git-dir="$GITHUB_WORKSPACE/.git" log --left-right --cherry-pick --pretty=format:"%H" remotes/origin/$GITHUB_BASE_REF...remotes/origin/$GITHUB_HEAD_REF > commit_list.txt
+git --git-dir="$GITHUB_WORKSPACE/.git" log --left-right --cherry-pick --pretty=format:"%H" remotes/origin/$GITHUB_BASE_REF... > commit_list.txt

btw thanks for your awesome work on gitleaks 🤘

Can not install gitleaks for selfhosted runner (Destination file path /tmp/gitleaks.tmp already exists)

I understand this is meant to be used with docker, but perhaps it would be an idea to try to remove gitleaks.tmp from tmp before or after download and extraction?

For our self-hosted runner we fixed this by removing /tmp/gitleaks.tmp before running gitleaks-action

e.g:

  - name: Remove gitleaks from tmp if it exist
    run: rm -f /tmp/gitleaks.tmp || echo "gitleaks.tmp has already been removed."
gitleaks version: 8.18.0
Version to install: 8.18.0 (target directory: /tmp/gitleaks-8.18.0)
Downloading gitleaks from https://github.com/zricethezav/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz
Destination file path /tmp/gitleaks.tmp already exists
Waiting 19 seconds before trying again
Destination file path /tmp/gitleaks.tmp already exists
Waiting 17 seconds before trying again
Error: could not install gitleaks from https://github.com/zricethezav/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz, error: Error: Destination file path /tmp/gitleaks.tmp already exists
/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:86[12](https://github.com/AdmincontrolAS/unicorn/actions/runs/6705241157/job/18219262014?pr=8355#step:3:13)
            throw new Error("parameter 'file' is required");
                  ^

Error: parameter 'file' is required
    at Object.<anonymous> (/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:8612:19)
    at Generator.next (<anonymous>)
    at /actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:8411:71
    at new Promise (<anonymous>)
    at __webpack_modules__.7784.__awaiter (/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:8407:12)
    at Object.extractTar (/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:8610:12)
    at Object.Install (/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:70516:16)
    at async start (/actions-runner/_work/_actions/AdmincontrolAS/gitleaks-action/v2/dist/index.js:7[13](https://github.com/AdmincontrolAS/unicorn/actions/runs/6705241157/job/18219262014?pr=8355#step:3:14)42:[22](https://github.com/AdmincontrolAS/unicorn/actions/runs/6705241157/job/18219262014?pr=8355#step:3:23))

License key validation failed all of a sudden

Problem

As of this morning, we started receiving the follow error from this GitHub Action:

Error: Validating key returned [{"meta":{"id":"b5c054e8-4f0f-4197-9258-e60653c980b4"},"errors":[{"title":"Internal server error","detail":"Looks like something went wrong! Our engineers have been notified. If you continue to have problems, please contact [email protected]."}]}]

Our GitLeaks License Key hasn't changed in 3 months. This also popped up after having successful runs earlier this morning.

Version

gitleaks/gitleaks-action@1f2d10fb689bc07a5f56f48d6db61f5bbbe772fa # v2.3.2

False leak reported "AWS Access Key"?

Describe the bug
I believe gitleaks-action is producing a false alarm

To Reproduce
Both of these repos were passing when i added the action on Jan 30, 2021. Then on Feb 22, 2021 after no significant changes in content. Both repos failed. Here are the logs from two of our repos.

  1. repo1
  2. repo2

Expected behavior
This image the leak is relating to in repo1 is produced using R code. Not sure why this would be considered a leak although it is reporting an AWS Access Key. The leak in repo2 seems to be related to a travis CI key.

Screenshots
See links above

Basic Info

  • Gitleaks Version: 7.2.2

cc @zricethezav

Ignoring yarn.lock

Hey there, I'm having trouble finding documentation whether related explicitly to gitleaks or Github actions with regards to ignoring the yarn.lock file generated automatically. It's throwing errors when running that file, it seems like it's seeing the hashes and not liking them:

image

Any thoughts? Thanks

v1.3.0+ scans entire history on push

Following this PR, the behavior on push is to scan the entire history, which I think is not actually intended.

In this PR, for example, two gitleaks jobs run - one for pull_request and one for push. The PR job is both much faster (14s vs 1m) and also passes, while the push job fails due to a very old match.
image

I'm not sure what the perfect way forward is. I can understand the use case of wanting to scan multiple pushed commits, but for performance and to limit the effort for users I think it should still be bounded to only those commits. On a PR branch it is clear how far back to scan, but it's harder when committing directly to a branch. Maybe a better git wizard than I has an idea?

cc @niall-byrne @zricethezav

merge_group event

Hi
Is there any plan to support the merge_group Github Action event?

Cheers

Failed with Self hosted GitHub Runner

I am using a self-hosted GitHub Runner.
But when I run Git Leaks it through error to write and upload artifacts on GitHub

12:23PM DBG 1 commits scanned. Note: this number might be smaller than expected due to commits with no additions
12:23PM INF scan completed in 67.3ms
12:23PM WRN leaks found: 2
Starting artifact upload
For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging
Artifact name is valid!
/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:1857
                throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`);
                      ^

Error: The rootDirectory: /home/runner is not a parent directory of the file: /runner/_work/fe-app/fe-app/results.sarif
    at Object.getUploadSpecification (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:1857:23)
    at DefaultArtifactClient.<anonymous> (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:83:64)
    at Generator.next (<anonymous>)
    at /runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:[53](https://github.com/org/fe-app/actions/runs/5999759253/job/16270522345#step:4:54):71
    at new Promise (<anonymous>)
    at __webpack_modules__.8802.__awaiter (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:49:12)
    at DefaultArtifactClient.uploadArtifact (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:78:16)
    at Object.Scan (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:70[59](https://github.com/org/fe-app/actions/runs/5999759253/job/16270522345#step:4:60)0:26)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async start (/runner/_work/_actions/gitleaks/gitleaks-action/v2/dist/index.js:713[63](https://github.com/org/fe-app/actions/runs/5999759253/job/16270522345#step:4:64):16)

Also I am looking for an exit code in case leaks are found to Trigger Slack notifications which I am not able to do so.

GitHub Action Workflow file

name: gitleaks
on:
  pull_request:
    branches:
      - main
      - develop
      
  push:
    branches:
      - main
      - develop
jobs:
  scan:
    permissions:
      contents: write
      pull-requests: write
      checks: write
    name: gitleaks
    runs-on:
      labels: [self-hosted,dev-image-builder]
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: gitleaks/gitleaks-action@v2
        id: gitleaks
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}

    
      - name: Notify Token Detected
        if:  steps.gitleaks.outputs.exitcode == 1
        uses: voxmedia/github-action-slack-notify-build@v1
        id: slack-token-notify
        with:
          channel_id: ${{ secrets.SLACK_CHANNEL_ID }}
          status: Token Detected. Check Report at workflow.
          color: warning
        env:
          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}

cc @zricethezav

How do I pass options to the action?

Hello!

I'm using gitleaks as a docker and also installed with brew. There I can pass options to the scan, such as--no-git, --verbose and others.

Is there a way to do so with this GitHub action?

I'm quite new to it, saw nothing in the readme nor open issues.

thank you!

Gitleaks Summary Generated Urls Broken

Heyo!

The gitleaks summary is generating urls that are broken for all my private Org repos for all workflow event types.

The Url generated for example is https://github.com///actions/runs/undefined/commit/21f3bb48c90c82c688feb801ed5d539a6472273b

If I take out the "actions/runs/undefined" part of the url it seems to at least land on the commit page.

Any ideas whats happening here?

It seems odd because the url seems like it should be created based off eventJSON.repository.html_url and when I view that in the pipeline it looks correct without the actions/runs/undefined bit added.

Feature Request: input to allow for report format / location

Allow user input to choose the report output and format.

The main reason for this would be to opt in to use the sarif format for integration with Github Security tab - but of course would be useful to create artifacts in various formats for different purposes.

Ideally then combine with an output for the file location too

Improve error message for MACHINE_LIMIT_EXCEEDED failure

When a user tries to activate too many repositories on their license, they get a message like this:

❗ this repo has not been associated with the license, attempting to activate a repo for the license
🛑 Activation request returned [1] errors:
🛑 Error activating repo: MACHINE_LIMIT_EXCEEDED | Unprocessable resource | machine count has exceeded maximum allowed by current policy (10) | /data | 

We should improve this error message to read something like this:

Failed to activate repo [org123/repo456]. License has already reached its limit of [N] repos: [list, of, repos]. If you would like to increase your limit or remove some of these repos from your license, please do not hesitate to contact us.

GitHub action on pull_request keep on scanning previous commits

Hi I have tried this workflow yaml in GitHub action
name: gitleaks
on: [pull_request, workflow_dispatch]
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}} #

But this workflow keep on scanning previous commits and finding the secrets which I have already deleted in the previous commits. How to make above yaml to scan only the latest commit

GITLEAKS_NOTIFY_USER_LIST - does not work while setting up the workflow as a reusable workflow

I have setup the workflow env as in the main workflow and the "GITLEAKS_ENABLE_UPLOAD_ARTIFACT" is working as expected and no sarif is being uploaded with the action. However, GITLEAKS_NOTIFY_USER_LIST does not work as expected as gitleaks is not putting a comment ccing the user defined in input1. In fact, it does not do any comment.

env:
GITLEAKS_NOTIFY_USER_LIST: ${{ inputs.input1 }}
GITLEAKS_ENABLE_UPLOAD_ARTIFACT: ${{ inputs.input2 }}

Action not working on reusable workflows

When calling the gitleaks action from a reusable workflow the following error is received:

TypeError: Cannot read properties of undefined (reading 'commitSha')
    at /home/runner/work/_actions/gitleaks/gitleaks-action/v2.3.2/dist/index.js:70938:52
    at Array.forEach (<anonymous>)
    at Object.Write (/home/runner/work/_actions/gitleaks/gitleaks-action/v2.3.2/dist/index.js:70937:27)
    at start (/home/runner/work/_actions/gitleaks/gitleaks-action/v2.3.2/dist/index.js:71385:19)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Seems like the GITHUB_EVENT_PATH is working on the subworkflow event path.

Can't use 'tar -xzf' extract archive file. return code: 2.

Hi, since today my Gitleaks runs are all failing with an error message similar to this:

Can't use 'tar -xzf' extract archive file: /home/runner/work/_actions/_temp_0ff29a0b-45d3-43d7-9e97-4bbf29eecf79/77956855-4854-4a8d-b3f9-9c2cda3025e6.tar.gz. return code: 2.

My workflow file wasn't changed:

name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}
GITLEAKS_CONFIG: gitleaks/rules.toml

Can somebody help?

Thank you!

Allow setting the .gitleaks.toml configuration file path

I'd like to include the .gitleaks.toml in my github actions directory rather than put this in the root of the repository, allowing easier management of workflows and sharing with my team.

Can this be an optional parameter please?

Track timestamp of last repo scan for more billing flexibility

Background
Currently, we are tracking "Last Validation" for each license (via keygen). However, when multiple repos are associated with a license, which is usually the case, we don't know which / how many repos were scanned at that Last Validation time.

New Feature
We should track the most recent timestamp that each repo was scanned as well. That would enable somewhat more flexible billing options such as "pay per repo, if scanned".

Additional Info

  • The original motivation for this issue was a request from @dopey for usage-based pricing. I have a call with him next week to discuss his requirements in more detail.
  • Not included in this issue, but possible future work:
    • Counting how many times each repo is scanned
    • Counting how many lines of code (or chars or bytes) were scanned

CC @zricethezav

Cannot configure repository path

If the checkout action is performed with a given path, the gitleaks action won't work as it runs on a different path. As the "working-directory" param doesn't work with "uses", could the path be set as input param?

` - name: Checkout code
uses: actions/checkout@v2
with:
path: ./src/github.com/${{ github.repository }}

- name: Git Leaks 
  uses: zricethezav/gitleaks-action@master`

This action uses old version (v4.1.0) gitleaks which may wrongly report token leaks. Wait for image update(to v6.1.0).

We introduced gitleaks in our internal repository for check, it works well. However, recently we got a problem with gitleaks.

A complex JSON file is wrongly reported token leaks by gitleaks-action(which uses v4.1.0), but we run the gitleaks command on our local machine(with gitleaks version: v6.0.0), the result is without token leaks. We repeated this problem by using docker-hosted gitleaks v4.1.0.

So we are waiting for the official update to fix this problem.

Though update toml config may also works, but it's better to solve this problem rootly.

Thanks!

Problem when adding workflow_dispatch

I'd like this action to scan for more than just the last commit, so I forked it to scan all code (not commits). After adding a new action, I wanted to create a selection for users to select via input:
'last_commit' - Scan the last commit
'whole_repo' - Scan the entire repository

When I use workflow_dispatch with this selection, the main action scans all commits, so previous leaks are detected and the action fails every time.

Is this the expected behavior of this action?
Is it possible to configure this action to scan code, not commits?

GitLeaks making Error with "Invalid revision range"

Hello,
I would like to report an issue where GitLeaks CI fails with the error Invalid revision range.

Reproduction steps:

  1. Create a PR with a commit to a target branch that runs GitLeaks on PRs
  2. Instantly, create a new commit on the source branch
  3. Notice the GitLeaks CI check fails on the 1st commit with similar to below details:
[...]
7:30AM DBG executing: /usr/bin/git -C . log -p -U0 --no-merges --first-parent a833a[...]^..ea4e0[...]
7:30AM ERR [git] fatal: Invalid revision range a833a[...]^..ea4e0[...][27](https://github.com/xxxxx#step:5:28)
7:30AM DBG 0 commits scanned. Note: this number might be smaller than expected due to commits with no additions
7:30AM ERR git error encountered, see logs
7:30AM WRN partial scan completed in 60.2ms
7:30AM WRN no leaks found in partial scan
[...]

This issue seems like a race-condition to me where the GitLeaks initiated on the 1st commit but also got the details of the latest commit but git log does not have the details about the latest commit.

Root Cause:
I also did some analysis:
1st commit: a833a --> Initiated the GitLeaks CI --> Fails with Invalid revision range error
2nd commit: ea4e0 (note that this commit should be instantly after the 1st commit so that GitLeaks gets confused) --> Initiated the GitLeaks CI --> Pass (obv if no leak found)

Now notice, GitLeaks on the 1st commit has the Invalid revision range error, and looking in detail you will find out that it also has the commit address of the 2nd commit. How is that possible?

cc/ @weineran @zricethezav

Thanks!

Announcement: Upcoming breaking update

📢 Announcement

6/13/2022

On June 2, 2022, we released Gitleaks Action v2. There are a boatload of improvements in v2, but it also represents a breaking change from the prior version (v1.6.0). We haven't merged v2 to the master branch yet because we noticed that many users of Gitleaks Action don't pin their version. If you are using zricethezav/gitleaks-action@master (or now gitleaks/gitleaks-action@master), then as soon as we merge v2 to master, your jobs will start failing.

We are planning to complete the merge on June 20, 2022. We recommend updating your .yml files to use v2 now so you aren't scrambling to do it after your gitleaks-action jobs start failing. As an alternative, you can pin your version to v1.6.0 for now, if you aren't ready to upgrade at the moment.

How to upgrade to v2

For full details, see the v2 README here: https://github.com/gitleaks/gitleaks-action/tree/v2. Here is the quick list of changes to your .yml:

  • Change the "uses" line to - uses: gitleaks/gitleaks-action@v2
  • Add an env: section with GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  • If you are scanning repos that belong to an organization, you'll also have to acquire a GITLEAKS_LICENSE, add the license to your GitHub Secrets, and add this line to the env: section: GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}

How to pin to v1.6.0

  • Change your "uses" line to gitleaks/[email protected]
  • Set a reminder to upgrade to v2 later.

Pull requests getting stuck waiting for status to be reported

Hi,

I've been using successfully Gitleaks checks in my repos for a long time, but lately my PRs are getting stuck waiting for "Gitleaks report to be reported". After further investigation, it appears that no checks were run on the PR, though Gitleaks is still waiting for the report. It looks like GitHub is responding as it should. This started to happen about one month ago and keep happening. This lead me in disabling Gitleaks as a required status checks to be able to work. I was wondering if someone could help me solve this problem...I did not change both my workflow and rules files below during this period, which are pretty basic:

Workflow file:

name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
  scan:
    name: gitleaks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
          GITLEAKS_CONFIG: path/rules.toml

Rules file:

title = "Gitleaks Config File"

[extend]
useDefault = true

[allowlist]
description = "global allow list"

paths = [
  '''path/rules.toml'''
]

stopwords = [
]

image

Thank you,
Igor

pass checkout path?

It seems that action does not support passing path with usual with: path: ...
my checkout is in a subfolder and action failed because not a git repo

https://github.com/juju4/ansible-adduser/actions/runs/4151619785/jobs/7182030614#step:12:26

1:40PM DBG no gitleaks config found in path .gitleaks.toml, using default gitleaks config
1:40PM DBG executing: /usr/bin/git -C . log -p -U0 --no-merges --first-parent 7c0c0e648f21bea1575b57aba8091c8f2c705e06^..da271afad6e5b5d769a7bdf1c654fb1ea32942c1
1:40PM ERR [git] fatal: not a git repository (or any of the parent directories): .git
1:40PM DBG 0 commits scanned. Note: this number might be smaller than expected due to commits with no additions

config
https://github.com/juju4/ansible-adduser/blob/da271afad6e5b5d769a7bdf1c654fb1ea32942c1/.github/workflows/lint.yml#L74

    steps:
      - uses: actions/checkout@v2
        with:
          path: ${{ env.ANSIBLE_ROLE }}
[...]
      - name: Gitleaks check
        uses: gitleaks/gitleaks-action@1f2d10fb689bc07a5f56f48d6db61f5bbbe772fa
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_ENABLE_SUMMARY: true
          GITLEAKS_ENABLE_COMMENTS: true
          GITLEAKS_ENABLE_UPLOAD_ARTIFACT: false
        with:
          path: ${{ env.ANSIBLE_ROLE }}

Action passes even if git log fails

Hi, when setting up the action for PRs I noticed that with the fetch-depth: '2' recommended in the marketplace description (https://github.com/marketplace/actions/gitleaks very bottom), the git log fails due to not having the target ref cloned, logging: fatal: ambiguous argument 'remotes/origin/main...': unknown revision or path not in the working tree., but the action step as a whole succeeds, hiding potential issues in the PR. fetch-depth: '0' solves this problem although with a large history the clone may still be inefficient as the description says.

I'd expect the action as a whole to fail if it's not able to scan anything. If a similar problem appears again, it might silently fail to report problematic commits, and because it typically only scans new commits, those that slipped may not be easily discovered again.

I've set up a minimal repro, here is an example of this behavior in a PR build https://github.com/jbrestan/gitleaks-repro/runs/2965724359?check_suite_focus=true#step:4:6

Overriding / merging config

Is there an existing way to override or merge config?

I have a use-case where we have an organisation wide configuration for gitleaks. For some repositories we need to add additional configuration or add an allowlist to an existing rule.

Currently we have to duplicate the configuration for these repositories - which means that they will become out of date if we add additional rules for the organisation configuration in the future.

Getting "encountered leaks" from unknown code

I just cloned the recent gitleaks-action repo and modified the workflows yml file to point to my personal repo and tried running a push but it keeps failing with gitleaks encountering leaks but it's point to code that I have no idea where they're coming from. Below is a snip of the error - it's pointing to the entrypoint.sh file but the linenumber and code is not accurate. Please help.

🛑 STOP! Gitleaks encountered leaks

{
"line": "# aws_access_key_id='REDACTED' ",
"lineNumber": 16,
"offender": "REDACTED",
"commit": "e7150a87e012d353a2c2e1ca8ec832b036dbde40",
"repo": "workspace",
"repoURL": "",
"leakURL": "",
"rule": "AWS Manager ID",
"commitMessage": "Update entrypoint.sh",
"author": "Zachary Rice",
"email": "[email protected]",
"file": "entrypoint.sh",
"date": "2020-02-25T11:06:44-05:00",
"tags": "key, AWS"
}
{
"line": "# aws_access_key_id='REDACTED'",
"lineNumber": 18,
"offender": "REDACTED",
"commit": "e1a5408dec0df17125c6a2e4bc57fa56e1296e7d",
"repo": "workspace",
"repoURL": "",
"leakURL": "",
"rule": "AWS Manager ID",
"commitMessage": "Update entrypoint.sh",
"author": "Zachary Rice",
"email": "[email protected]",
"file": "entrypoint.sh",
"date": "2020-02-25T10:53:36-05:00",
"tags": "key, AWS"
}

GitHub Action does not apply gitleaks.toml rules

Given the following gitleaks-action file placed in .github/workflows on my GitHub project

name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
  scan:
    name: gitleaks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}

The GitHub action does not find my gitleaks.toml file placed at the root of the project even if this page says it will.

Defined the gitleaks.toml file elsewhere and precising through GITLEAKS_CONFIG env variable where to find it, the GitHub action just ignores it.

gitleaks.toml is like bellow:

[[rules]]
  description = "Detect Some Service key in URL"
  regex = '''(?i)apikey=([a-zA-Z0-9_-]{10})'''

and is working with gitleaks in CLI.

How make the GitHub Actions use the rules of the TOML file?

Feature Request: Consider adding a floating major version tag

Hey @zricethezav,

Would you consider adding the support for a floating major version tag like in actions/checkout? ie: zricethezav/gitleaks-action@v1

The reason behind this request is I'm trying to enforce running gitleaks in hundreds of repositories and would like to benefit from a fairly stable up-to-date tag of your action without having to pin to a specific version or master/main.

Trying to run gitleaks only on last commit

This is my yaml:

name: gitleaks

on: [pull_request]

jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: '0'
      - name: gitleaks-action
        uses: zricethezav/gitleaks-action@master

If i got some leaks in my code and delete it and commit again it's still failed (it's run on all the commits history).
Itried to change fetch-depth to '' or '1' or '2' but when i do it it don't check any commit.
How can i change it to work only on last commit?

incorrectly constructed download URL for some architectures

running the gitleaks action on my self-hosted ARM7 runner fails:

log snippet:

2023-07-19T04:36:09.9024034Z [bwhitehead0] is an individual user. No license key is required.
2023-07-19T04:36:09.9048238Z gitleaks version: 8.12.0
2023-07-19T04:36:09.9086434Z Version to install: 8.12.0 (target directory: /tmp/gitleaks-8.12.0)
2023-07-19T04:36:10.6016829Z Downloading gitleaks from https://github.com/zricethezav/gitleaks/releases/download/v8.12.0/gitleaks_8.12.0_linux_arm.tar.gz
2023-07-19T04:36:11.0949685Z ##[error]could not install gitleaks from https://github.com/zricethezav/gitleaks/releases/download/v8.12.0/gitleaks_8.12.0_linux_arm.tar.gz, error: Error: Unexpected HTTP response: 404
2023-07-19T04:36:11.1353564Z /home/github-runner/actions-runner/_work/_actions/gitleaks/gitleaks-action/v2.3.2/dist/index.js:8612

in this case, it appears that this code block might need to be modified to account for ARM variants:

    const gitleaksReleaseURL = downloadURL(
      process.platform,
      process.arch,
      version
    );

i'm not very familiar w/ node, but it appears we need to do something similar to this comment to properly construct the download URL for some ARM variants, or, find another way to determine architecture type is ARM, then poll the OS thru node to determine if it's arm64, arm6, or arm7.

os.cpus() (model) should report the ARM version:

node -p "os.cpus()"    
[ { model: 'ARMv7 Processor rev 5 (v7l)',
    speed: 900,
    times:
     { user: 28061900,
       nice: 1726100,
       sys: 41051200,
       idle: 3227428,
       irq: 0 } },
...

wish i could offer more but node isn't my thing.

Support running gitleaks-action on schedule

I recently added this Action to a workflow that, besides triggering on pushes and Pull Requests, also runs on a schedule. Then I discovered this is currently not supported (see this run, for example). It seems this is failing at:

const githubUsername = eventJSON.repository.owner.login;

due to the repository property missing from the eventJSON.

If it's possible to fix the above issue, I must admit I'm not 100% sure what supporting the schedule trigger would mean for gitleak-actions. I think it could be leveraged to perform a historic scan?

If a historic scan isn't an option, I would like to suggest documenting which triggers are supported and providing a proper error message for unsupported triggers (e.g. by checking the value of GITHUB_EVENT_NAME and exiting with an error message when it's not "push", "pull_request", or "workflow_dispatch").

Gitleaks keeps on scanning previous commit shas even if the secret/key has been removed

In my workflow when I use the gitleaks action it works and scans the file for the first time.
Next build when I remove the secret from the repo then too the action refers to the previous commit sha and fails the build saying that the repo still has secrets/keys.

To Reproduce
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:

  • uses: actions/checkout@v2
    with:
    fetch-depth: '0'
  • name: gitleaks-action
    uses: zricethezav/gitleaks-action@master

test.txt AKIAIOSFODNN7EXAMPLE

cc @zricethezav

Feature Request: Define output variables for step

Can you set an output variable to the action for the gitleaks finding?

Use case: Write the output back to comments for the commit.

Output lines of interest:
INFO[2020-08-28T15:21:36Z] No leaks detected. 1 commits scanned in 0 seconds
✅ SUCCESS! Your code is good to go!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.