detect_test.go 46 KB

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