4
0

detect_test.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. package detect
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. "testing"
  9. "github.com/google/go-cmp/cmp"
  10. "github.com/rs/zerolog"
  11. "github.com/spf13/viper"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. "golang.org/x/exp/maps"
  15. "github.com/zricethezav/gitleaks/v8/cmd/scm"
  16. "github.com/zricethezav/gitleaks/v8/config"
  17. "github.com/zricethezav/gitleaks/v8/logging"
  18. "github.com/zricethezav/gitleaks/v8/regexp"
  19. "github.com/zricethezav/gitleaks/v8/report"
  20. "github.com/zricethezav/gitleaks/v8/sources"
  21. )
  22. const maxDecodeDepth = 8
  23. const configPath = "../testdata/config/"
  24. const repoBasePath = "../testdata/repos/"
  25. const b64TestValues = `
  26. # Decoded
  27. -----BEGIN PRIVATE KEY-----
  28. 135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb
  29. u+QDkg0spw==
  30. -----END PRIVATE KEY-----
  31. # Encoded
  32. private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'
  33. # Double Encoded: b64 encoded aws config inside a jwt
  34. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA
  35. # A small secret at the end to make sure that as the other ones above shrink
  36. # when decoded, the positions are taken into consideratoin for overlaps
  37. c21hbGwtc2VjcmV0
  38. # This tests how it handles when the match bounds go outside the decoded value
  39. secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=
  40. # The above encoded again
  41. c2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=
  42. # Confirm you can ignore on the decoded value
  43. password="bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw=="
  44. `
  45. func TestDetect(t *testing.T) {
  46. tests := []struct {
  47. cfgName string
  48. baselinePath string
  49. fragment Fragment
  50. // NOTE: for expected findings, all line numbers will be 0
  51. // because line deltas are added _after_ the finding is created.
  52. // I.e., if the finding is from a --no-git file, the line number will be
  53. // increase by 1 in DetectFromFiles(). If the finding is from git,
  54. // the line number will be increased by the patch delta.
  55. expectedFindings []report.Finding
  56. wantError error
  57. }{
  58. {
  59. cfgName: "simple",
  60. fragment: Fragment{
  61. Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
  62. FilePath: "tmp.go",
  63. },
  64. },
  65. {
  66. cfgName: "simple",
  67. fragment: Fragment{
  68. Raw: `awsToken := \
  69. \"AKIALALEMEL33243OKIA\ // gitleaks:allow"
  70. `,
  71. FilePath: "tmp.go",
  72. },
  73. },
  74. {
  75. cfgName: "simple",
  76. fragment: Fragment{
  77. Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
  78. // gitleaks:allow"
  79. `,
  80. FilePath: "tmp.go",
  81. },
  82. expectedFindings: []report.Finding{
  83. {
  84. Description: "AWS Access Key",
  85. Secret: "AKIALALEMEL33243OKIA",
  86. Match: "AKIALALEMEL33243OKIA",
  87. File: "tmp.go",
  88. Line: `awsToken := \"AKIALALEMEL33243OKIA\"`,
  89. RuleID: "aws-access-key",
  90. Tags: []string{"key", "AWS"},
  91. StartLine: 0,
  92. EndLine: 0,
  93. StartColumn: 15,
  94. EndColumn: 34,
  95. Entropy: 3.1464393,
  96. },
  97. },
  98. },
  99. {
  100. cfgName: "escaped_character_group",
  101. fragment: Fragment{
  102. Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
  103. FilePath: "tmp.go",
  104. },
  105. expectedFindings: []report.Finding{
  106. {
  107. Description: "PyPI upload token",
  108. Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
  109. Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
  110. Line: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
  111. File: "tmp.go",
  112. RuleID: "pypi-upload-token",
  113. Tags: []string{"key", "pypi"},
  114. StartLine: 0,
  115. EndLine: 0,
  116. StartColumn: 1,
  117. EndColumn: 86,
  118. Entropy: 1.9606875,
  119. },
  120. },
  121. },
  122. {
  123. cfgName: "simple",
  124. fragment: Fragment{
  125. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  126. FilePath: "tmp.go",
  127. },
  128. expectedFindings: []report.Finding{
  129. {
  130. Description: "AWS Access Key",
  131. Secret: "AKIALALEMEL33243OLIA",
  132. Match: "AKIALALEMEL33243OLIA",
  133. Line: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  134. File: "tmp.go",
  135. RuleID: "aws-access-key",
  136. Tags: []string{"key", "AWS"},
  137. StartLine: 0,
  138. EndLine: 0,
  139. StartColumn: 15,
  140. EndColumn: 34,
  141. Entropy: 3.0841837,
  142. },
  143. },
  144. },
  145. {
  146. cfgName: "simple",
  147. fragment: Fragment{
  148. Raw: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
  149. FilePath: "tmp.sh",
  150. },
  151. expectedFindings: []report.Finding{
  152. {
  153. Description: "Sidekiq Secret",
  154. Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;",
  155. Secret: "cafebabe:deadbeef",
  156. Line: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
  157. File: "tmp.sh",
  158. RuleID: "sidekiq-secret",
  159. Tags: []string{},
  160. Entropy: 2.6098502,
  161. StartLine: 0,
  162. EndLine: 0,
  163. StartColumn: 8,
  164. EndColumn: 60,
  165. },
  166. },
  167. },
  168. {
  169. cfgName: "simple",
  170. fragment: Fragment{
  171. Raw: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
  172. FilePath: "tmp.sh",
  173. },
  174. expectedFindings: []report.Finding{
  175. {
  176. Description: "Sidekiq Secret",
  177. Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=\"cafebabe:deadbeef\"",
  178. Secret: "cafebabe:deadbeef",
  179. File: "tmp.sh",
  180. Line: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
  181. RuleID: "sidekiq-secret",
  182. Tags: []string{},
  183. Entropy: 2.6098502,
  184. StartLine: 0,
  185. EndLine: 0,
  186. StartColumn: 21,
  187. EndColumn: 74,
  188. },
  189. },
  190. },
  191. {
  192. cfgName: "simple",
  193. fragment: Fragment{
  194. Raw: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`,
  195. FilePath: "tmp.sh",
  196. },
  197. expectedFindings: []report.Finding{
  198. {
  199. Description: "Sidekiq Sensitive URL",
  200. Match: "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:",
  201. Secret: "cafeb4b3:d3adb33f",
  202. File: "tmp.sh",
  203. Line: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`,
  204. RuleID: "sidekiq-sensitive-url",
  205. Tags: []string{},
  206. Entropy: 2.984234,
  207. StartLine: 0,
  208. EndLine: 0,
  209. StartColumn: 8,
  210. EndColumn: 58,
  211. },
  212. },
  213. },
  214. {
  215. cfgName: "allow_aws_re",
  216. fragment: Fragment{
  217. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  218. FilePath: "tmp.go",
  219. },
  220. },
  221. {
  222. cfgName: "allow_path",
  223. fragment: Fragment{
  224. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  225. FilePath: "tmp.go",
  226. },
  227. },
  228. {
  229. cfgName: "allow_commit",
  230. fragment: Fragment{
  231. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  232. FilePath: "tmp.go",
  233. CommitSHA: "allowthiscommit",
  234. },
  235. },
  236. {
  237. cfgName: "entropy_group",
  238. fragment: Fragment{
  239. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  240. FilePath: "tmp.go",
  241. },
  242. expectedFindings: []report.Finding{
  243. {
  244. Description: "Discord API key",
  245. Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
  246. Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
  247. Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  248. File: "tmp.go",
  249. RuleID: "discord-api-key",
  250. Tags: []string{},
  251. Entropy: 3.7906237,
  252. StartLine: 0,
  253. EndLine: 0,
  254. StartColumn: 7,
  255. EndColumn: 93,
  256. },
  257. },
  258. },
  259. {
  260. cfgName: "generic_with_py_path",
  261. fragment: Fragment{
  262. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  263. FilePath: "tmp.go",
  264. },
  265. },
  266. {
  267. cfgName: "generic_with_py_path",
  268. fragment: Fragment{
  269. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  270. FilePath: "tmp.py",
  271. },
  272. expectedFindings: []report.Finding{
  273. {
  274. Description: "Generic API Key",
  275. Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
  276. Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
  277. Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  278. File: "tmp.py",
  279. RuleID: "generic-api-key",
  280. Tags: []string{},
  281. Entropy: 3.7906237,
  282. StartLine: 0,
  283. EndLine: 0,
  284. StartColumn: 22,
  285. EndColumn: 93,
  286. },
  287. },
  288. },
  289. {
  290. cfgName: "path_only",
  291. fragment: Fragment{
  292. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  293. FilePath: "tmp.py",
  294. },
  295. expectedFindings: []report.Finding{
  296. {
  297. Description: "Python Files",
  298. Match: "file detected: tmp.py",
  299. File: "tmp.py",
  300. RuleID: "python-files-only",
  301. Tags: []string{},
  302. },
  303. },
  304. },
  305. {
  306. cfgName: "bad_entropy_group",
  307. fragment: Fragment{
  308. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  309. FilePath: "tmp.go",
  310. },
  311. wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
  312. },
  313. {
  314. cfgName: "simple",
  315. fragment: Fragment{
  316. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  317. FilePath: filepath.Join(configPath, "simple.toml"),
  318. },
  319. },
  320. {
  321. cfgName: "allow_global_aws_re",
  322. fragment: Fragment{
  323. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  324. FilePath: "tmp.go",
  325. },
  326. },
  327. {
  328. cfgName: "generic_with_py_path",
  329. fragment: Fragment{
  330. Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  331. FilePath: "tmp.py",
  332. },
  333. },
  334. {
  335. cfgName: "path_only",
  336. baselinePath: ".baseline.json",
  337. fragment: Fragment{
  338. Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
  339. FilePath: ".baseline.json",
  340. },
  341. },
  342. {
  343. cfgName: "base64_encoded",
  344. fragment: Fragment{
  345. Raw: b64TestValues,
  346. FilePath: "tmp.go",
  347. },
  348. expectedFindings: []report.Finding{
  349. { // Plain text key captured by normal rule
  350. Description: "Private Key",
  351. Secret: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  352. Match: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  353. File: "tmp.go",
  354. Line: "\n-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  355. RuleID: "private-key",
  356. Tags: []string{"key", "private"},
  357. StartLine: 2,
  358. EndLine: 5,
  359. StartColumn: 2,
  360. EndColumn: 26,
  361. Entropy: 5.350665,
  362. },
  363. { // Encoded key captured by custom b64 regex rule
  364. Description: "Private Key",
  365. Secret: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
  366. Match: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
  367. File: "tmp.go",
  368. Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
  369. RuleID: "b64-encoded-private-key",
  370. Tags: []string{"key", "private"},
  371. StartLine: 8,
  372. EndLine: 8,
  373. StartColumn: 16,
  374. EndColumn: 207,
  375. Entropy: 5.3861146,
  376. },
  377. { // Encoded key captured by plain text rule using the decoder
  378. Description: "Private Key",
  379. Secret: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  380. Match: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  381. File: "tmp.go",
  382. Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
  383. RuleID: "private-key",
  384. Tags: []string{"key", "private", "decoded:base64", "decode-depth:1"},
  385. StartLine: 8,
  386. EndLine: 8,
  387. StartColumn: 16,
  388. EndColumn: 207,
  389. Entropy: 5.350665,
  390. },
  391. { // Encoded AWS config with a access key id inside a JWT
  392. Description: "AWS IAM Unique Identifier",
  393. Secret: "ASIAIOSFODNN7LXM10JI",
  394. Match: " ASIAIOSFODNN7LXM10JI",
  395. File: "tmp.go",
  396. Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
  397. RuleID: "aws-iam-unique-identifier",
  398. Tags: []string{"aws", "identifier", "decoded:base64", "decode-depth:2"},
  399. StartLine: 11,
  400. EndLine: 11,
  401. StartColumn: 39,
  402. EndColumn: 344,
  403. Entropy: 3.6841838,
  404. },
  405. { // Encoded AWS config with a secret access key inside a JWT
  406. Description: "AWS Secret Access Key",
  407. Secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
  408. Match: "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
  409. File: "tmp.go",
  410. Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
  411. RuleID: "aws-secret-access-key",
  412. Tags: []string{"aws", "secret", "decoded:base64", "decode-depth:2"},
  413. StartLine: 11,
  414. EndLine: 11,
  415. StartColumn: 39,
  416. EndColumn: 344,
  417. Entropy: 4.721928,
  418. },
  419. { // Encoded Small secret at the end to make sure it's picked up by the decoding
  420. Description: "Small Secret",
  421. Secret: "small-secret",
  422. Match: "small-secret",
  423. File: "tmp.go",
  424. Line: "\nc21hbGwtc2VjcmV0",
  425. RuleID: "small-secret",
  426. Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
  427. StartLine: 15,
  428. EndLine: 15,
  429. StartColumn: 2,
  430. EndColumn: 17,
  431. Entropy: 3.0849626,
  432. },
  433. { // Secret where the decoded match goes outside the encoded value
  434. Description: "Overlapping",
  435. Secret: "decoded-secret-value",
  436. Match: "secret=decoded-secret-value",
  437. File: "tmp.go",
  438. Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=",
  439. RuleID: "overlapping",
  440. Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
  441. StartLine: 18,
  442. EndLine: 18,
  443. StartColumn: 2,
  444. EndColumn: 36,
  445. Entropy: 3.3037016,
  446. },
  447. { // Secret where the decoded match goes outside the encoded value and then encoded again
  448. Description: "Overlapping",
  449. Secret: "decoded-secret-value",
  450. Match: "secret=decoded-secret-value",
  451. File: "tmp.go",
  452. Line: "\nc2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=",
  453. RuleID: "overlapping",
  454. Tags: []string{"overlapping", "decoded:base64", "decode-depth:2"},
  455. StartLine: 20,
  456. EndLine: 20,
  457. StartColumn: 2,
  458. EndColumn: 49,
  459. Entropy: 3.3037016,
  460. },
  461. { // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good)
  462. Description: "Make sure this would be detected with no allowlist",
  463. Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw",
  464. Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"",
  465. File: "tmp.go",
  466. Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"",
  467. RuleID: "decoded-password-dont-ignore",
  468. Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"},
  469. StartLine: 23,
  470. EndLine: 23,
  471. StartColumn: 2,
  472. EndColumn: 68,
  473. Entropy: 4.5841837,
  474. },
  475. },
  476. },
  477. }
  478. for _, tt := range tests {
  479. t.Run(fmt.Sprintf("%s - %s", tt.cfgName, tt.fragment.FilePath), func(t *testing.T) {
  480. viper.Reset()
  481. viper.AddConfigPath(configPath)
  482. viper.SetConfigName(tt.cfgName)
  483. viper.SetConfigType("toml")
  484. err := viper.ReadInConfig()
  485. require.NoError(t, err)
  486. var vc config.ViperConfig
  487. err = viper.Unmarshal(&vc)
  488. require.NoError(t, err)
  489. cfg, err := vc.Translate()
  490. cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
  491. assert.Equal(t, tt.wantError, err)
  492. d := NewDetector(cfg)
  493. d.MaxDecodeDepth = maxDecodeDepth
  494. d.baselinePath = tt.baselinePath
  495. findings := d.Detect(tt.fragment)
  496. assert.ElementsMatch(t, tt.expectedFindings, findings)
  497. })
  498. }
  499. }
  500. // TestFromGit tests the FromGit function
  501. func TestFromGit(t *testing.T) {
  502. // TODO: Fix this test on windows.
  503. if runtime.GOOS == "windows" {
  504. t.Skipf("TODO: this fails on Windows: [git] fatal: bad object refs/remotes/origin/main?")
  505. return
  506. }
  507. tests := []struct {
  508. cfgName string
  509. source string
  510. logOpts string
  511. expectedFindings []report.Finding
  512. }{
  513. {
  514. source: filepath.Join(repoBasePath, "small"),
  515. cfgName: "simple", // the remote url is `git@github.com:gitleaks/test.git`
  516. expectedFindings: []report.Finding{
  517. {
  518. RuleID: "aws-access-key",
  519. Description: "AWS Access Key",
  520. StartLine: 20,
  521. EndLine: 20,
  522. StartColumn: 19,
  523. EndColumn: 38,
  524. Line: "\n awsToken := \"AKIALALEMEL33243OLIA\"",
  525. Secret: "AKIALALEMEL33243OLIA",
  526. Match: "AKIALALEMEL33243OLIA",
  527. Entropy: 3.0841837,
  528. File: "main.go",
  529. Date: "2021-11-02T23:37:53Z",
  530. Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
  531. Author: "Zachary Rice",
  532. Email: "zricer@protonmail.com",
  533. Message: "Accidentally add a secret",
  534. Tags: []string{"key", "AWS"},
  535. Fingerprint: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587:main.go:aws-access-key:20",
  536. Link: "https://github.com/gitleaks/test/blob/1b6da43b82b22e4eaa10bcf8ee591e91abbfc587/main.go#L20",
  537. },
  538. {
  539. RuleID: "aws-access-key",
  540. Description: "AWS Access Key",
  541. StartLine: 9,
  542. EndLine: 9,
  543. StartColumn: 17,
  544. EndColumn: 36,
  545. Secret: "AKIALALEMEL33243OLIA",
  546. Match: "AKIALALEMEL33243OLIA",
  547. Line: "\n\taws_token := \"AKIALALEMEL33243OLIA\"",
  548. File: "foo/foo.go",
  549. Date: "2021-11-02T23:48:06Z",
  550. Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
  551. Author: "Zach Rice",
  552. Email: "zricer@protonmail.com",
  553. Message: "adding foo package with secret",
  554. Tags: []string{"key", "AWS"},
  555. Entropy: 3.0841837,
  556. Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
  557. Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
  558. },
  559. },
  560. },
  561. {
  562. source: filepath.Join(repoBasePath, "small"),
  563. logOpts: "--all foo...",
  564. cfgName: "simple",
  565. expectedFindings: []report.Finding{
  566. {
  567. RuleID: "aws-access-key",
  568. Description: "AWS Access Key",
  569. StartLine: 9,
  570. EndLine: 9,
  571. StartColumn: 17,
  572. EndColumn: 36,
  573. Secret: "AKIALALEMEL33243OLIA",
  574. Line: "\n\taws_token := \"AKIALALEMEL33243OLIA\"",
  575. Match: "AKIALALEMEL33243OLIA",
  576. Date: "2021-11-02T23:48:06Z",
  577. File: "foo/foo.go",
  578. Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
  579. Author: "Zach Rice",
  580. Email: "zricer@protonmail.com",
  581. Message: "adding foo package with secret",
  582. Tags: []string{"key", "AWS"},
  583. Entropy: 3.0841837,
  584. Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
  585. Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
  586. },
  587. },
  588. },
  589. }
  590. moveDotGit(t, "dotGit", ".git")
  591. defer moveDotGit(t, ".git", "dotGit")
  592. for _, tt := range tests {
  593. t.Run(strings.Join([]string{tt.cfgName, tt.source, tt.logOpts}, "/"), func(t *testing.T) {
  594. viper.AddConfigPath(configPath)
  595. viper.SetConfigName("simple")
  596. viper.SetConfigType("toml")
  597. err := viper.ReadInConfig()
  598. require.NoError(t, err)
  599. var vc config.ViperConfig
  600. err = viper.Unmarshal(&vc)
  601. require.NoError(t, err)
  602. cfg, err := vc.Translate()
  603. require.NoError(t, err)
  604. detector := NewDetector(cfg)
  605. var ignorePath string
  606. info, err := os.Stat(tt.source)
  607. require.NoError(t, err)
  608. if info.IsDir() {
  609. ignorePath = filepath.Join(tt.source, ".gitleaksignore")
  610. } else {
  611. ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
  612. }
  613. err = detector.AddGitleaksIgnore(ignorePath)
  614. require.NoError(t, err)
  615. gitCmd, err := sources.NewGitLogCmd(tt.source, tt.logOpts)
  616. require.NoError(t, err)
  617. remote := NewRemoteInfo(scm.UnknownPlatform, tt.source)
  618. findings, err := detector.DetectGit(gitCmd, remote)
  619. require.NoError(t, err)
  620. for _, f := range findings {
  621. f.Match = "" // remove lines cause copying and pasting them has some wack formatting
  622. }
  623. assert.ElementsMatch(t, tt.expectedFindings, findings)
  624. })
  625. }
  626. }
  627. func TestFromGitStaged(t *testing.T) {
  628. tests := []struct {
  629. cfgName string
  630. source string
  631. logOpts string
  632. expectedFindings []report.Finding
  633. }{
  634. {
  635. source: filepath.Join(repoBasePath, "staged"),
  636. cfgName: "simple",
  637. expectedFindings: []report.Finding{
  638. {
  639. RuleID: "aws-access-key",
  640. Description: "AWS Access Key",
  641. StartLine: 7,
  642. EndLine: 7,
  643. StartColumn: 18,
  644. EndColumn: 37,
  645. Line: "\n\taws_token2 := \"AKIALALEMEL33243OLIA\" // this one is not",
  646. Match: "AKIALALEMEL33243OLIA",
  647. Secret: "AKIALALEMEL33243OLIA",
  648. File: "api/api.go",
  649. SymlinkFile: "",
  650. Commit: "",
  651. Entropy: 3.0841837,
  652. Author: "",
  653. Email: "",
  654. Date: "0001-01-01T00:00:00Z",
  655. Message: "",
  656. Tags: []string{
  657. "key",
  658. "AWS",
  659. },
  660. Fingerprint: "api/api.go:aws-access-key:7",
  661. Link: "",
  662. },
  663. },
  664. },
  665. }
  666. moveDotGit(t, "dotGit", ".git")
  667. defer moveDotGit(t, ".git", "dotGit")
  668. for _, tt := range tests {
  669. viper.AddConfigPath(configPath)
  670. viper.SetConfigName("simple")
  671. viper.SetConfigType("toml")
  672. err := viper.ReadInConfig()
  673. require.NoError(t, err)
  674. var vc config.ViperConfig
  675. err = viper.Unmarshal(&vc)
  676. require.NoError(t, err)
  677. cfg, err := vc.Translate()
  678. require.NoError(t, err)
  679. detector := NewDetector(cfg)
  680. err = detector.AddGitleaksIgnore(filepath.Join(tt.source, ".gitleaksignore"))
  681. require.NoError(t, err)
  682. gitCmd, err := sources.NewGitDiffCmd(tt.source, true)
  683. require.NoError(t, err)
  684. remote := NewRemoteInfo(scm.UnknownPlatform, tt.source)
  685. findings, err := detector.DetectGit(gitCmd, remote)
  686. require.NoError(t, err)
  687. for _, f := range findings {
  688. f.Match = "" // remove lines cause copying and pasting them has some wack formatting
  689. }
  690. assert.ElementsMatch(t, tt.expectedFindings, findings)
  691. }
  692. }
  693. // TestFromFiles tests the FromFiles function
  694. func TestFromFiles(t *testing.T) {
  695. tests := []struct {
  696. cfgName string
  697. source string
  698. expectedFindings []report.Finding
  699. }{
  700. {
  701. source: filepath.Join(repoBasePath, "nogit"),
  702. cfgName: "simple",
  703. expectedFindings: []report.Finding{
  704. {
  705. RuleID: "aws-access-key",
  706. Description: "AWS Access Key",
  707. StartLine: 20,
  708. EndLine: 20,
  709. StartColumn: 16,
  710. EndColumn: 35,
  711. Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
  712. Match: "AKIALALEMEL33243OLIA",
  713. Secret: "AKIALALEMEL33243OLIA",
  714. File: "../testdata/repos/nogit/main.go",
  715. SymlinkFile: "",
  716. Tags: []string{"key", "AWS"},
  717. Entropy: 3.0841837,
  718. Fingerprint: "../testdata/repos/nogit/main.go:aws-access-key:20",
  719. },
  720. },
  721. },
  722. {
  723. source: filepath.Join(repoBasePath, "nogit", "main.go"),
  724. cfgName: "simple",
  725. expectedFindings: []report.Finding{
  726. {
  727. RuleID: "aws-access-key",
  728. Description: "AWS Access Key",
  729. StartLine: 20,
  730. EndLine: 20,
  731. StartColumn: 16,
  732. EndColumn: 35,
  733. Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
  734. Match: "AKIALALEMEL33243OLIA",
  735. Secret: "AKIALALEMEL33243OLIA",
  736. File: "../testdata/repos/nogit/main.go",
  737. Tags: []string{"key", "AWS"},
  738. Entropy: 3.0841837,
  739. Fingerprint: "../testdata/repos/nogit/main.go:aws-access-key:20",
  740. },
  741. },
  742. },
  743. {
  744. source: filepath.Join(repoBasePath, "nogit", "api.go"),
  745. cfgName: "simple",
  746. expectedFindings: []report.Finding{},
  747. },
  748. {
  749. source: filepath.Join(repoBasePath, "nogit", ".env.prod"),
  750. cfgName: "generic",
  751. expectedFindings: []report.Finding{
  752. {
  753. RuleID: "generic-api-key",
  754. Description: "Generic API Key",
  755. StartLine: 4,
  756. EndLine: 4,
  757. StartColumn: 5,
  758. EndColumn: 35,
  759. Line: "\nDB_PASSWORD=8ae31cacf141669ddfb5da",
  760. Match: "PASSWORD=8ae31cacf141669ddfb5da",
  761. Secret: "8ae31cacf141669ddfb5da",
  762. File: "../testdata/repos/nogit/.env.prod",
  763. Tags: []string{},
  764. Entropy: 3.5383105,
  765. Fingerprint: "../testdata/repos/nogit/.env.prod:generic-api-key:4",
  766. },
  767. },
  768. },
  769. }
  770. for _, tt := range tests {
  771. t.Run(tt.cfgName+" - "+tt.source, func(t *testing.T) {
  772. viper.AddConfigPath(configPath)
  773. viper.SetConfigName(tt.cfgName)
  774. viper.SetConfigType("toml")
  775. err := viper.ReadInConfig()
  776. require.NoError(t, err)
  777. var vc config.ViperConfig
  778. err = viper.Unmarshal(&vc)
  779. require.NoError(t, err)
  780. cfg, _ := vc.Translate()
  781. detector := NewDetector(cfg)
  782. info, err := os.Stat(tt.source)
  783. require.NoError(t, err)
  784. var ignorePath string
  785. if info.IsDir() {
  786. ignorePath = filepath.Join(tt.source, ".gitleaksignore")
  787. } else {
  788. ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
  789. }
  790. err = detector.AddGitleaksIgnore(ignorePath)
  791. require.NoError(t, err)
  792. detector.FollowSymlinks = true
  793. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
  794. require.NoError(t, err)
  795. findings, err := detector.DetectFiles(paths)
  796. require.NoError(t, err)
  797. // TODO: Temporary mitigation.
  798. // https://github.com/gitleaks/gitleaks/issues/1641
  799. normalizedFindings := make([]report.Finding, len(findings))
  800. for i, f := range findings {
  801. if strings.HasSuffix(f.Line, "\r") {
  802. f.Line = strings.ReplaceAll(f.Line, "\r", "")
  803. }
  804. if strings.HasSuffix(f.Match, "\r") {
  805. f.EndColumn = f.EndColumn - 1
  806. f.Match = strings.ReplaceAll(f.Match, "\r", "")
  807. }
  808. normalizedFindings[i] = f
  809. }
  810. assert.ElementsMatch(t, tt.expectedFindings, normalizedFindings)
  811. })
  812. }
  813. }
  814. func TestDetectWithSymlinks(t *testing.T) {
  815. // TODO: Fix this test on windows.
  816. if runtime.GOOS == "windows" {
  817. t.Skipf("TODO: this returns no results on windows, I'm not sure why.")
  818. return
  819. }
  820. tests := []struct {
  821. cfgName string
  822. source string
  823. expectedFindings []report.Finding
  824. }{
  825. {
  826. source: filepath.Join(repoBasePath, "symlinks/file_symlink"),
  827. cfgName: "simple",
  828. expectedFindings: []report.Finding{
  829. {
  830. RuleID: "apkey",
  831. Description: "Asymmetric Private Key",
  832. StartLine: 1,
  833. EndLine: 1,
  834. StartColumn: 1,
  835. EndColumn: 35,
  836. Match: "-----BEGIN OPENSSH PRIVATE KEY-----",
  837. Secret: "-----BEGIN OPENSSH PRIVATE KEY-----",
  838. Line: "-----BEGIN OPENSSH PRIVATE KEY-----",
  839. File: "../testdata/repos/symlinks/source_file/id_ed25519",
  840. SymlinkFile: "../testdata/repos/symlinks/file_symlink/symlinked_id_ed25519",
  841. Tags: []string{"key", "AsymmetricPrivateKey"},
  842. Entropy: 3.587164,
  843. Fingerprint: "../testdata/repos/symlinks/source_file/id_ed25519:apkey:1",
  844. },
  845. },
  846. },
  847. }
  848. for _, tt := range tests {
  849. viper.AddConfigPath(configPath)
  850. viper.SetConfigName("simple")
  851. viper.SetConfigType("toml")
  852. err := viper.ReadInConfig()
  853. require.NoError(t, err)
  854. var vc config.ViperConfig
  855. err = viper.Unmarshal(&vc)
  856. require.NoError(t, err)
  857. cfg, _ := vc.Translate()
  858. detector := NewDetector(cfg)
  859. detector.FollowSymlinks = true
  860. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
  861. require.NoError(t, err)
  862. findings, err := detector.DetectFiles(paths)
  863. require.NoError(t, err)
  864. assert.ElementsMatch(t, tt.expectedFindings, findings)
  865. }
  866. }
  867. func TestDetectRuleAllowlist(t *testing.T) {
  868. cases := map[string]struct {
  869. fragment Fragment
  870. allowlist config.Allowlist
  871. expected []report.Finding
  872. }{
  873. // Commit / path
  874. "commit allowed": {
  875. fragment: Fragment{
  876. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  877. },
  878. allowlist: config.Allowlist{
  879. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  880. },
  881. },
  882. "path allowed": {
  883. fragment: Fragment{
  884. FilePath: "package-lock.json",
  885. },
  886. allowlist: config.Allowlist{
  887. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  888. },
  889. },
  890. "commit AND path allowed": {
  891. fragment: Fragment{
  892. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  893. FilePath: "package-lock.json",
  894. },
  895. allowlist: config.Allowlist{
  896. MatchCondition: config.AllowlistMatchAnd,
  897. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  898. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  899. },
  900. },
  901. "commit AND path NOT allowed": {
  902. fragment: Fragment{
  903. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  904. FilePath: "package.json",
  905. },
  906. allowlist: config.Allowlist{
  907. MatchCondition: config.AllowlistMatchAnd,
  908. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  909. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  910. },
  911. expected: []report.Finding{
  912. {
  913. StartColumn: 50,
  914. EndColumn: 60,
  915. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  916. Match: "Summer2024!",
  917. Secret: "Summer2024!",
  918. File: "package.json",
  919. Entropy: 3.095795154571533,
  920. RuleID: "test-rule",
  921. },
  922. },
  923. },
  924. "commit AND path NOT allowed - other conditions": {
  925. fragment: Fragment{
  926. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  927. FilePath: "package-lock.json",
  928. },
  929. allowlist: config.Allowlist{
  930. MatchCondition: config.AllowlistMatchAnd,
  931. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  932. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  933. Regexes: []*regexp.Regexp{regexp.MustCompile("password")},
  934. },
  935. expected: []report.Finding{
  936. {
  937. StartColumn: 50,
  938. EndColumn: 60,
  939. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  940. Match: "Summer2024!",
  941. Secret: "Summer2024!",
  942. File: "package-lock.json",
  943. Entropy: 3.095795154571533,
  944. RuleID: "test-rule",
  945. },
  946. },
  947. },
  948. "commit OR path allowed": {
  949. fragment: Fragment{
  950. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  951. FilePath: "package-lock.json",
  952. },
  953. allowlist: config.Allowlist{
  954. MatchCondition: config.AllowlistMatchOr,
  955. Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
  956. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  957. },
  958. },
  959. // Regex / stopwords
  960. "regex allowed": {
  961. fragment: Fragment{},
  962. allowlist: config.Allowlist{
  963. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  964. },
  965. },
  966. "stopwords allowed": {
  967. fragment: Fragment{},
  968. allowlist: config.Allowlist{
  969. StopWords: []string{"summer"},
  970. },
  971. },
  972. "regex AND stopword allowed": {
  973. fragment: Fragment{},
  974. allowlist: config.Allowlist{
  975. MatchCondition: config.AllowlistMatchAnd,
  976. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  977. StopWords: []string{"2024"},
  978. },
  979. },
  980. "regex AND stopword allowed - other conditions": {
  981. fragment: Fragment{
  982. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  983. FilePath: "config.js",
  984. },
  985. allowlist: config.Allowlist{
  986. MatchCondition: config.AllowlistMatchAnd,
  987. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  988. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  989. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  990. StopWords: []string{"2024"},
  991. },
  992. },
  993. "regex AND stopword NOT allowed - non-git, other conditions": {
  994. fragment: Fragment{
  995. FilePath: "config.js",
  996. },
  997. allowlist: config.Allowlist{
  998. MatchCondition: config.AllowlistMatchAnd,
  999. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1000. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  1001. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1002. StopWords: []string{"2024"},
  1003. },
  1004. expected: []report.Finding{
  1005. {
  1006. StartColumn: 50,
  1007. EndColumn: 60,
  1008. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1009. Match: "Summer2024!",
  1010. Secret: "Summer2024!",
  1011. File: "config.js",
  1012. Entropy: 3.095795154571533,
  1013. RuleID: "test-rule",
  1014. },
  1015. },
  1016. },
  1017. "regex AND stopword NOT allowed": {
  1018. fragment: Fragment{},
  1019. allowlist: config.Allowlist{
  1020. MatchCondition: config.AllowlistMatchAnd,
  1021. Regexes: []*regexp.Regexp{
  1022. regexp.MustCompile(`(?i)winter.+`),
  1023. },
  1024. StopWords: []string{"2024"},
  1025. },
  1026. expected: []report.Finding{
  1027. {
  1028. StartColumn: 50,
  1029. EndColumn: 60,
  1030. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1031. Match: "Summer2024!",
  1032. Secret: "Summer2024!",
  1033. Entropy: 3.095795154571533,
  1034. RuleID: "test-rule",
  1035. },
  1036. },
  1037. },
  1038. "regex AND stopword NOT allowed - other conditions": {
  1039. fragment: Fragment{
  1040. CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
  1041. FilePath: "config.js",
  1042. },
  1043. allowlist: config.Allowlist{
  1044. MatchCondition: config.AllowlistMatchAnd,
  1045. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1046. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  1047. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)winter.+`)},
  1048. StopWords: []string{"2024"},
  1049. },
  1050. expected: []report.Finding{
  1051. {
  1052. StartColumn: 50,
  1053. EndColumn: 60,
  1054. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1055. Match: "Summer2024!",
  1056. Secret: "Summer2024!",
  1057. File: "config.js",
  1058. Entropy: 3.095795154571533,
  1059. RuleID: "test-rule",
  1060. },
  1061. },
  1062. },
  1063. "regex OR stopword allowed": {
  1064. fragment: Fragment{},
  1065. allowlist: config.Allowlist{
  1066. MatchCondition: config.AllowlistMatchOr,
  1067. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1068. StopWords: []string{"winter"},
  1069. },
  1070. },
  1071. }
  1072. raw := `let username = 'james@mail.com';
  1073. let password = 'Summer2024!';`
  1074. for name, tc := range cases {
  1075. t.Run(name, func(t *testing.T) {
  1076. rule := config.Rule{
  1077. RuleID: "test-rule",
  1078. Regex: regexp.MustCompile(`Summer2024!`),
  1079. Allowlists: []config.Allowlist{
  1080. tc.allowlist,
  1081. },
  1082. }
  1083. d, err := NewDetectorDefaultConfig()
  1084. require.NoError(t, err)
  1085. f := tc.fragment
  1086. f.Raw = raw
  1087. actual := d.detectRule(f, raw, rule, []EncodedSegment{})
  1088. if diff := cmp.Diff(tc.expected, actual); diff != "" {
  1089. t.Errorf("diff: (-want +got)\n%s", diff)
  1090. }
  1091. })
  1092. }
  1093. }
  1094. func moveDotGit(t *testing.T, from, to string) {
  1095. t.Helper()
  1096. repoDirs, err := os.ReadDir("../testdata/repos")
  1097. require.NoError(t, err)
  1098. for _, dir := range repoDirs {
  1099. if to == ".git" {
  1100. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
  1101. if os.IsNotExist(err) {
  1102. // dont want to delete the only copy of .git accidentally
  1103. continue
  1104. }
  1105. os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
  1106. }
  1107. if !dir.IsDir() {
  1108. continue
  1109. }
  1110. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
  1111. if os.IsNotExist(err) {
  1112. continue
  1113. }
  1114. err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
  1115. fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
  1116. require.NoError(t, err)
  1117. }
  1118. }
  1119. // region Windows-specific tests[]
  1120. func TestNormalizeGitleaksIgnorePaths(t *testing.T) {
  1121. d, err := NewDetectorDefaultConfig()
  1122. require.NoError(t, err)
  1123. err = d.AddGitleaksIgnore("../testdata/gitleaksignore/.windowspaths")
  1124. require.NoError(t, err)
  1125. assert.Len(t, d.gitleaksIgnore, 3)
  1126. expected := map[string]struct{}{
  1127. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:4": {},
  1128. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:5": {},
  1129. "b55d88dc151f7022901cda41a03d43e0e508f2b7:test_data/test_local_repo_three_leaks.json:aws-access-token:73": {},
  1130. }
  1131. assert.ElementsMatch(t, maps.Keys(d.gitleaksIgnore), maps.Keys(expected))
  1132. }
  1133. func TestWindowsFileSeparator_RulePath(t *testing.T) {
  1134. logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
  1135. unixRule := config.Rule{
  1136. RuleID: "test-rule",
  1137. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1138. }
  1139. windowsRule := config.Rule{
  1140. RuleID: "test-rule",
  1141. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1142. }
  1143. expected := []report.Finding{
  1144. {
  1145. RuleID: "test-rule",
  1146. Match: "file detected: .m2/settings.xml",
  1147. File: ".m2/settings.xml",
  1148. },
  1149. }
  1150. tests := map[string]struct {
  1151. fragment Fragment
  1152. rule config.Rule
  1153. expected []report.Finding
  1154. }{
  1155. // unix rule
  1156. "unix rule - unix path separator": {
  1157. fragment: Fragment{
  1158. FilePath: `.m2/settings.xml`,
  1159. },
  1160. rule: unixRule,
  1161. expected: expected,
  1162. },
  1163. "unix rule - windows path separator": {
  1164. fragment: Fragment{
  1165. FilePath: `.m2/settings.xml`,
  1166. WindowsFilePath: `.m2\settings.xml`,
  1167. },
  1168. rule: unixRule,
  1169. expected: expected,
  1170. },
  1171. "unix regex+path rule - windows path separator": {
  1172. fragment: Fragment{
  1173. Raw: `<password>s3cr3t</password>`,
  1174. FilePath: `.m2/settings.xml`,
  1175. },
  1176. rule: config.Rule{
  1177. RuleID: "test-rule",
  1178. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1179. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1180. },
  1181. expected: []report.Finding{
  1182. {
  1183. RuleID: "test-rule",
  1184. StartColumn: 1,
  1185. EndColumn: 27,
  1186. Line: "<password>s3cr3t</password>",
  1187. Match: "<password>s3cr3t</password>",
  1188. Secret: "s3cr3t",
  1189. Entropy: 2.251629114151001,
  1190. File: ".m2/settings.xml",
  1191. },
  1192. },
  1193. },
  1194. // windows rule
  1195. "windows rule - unix path separator": {
  1196. fragment: Fragment{
  1197. FilePath: `.m2/settings.xml`,
  1198. },
  1199. rule: windowsRule,
  1200. // This never worked, and continues not to work.
  1201. // Paths should be normalized to use Unix file separators.
  1202. expected: nil,
  1203. },
  1204. "windows rule - windows path separator": {
  1205. fragment: Fragment{
  1206. FilePath: `.m2/settings.xml`,
  1207. WindowsFilePath: `.m2\settings.xml`,
  1208. },
  1209. rule: windowsRule,
  1210. expected: expected,
  1211. },
  1212. "windows regex+path rule - windows path separator": {
  1213. fragment: Fragment{
  1214. Raw: `<password>s3cr3t</password>`,
  1215. FilePath: `.m2/settings.xml`,
  1216. WindowsFilePath: `.m2\settings.xml`,
  1217. },
  1218. rule: config.Rule{
  1219. RuleID: "test-rule",
  1220. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1221. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1222. },
  1223. expected: []report.Finding{
  1224. {
  1225. RuleID: "test-rule",
  1226. StartColumn: 1,
  1227. EndColumn: 27,
  1228. Line: "<password>s3cr3t</password>",
  1229. Match: "<password>s3cr3t</password>",
  1230. Secret: "s3cr3t",
  1231. Entropy: 2.251629114151001,
  1232. File: ".m2/settings.xml",
  1233. },
  1234. }},
  1235. }
  1236. d, err := NewDetectorDefaultConfig()
  1237. require.NoError(t, err)
  1238. for name, test := range tests {
  1239. t.Run(name, func(t *testing.T) {
  1240. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1241. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1242. t.Errorf("diff: (-want +got)\n%s", diff)
  1243. }
  1244. })
  1245. }
  1246. }
  1247. func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
  1248. tests := map[string]struct {
  1249. fragment Fragment
  1250. rule config.Rule
  1251. expected []report.Finding
  1252. }{
  1253. // unix
  1254. "unix path separator - unix rule - OR allowlist path-only": {
  1255. fragment: Fragment{
  1256. Raw: `value: "s3cr3t"`,
  1257. FilePath: `ignoreme/unix.txt`,
  1258. },
  1259. rule: config.Rule{
  1260. RuleID: "unix-rule",
  1261. Regex: regexp.MustCompile(`s3cr3t`),
  1262. Allowlists: []config.Allowlist{
  1263. {
  1264. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1265. },
  1266. },
  1267. },
  1268. expected: nil,
  1269. },
  1270. "unix path separator - windows rule - OR allowlist path-only": {
  1271. fragment: Fragment{
  1272. Raw: `value: "s3cr3t"`,
  1273. FilePath: `ignoreme/unix.txt`,
  1274. },
  1275. rule: config.Rule{
  1276. RuleID: "windows-rule",
  1277. Regex: regexp.MustCompile(`s3cr3t`),
  1278. Allowlists: []config.Allowlist{
  1279. {
  1280. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1281. },
  1282. },
  1283. },
  1284. // Windows separators in regex don't work for unix.
  1285. expected: []report.Finding{
  1286. {
  1287. RuleID: "windows-rule",
  1288. StartColumn: 9,
  1289. EndColumn: 14,
  1290. Line: `value: "s3cr3t"`,
  1291. Match: `s3cr3t`,
  1292. Secret: `s3cr3t`,
  1293. File: "ignoreme/unix.txt",
  1294. Entropy: 2.251629114151001,
  1295. },
  1296. },
  1297. },
  1298. "unix path separator - unix rule - AND allowlist path+stopwords": {
  1299. fragment: Fragment{
  1300. Raw: `value: "f4k3s3cr3t"`,
  1301. FilePath: `ignoreme/unix.txt`,
  1302. },
  1303. rule: config.Rule{
  1304. RuleID: "unix-rule",
  1305. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1306. Allowlists: []config.Allowlist{
  1307. {
  1308. MatchCondition: config.AllowlistMatchAnd,
  1309. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1310. StopWords: []string{"f4k3"},
  1311. },
  1312. },
  1313. },
  1314. expected: nil,
  1315. },
  1316. "unix path separator - windows rule - AND allowlist path+stopwords": {
  1317. fragment: Fragment{
  1318. Raw: `value: "f4k3s3cr3t"`,
  1319. FilePath: `ignoreme/unix.txt`,
  1320. },
  1321. rule: config.Rule{
  1322. RuleID: "windows-rule",
  1323. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1324. Allowlists: []config.Allowlist{
  1325. {
  1326. MatchCondition: config.AllowlistMatchAnd,
  1327. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1328. StopWords: []string{"f4k3"},
  1329. },
  1330. },
  1331. },
  1332. expected: []report.Finding{
  1333. {
  1334. RuleID: "windows-rule",
  1335. StartColumn: 1,
  1336. EndColumn: 19,
  1337. Line: `value: "f4k3s3cr3t"`,
  1338. Match: `value: "f4k3s3cr3t"`,
  1339. Secret: `value: "f4k3s3cr3t"`,
  1340. File: "ignoreme/unix.txt",
  1341. Entropy: 3.892407178878784,
  1342. },
  1343. },
  1344. },
  1345. // windows
  1346. "windows path separator - unix rule - OR allowlist path-only": {
  1347. fragment: Fragment{
  1348. Raw: `value: "s3cr3t"`,
  1349. FilePath: `ignoreme/windows.txt`,
  1350. WindowsFilePath: `ignoreme\windows.txt`,
  1351. },
  1352. rule: config.Rule{
  1353. RuleID: "unix-rule",
  1354. Regex: regexp.MustCompile(`s3cr3t`),
  1355. Allowlists: []config.Allowlist{
  1356. {
  1357. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1358. },
  1359. },
  1360. },
  1361. expected: nil,
  1362. },
  1363. "windows path separator - windows rule - OR allowlist path-only": {
  1364. fragment: Fragment{
  1365. Raw: `value: "s3cr3t"`,
  1366. FilePath: `ignoreme/windows.txt`,
  1367. WindowsFilePath: `ignoreme\windows.txt`,
  1368. },
  1369. rule: config.Rule{
  1370. RuleID: "windows-rule",
  1371. Regex: regexp.MustCompile(`s3cr3t`),
  1372. Allowlists: []config.Allowlist{
  1373. {
  1374. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1375. },
  1376. },
  1377. },
  1378. expected: nil,
  1379. },
  1380. "windows path separator - unix rule - AND allowlist path+stopwords": {
  1381. fragment: Fragment{
  1382. Raw: `value: "f4k3s3cr3t"`,
  1383. FilePath: `ignoreme/unix.txt`,
  1384. WindowsFilePath: `ignoreme\windows.txt`,
  1385. },
  1386. rule: config.Rule{
  1387. RuleID: "unix-rule",
  1388. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1389. Allowlists: []config.Allowlist{
  1390. {
  1391. MatchCondition: config.AllowlistMatchAnd,
  1392. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1393. StopWords: []string{"f4k3"},
  1394. },
  1395. },
  1396. },
  1397. expected: nil,
  1398. },
  1399. "windows path separator - windows rule - AND allowlist path+stopwords": {
  1400. fragment: Fragment{
  1401. Raw: `value: "f4k3s3cr3t"`,
  1402. FilePath: `ignoreme/unix.txt`,
  1403. WindowsFilePath: `ignoreme\windows.txt`,
  1404. },
  1405. rule: config.Rule{
  1406. RuleID: "windows-rule",
  1407. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1408. Allowlists: []config.Allowlist{
  1409. {
  1410. MatchCondition: config.AllowlistMatchAnd,
  1411. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1412. StopWords: []string{"f4k3"},
  1413. },
  1414. },
  1415. },
  1416. expected: nil,
  1417. },
  1418. }
  1419. d, err := NewDetectorDefaultConfig()
  1420. require.NoError(t, err)
  1421. for name, test := range tests {
  1422. t.Run(name, func(t *testing.T) {
  1423. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1424. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1425. t.Errorf("diff: (-want +got)\n%s", diff)
  1426. }
  1427. })
  1428. }
  1429. }
  1430. //endregion