Files
gitleaks/cmd/generate/config/main.go
T
bplaxcoandAlex Layne 782f310478 Archive support (#1872)
* Start Files Source

* Keep cmd the same for now

* Get tests to pass

* s.MaxTargetMegaBytes -> s.MaxFileSize

* Tweak some log messages & use q semgroup for files

* Just call yield inside the semgroup

* Refactor a check and revert some log lines

* Move mg && misc tuning

* Add `make profile`

(Benchmark results are only added if tools are installed)

Example output:

```
========================================================================
generating profile data
------------------------------------------------------------------------
- mode: dir
  benchmark:
    tool: hyperfine
    path: profile/1748019612/dir/benchmark.json
    results:
      mean: 1.12852930166
      stddev: 0.12163775966037399
      median: 1.07242928416
      user: 3.9699382799999996
      system: 0.04382341999999999
      min: 1.03207673016
      max: 1.3913475181600001
  profile:
    - mode: cpu
      path: profile/1748019612/dir/cpu.pprof
      view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/cpu.pprof
    - mode: mem
      path: profile/1748019612/dir/mem.pprof
      view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/mem.pprof
    - mode: trace
      path: profile/1748019612/dir/trace.out
      view: go tool trace profile/1748019612/dir/trace.out
- mode: git
  ...snip...
```

* Archive support for File based sources

* Move Git to Source interface

* Scan archives in git

* Misc linter fixes

* Exclude certain diffs: --diff-filter=tuxdb

* Add git archives tests

* Log error instead of fatal

* Fix spacing in test config

* Refine source comments/wording

* Make MB conversions more readable

* Format cmd

* Adjust DetectSource logging

* MiB -> MB in logs

* Add testdata/repos/archives/dotGit/refs/.gitkeep

Without it the refs folder gets deleted and the
and then it isn't detected as a git repo ¯\_(ツ)_/¯

So then the test starts scanning the whole gitleaks
repo instead :D

* Handle finding links for archives

* Working on archive depth

* Fixes from failfast test

* cmd max-archive-depth

* added comments, fixed warnings

* removed test print

* Update README.md

* Set archive depth for DetectFiles

* Tweak logs & pass max archive for readers

* Pass ctx to Fragments

* Add make lint target and address some issues

* Fix compat issue

* Report path in fragment errors

* Apply PR suggestions & misc changes

- Update blobReader.Close() to discard the buffer
- Misc logger issues & uses
- Tweak .golangci.yaml to default to none
- Discard remaining blobReader data on close
- Undo a De Morgan's Law suggestion (and disable QF1001)

* Add http mode for diagnostics

gitleaks --diagnostics=http ...
-----

From the net/http/pprof docs:

Use the pprof tool to look at the heap profile:
```
go tool pprof http://localhost:6060/debug/pprof/heap
```

Or to look at a 30-second CPU profile:
```
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
```

Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:
```
go tool pprof http://localhost:6060/debug/pprof/block
```

Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:
```
go tool pprof http://localhost:6060/debug/pprof/mutex
```

(For more info see https://pkg.go.dev/net/http/pprof)

---------

Co-authored-by: Alex Layne <alayne@redhat.com>
2025-06-01 11:29:34 -05:00

288 lines
7.6 KiB
Go

package main
import (
"os"
"slices"
"text/template"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
const (
templatePath = "rules/config.tmpl"
)
//go:generate go run $GOFILE ../../../config/gitleaks.toml
func main() {
if len(os.Args) < 2 {
_, _ = os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
os.Exit(2)
}
gitleaksConfigPath := os.Args[1]
configRules := []*config.Rule{
rules.OnePasswordSecretKey(),
rules.OnePasswordServiceAccountToken(),
rules.AdafruitAPIKey(),
rules.AdobeClientID(),
rules.AdobeClientSecret(),
rules.AgeSecretKey(),
rules.Airtable(),
rules.AlgoliaApiKey(),
rules.AlibabaAccessKey(),
rules.AlibabaSecretKey(),
rules.AsanaClientID(),
rules.AsanaClientSecret(),
rules.Atlassian(),
rules.Authress(),
rules.AWS(),
rules.AzureActiveDirectoryClientSecret(),
rules.BitBucketClientID(),
rules.BitBucketClientSecret(),
rules.BittrexAccessKey(),
rules.BittrexSecretKey(),
rules.Beamer(),
rules.CodecovAccessToken(),
rules.CoinbaseAccessToken(),
rules.ClickHouseCloud(),
rules.Clojars(),
rules.CloudflareAPIKey(),
rules.CloudflareGlobalAPIKey(),
rules.CloudflareOriginCAKey(),
rules.CohereAPIToken(),
rules.ConfluentAccessToken(),
rules.ConfluentSecretKey(),
rules.Contentful(),
rules.CurlHeaderAuth(),
rules.CurlBasicAuth(),
rules.Databricks(),
rules.DatadogtokenAccessToken(),
rules.DefinedNetworkingAPIToken(),
rules.DigitalOceanPAT(),
rules.DigitalOceanOAuthToken(),
rules.DigitalOceanRefreshToken(),
rules.DiscordAPIToken(),
rules.DiscordClientID(),
rules.DiscordClientSecret(),
rules.Doppler(),
rules.DropBoxAPISecret(),
rules.DropBoxLongLivedAPIToken(),
rules.DropBoxShortLivedAPIToken(),
rules.DroneciAccessToken(),
rules.Duffel(),
rules.Dynatrace(),
rules.EasyPost(),
rules.EasyPostTestAPI(),
rules.EtsyAccessToken(),
rules.FacebookSecret(),
rules.FacebookAccessToken(),
rules.FacebookPageAccessToken(),
rules.FastlyAPIToken(),
rules.FinicityClientSecret(),
rules.FinicityAPIToken(),
rules.FlickrAccessToken(),
rules.FinnhubAccessToken(),
rules.FlutterwavePublicKey(),
rules.FlutterwaveSecretKey(),
rules.FlutterwaveEncKey(),
rules.FlyIOAccessToken(),
rules.FrameIO(),
rules.Freemius(),
rules.FreshbooksAccessToken(),
rules.GoCardless(),
// TODO figure out what makes sense for GCP
// rules.GCPServiceAccount(),
rules.GCPAPIKey(),
rules.GitHubPat(),
rules.GitHubFineGrainedPat(),
rules.GitHubOauth(),
rules.GitHubApp(),
rules.GitHubRefresh(),
rules.GitlabCiCdJobToken(),
rules.GitlabDeployToken(),
rules.GitlabFeatureFlagClientToken(),
rules.GitlabFeedToken(),
rules.GitlabIncomingMailToken(),
rules.GitlabKubernetesAgentToken(),
rules.GitlabOauthAppSecret(),
rules.GitlabPat(),
rules.GitlabPatRoutable(),
rules.GitlabPipelineTriggerToken(),
rules.GitlabRunnerRegistrationToken(),
rules.GitlabRunnerAuthenticationToken(),
rules.GitlabRunnerAuthenticationTokenRoutable(),
rules.GitlabScimToken(),
rules.GitlabSessionCookie(),
rules.GitterAccessToken(),
rules.GrafanaApiKey(),
rules.GrafanaCloudApiToken(),
rules.GrafanaServiceAccountToken(),
rules.HarnessApiKey(),
rules.HashiCorpTerraform(),
rules.HashicorpField(),
rules.Heroku(),
rules.HubSpot(),
rules.HuggingFaceAccessToken(),
rules.HuggingFaceOrganizationApiToken(),
rules.Intercom(),
rules.Intra42ClientSecret(),
rules.JFrogAPIKey(),
rules.JFrogIdentityToken(),
rules.JWT(),
rules.JWTBase64(),
rules.KrakenAccessToken(),
rules.KubernetesSecret(),
rules.KucoinAccessToken(),
rules.KucoinSecretKey(),
rules.LaunchDarklyAccessToken(),
rules.LinearAPIToken(),
rules.LinearClientSecret(),
rules.LinkedinClientID(),
rules.LinkedinClientSecret(),
rules.LobAPIToken(),
rules.LobPubAPIToken(),
rules.MailChimp(),
rules.MailGunPubAPIToken(),
rules.MailGunPrivateAPIToken(),
rules.MailGunSigningKey(),
rules.MapBox(),
rules.MattermostAccessToken(),
rules.MaxMindLicenseKey(),
rules.Meraki(),
rules.MessageBirdAPIToken(),
rules.MessageBirdClientID(),
rules.NetlifyAccessToken(),
rules.NewRelicUserID(),
rules.NewRelicUserKey(),
rules.NewRelicBrowserAPIKey(),
rules.NewRelicInsertKey(),
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
rules.OctopusDeployApiKey(),
rules.OktaAccessToken(),
rules.OpenAI(),
rules.OpenshiftUserToken(),
rules.PerplexityAPIKey(),
rules.PlaidAccessID(),
rules.PlaidSecretKey(),
rules.PlaidAccessToken(),
rules.PlanetScalePassword(),
rules.PlanetScaleAPIToken(),
rules.PlanetScaleOAuthToken(),
rules.PostManAPI(),
rules.Prefect(),
rules.PrivateAIToken(),
rules.PrivateKey(),
rules.PrivateKeyPKCS12File(),
rules.PulumiAPIToken(),
rules.PyPiUploadToken(),
rules.RapidAPIAccessToken(),
rules.ReadMe(),
rules.RubyGemsAPIToken(),
rules.ScalingoAPIToken(),
rules.SendbirdAccessID(),
rules.SendbirdAccessToken(),
rules.SendGridAPIToken(),
rules.SendInBlueAPIToken(),
rules.SentryAccessToken(),
rules.SentryOrgToken(),
rules.SentryUserToken(),
rules.SettlemintApplicationAccessToken(),
rules.SettlemintPersonalAccessToken(),
rules.SettlemintServiceAccessToken(),
rules.ShippoAPIToken(),
rules.ShopifyAccessToken(),
rules.ShopifyCustomAccessToken(),
rules.ShopifyPrivateAppAccessToken(),
rules.ShopifySharedSecret(),
rules.SidekiqSecret(),
rules.SidekiqSensitiveUrl(),
rules.SlackBotToken(),
rules.SlackUserToken(),
rules.SlackAppLevelToken(),
rules.SlackConfigurationToken(),
rules.SlackConfigurationRefreshToken(),
rules.SlackLegacyBotToken(),
rules.SlackLegacyWorkspaceToken(),
rules.SlackLegacyToken(),
rules.SlackWebHookUrl(),
rules.Snyk(),
rules.Sonar(),
rules.SourceGraph(),
rules.StripeAccessToken(),
rules.SquareAccessToken(),
rules.SquareSpaceAccessToken(),
rules.SumoLogicAccessID(),
rules.SumoLogicAccessToken(),
rules.TeamsWebhook(),
rules.TelegramBotToken(),
rules.TravisCIAccessToken(),
rules.Twilio(),
rules.TwitchAPIToken(),
rules.TwitterAPIKey(),
rules.TwitterAPISecret(),
rules.TwitterAccessToken(),
rules.TwitterAccessSecret(),
rules.TwitterBearerToken(),
rules.Typeform(),
rules.VaultBatchToken(),
rules.VaultServiceToken(),
rules.YandexAPIKey(),
rules.YandexAWSAccessToken(),
rules.YandexAccessToken(),
rules.ZendeskSecretKey(),
rules.GenericCredential(),
rules.InfracostAPIToken(),
}
// ensure rules have unique ids
ruleLookUp := make(map[string]config.Rule, len(configRules))
for _, rule := range configRules {
if err := rule.Validate(); err != nil {
logging.Fatal().Err(err).
Str("rule-id", rule.RuleID).
Msg("Failed to validate rule")
}
sortRule(rule)
// check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok {
logging.Fatal().
Str("rule-id", rule.RuleID).
Msg("rule id is not unique")
}
// TODO: eventually change all the signatures to get ride of this
// nasty dereferencing.
ruleLookUp[rule.RuleID] = *rule
}
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
logging.Fatal().Err(err).Msg("Failed to parse template")
}
f, err := os.Create(gitleaksConfigPath)
if err != nil {
logging.Fatal().Err(err).Msg("Failed to create rules.toml")
}
defer f.Close()
cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp
if err = tmpl.Execute(f, cfg); err != nil {
logging.Fatal().Err(err).Msg("could not execute template")
}
}
// sortRule makes the generated config deterministic.
func sortRule(r *config.Rule) {
for _, a := range r.Allowlists {
slices.Sort(a.StopWords)
}
}