detect_test.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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. source: filepath.Join(repoBasePath, "archive"),
  771. cfgName: "simple",
  772. expectedFindings: []report.Finding{
  773. {
  774. RuleID: "aws-access-key",
  775. Description: "AWS Access Key",
  776. StartLine: 20,
  777. EndLine: 20,
  778. StartColumn: 16,
  779. EndColumn: 35,
  780. Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
  781. Match: "AKIALALEMEL33243OLIA",
  782. Secret: "AKIALALEMEL33243OLIA",
  783. File: "archive.zip/main.go",
  784. SymlinkFile: "",
  785. Tags: []string{"key", "AWS"},
  786. Entropy: 3.0841837,
  787. Fingerprint: "archive.zip/main.go:aws-access-key:20",
  788. },
  789. },
  790. },
  791. }
  792. for _, tt := range tests {
  793. t.Run(tt.cfgName+" - "+tt.source, func(t *testing.T) {
  794. viper.AddConfigPath(configPath)
  795. viper.SetConfigName(tt.cfgName)
  796. viper.SetConfigType("toml")
  797. err := viper.ReadInConfig()
  798. require.NoError(t, err)
  799. var vc config.ViperConfig
  800. err = viper.Unmarshal(&vc)
  801. require.NoError(t, err)
  802. cfg, _ := vc.Translate()
  803. detector := NewDetector(cfg)
  804. info, err := os.Stat(tt.source)
  805. require.NoError(t, err)
  806. var ignorePath string
  807. if info.IsDir() {
  808. ignorePath = filepath.Join(tt.source, ".gitleaksignore")
  809. } else {
  810. ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
  811. }
  812. err = detector.AddGitleaksIgnore(ignorePath)
  813. require.NoError(t, err)
  814. detector.FollowSymlinks = true
  815. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
  816. require.NoError(t, err)
  817. findings, err := detector.DetectFiles(paths)
  818. require.NoError(t, err)
  819. // TODO: Temporary mitigation.
  820. // https://github.com/gitleaks/gitleaks/issues/1641
  821. normalizedFindings := make([]report.Finding, len(findings))
  822. for i, f := range findings {
  823. if strings.HasSuffix(f.Line, "\r") {
  824. f.Line = strings.ReplaceAll(f.Line, "\r", "")
  825. }
  826. if strings.HasSuffix(f.Match, "\r") {
  827. f.EndColumn = f.EndColumn - 1
  828. f.Match = strings.ReplaceAll(f.Match, "\r", "")
  829. }
  830. normalizedFindings[i] = f
  831. }
  832. assert.ElementsMatch(t, tt.expectedFindings, normalizedFindings)
  833. })
  834. }
  835. }
  836. func TestDetectWithSymlinks(t *testing.T) {
  837. // TODO: Fix this test on windows.
  838. if runtime.GOOS == "windows" {
  839. t.Skipf("TODO: this returns no results on windows, I'm not sure why.")
  840. return
  841. }
  842. tests := []struct {
  843. cfgName string
  844. source string
  845. expectedFindings []report.Finding
  846. }{
  847. {
  848. source: filepath.Join(repoBasePath, "symlinks/file_symlink"),
  849. cfgName: "simple",
  850. expectedFindings: []report.Finding{
  851. {
  852. RuleID: "apkey",
  853. Description: "Asymmetric Private Key",
  854. StartLine: 1,
  855. EndLine: 1,
  856. StartColumn: 1,
  857. EndColumn: 35,
  858. Match: "-----BEGIN OPENSSH PRIVATE KEY-----",
  859. Secret: "-----BEGIN OPENSSH PRIVATE KEY-----",
  860. Line: "-----BEGIN OPENSSH PRIVATE KEY-----",
  861. File: "../testdata/repos/symlinks/source_file/id_ed25519",
  862. SymlinkFile: "../testdata/repos/symlinks/file_symlink/symlinked_id_ed25519",
  863. Tags: []string{"key", "AsymmetricPrivateKey"},
  864. Entropy: 3.587164,
  865. Fingerprint: "../testdata/repos/symlinks/source_file/id_ed25519:apkey:1",
  866. },
  867. },
  868. },
  869. }
  870. for _, tt := range tests {
  871. viper.AddConfigPath(configPath)
  872. viper.SetConfigName("simple")
  873. viper.SetConfigType("toml")
  874. err := viper.ReadInConfig()
  875. require.NoError(t, err)
  876. var vc config.ViperConfig
  877. err = viper.Unmarshal(&vc)
  878. require.NoError(t, err)
  879. cfg, _ := vc.Translate()
  880. detector := NewDetector(cfg)
  881. detector.FollowSymlinks = true
  882. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
  883. require.NoError(t, err)
  884. findings, err := detector.DetectFiles(paths)
  885. require.NoError(t, err)
  886. assert.ElementsMatch(t, tt.expectedFindings, findings)
  887. }
  888. }
  889. func TestDetectRuleAllowlist(t *testing.T) {
  890. cases := map[string]struct {
  891. fragment Fragment
  892. allowlist *config.Allowlist
  893. expected []report.Finding
  894. }{
  895. // Commit / path
  896. "commit allowed": {
  897. fragment: Fragment{
  898. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  899. },
  900. allowlist: &config.Allowlist{
  901. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  902. },
  903. },
  904. "path allowed": {
  905. fragment: Fragment{
  906. FilePath: "package-lock.json",
  907. },
  908. allowlist: &config.Allowlist{
  909. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  910. },
  911. },
  912. "commit AND path allowed": {
  913. fragment: Fragment{
  914. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  915. FilePath: "package-lock.json",
  916. },
  917. allowlist: &config.Allowlist{
  918. MatchCondition: config.AllowlistMatchAnd,
  919. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  920. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  921. },
  922. },
  923. "commit AND path NOT allowed": {
  924. fragment: Fragment{
  925. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  926. FilePath: "package.json",
  927. },
  928. allowlist: &config.Allowlist{
  929. MatchCondition: config.AllowlistMatchAnd,
  930. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  931. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  932. },
  933. expected: []report.Finding{
  934. {
  935. StartColumn: 50,
  936. EndColumn: 60,
  937. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  938. Match: "Summer2024!",
  939. Secret: "Summer2024!",
  940. File: "package.json",
  941. Entropy: 3.095795154571533,
  942. RuleID: "test-rule",
  943. },
  944. },
  945. },
  946. "commit AND path NOT allowed - other conditions": {
  947. fragment: Fragment{
  948. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  949. FilePath: "package-lock.json",
  950. },
  951. allowlist: &config.Allowlist{
  952. MatchCondition: config.AllowlistMatchAnd,
  953. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  954. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  955. Regexes: []*regexp.Regexp{regexp.MustCompile("password")},
  956. },
  957. expected: []report.Finding{
  958. {
  959. StartColumn: 50,
  960. EndColumn: 60,
  961. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  962. Match: "Summer2024!",
  963. Secret: "Summer2024!",
  964. File: "package-lock.json",
  965. Entropy: 3.095795154571533,
  966. RuleID: "test-rule",
  967. },
  968. },
  969. },
  970. "commit OR path allowed": {
  971. fragment: Fragment{
  972. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  973. FilePath: "package-lock.json",
  974. },
  975. allowlist: &config.Allowlist{
  976. MatchCondition: config.AllowlistMatchOr,
  977. Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
  978. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  979. },
  980. },
  981. // Regex / stopwords
  982. "regex allowed": {
  983. fragment: Fragment{},
  984. allowlist: &config.Allowlist{
  985. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  986. },
  987. },
  988. "stopwords allowed": {
  989. fragment: Fragment{},
  990. allowlist: &config.Allowlist{
  991. StopWords: []string{"summer"},
  992. },
  993. },
  994. "regex AND stopword allowed": {
  995. fragment: Fragment{},
  996. allowlist: &config.Allowlist{
  997. MatchCondition: config.AllowlistMatchAnd,
  998. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  999. StopWords: []string{"2024"},
  1000. },
  1001. },
  1002. "regex AND stopword allowed - other conditions": {
  1003. fragment: Fragment{
  1004. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  1005. FilePath: "config.js",
  1006. },
  1007. allowlist: &config.Allowlist{
  1008. MatchCondition: config.AllowlistMatchAnd,
  1009. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1010. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  1011. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1012. StopWords: []string{"2024"},
  1013. },
  1014. },
  1015. "regex AND stopword NOT allowed - non-git, other conditions": {
  1016. fragment: Fragment{
  1017. FilePath: "config.js",
  1018. },
  1019. allowlist: &config.Allowlist{
  1020. MatchCondition: config.AllowlistMatchAnd,
  1021. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1022. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  1023. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  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. File: "config.js",
  1034. Entropy: 3.095795154571533,
  1035. RuleID: "test-rule",
  1036. },
  1037. },
  1038. },
  1039. "regex AND stopword NOT allowed": {
  1040. fragment: Fragment{},
  1041. allowlist: &config.Allowlist{
  1042. MatchCondition: config.AllowlistMatchAnd,
  1043. Regexes: []*regexp.Regexp{
  1044. regexp.MustCompile(`(?i)winter.+`),
  1045. },
  1046. StopWords: []string{"2024"},
  1047. },
  1048. expected: []report.Finding{
  1049. {
  1050. StartColumn: 50,
  1051. EndColumn: 60,
  1052. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1053. Match: "Summer2024!",
  1054. Secret: "Summer2024!",
  1055. Entropy: 3.095795154571533,
  1056. RuleID: "test-rule",
  1057. },
  1058. },
  1059. },
  1060. "regex AND stopword NOT allowed - other conditions": {
  1061. fragment: Fragment{
  1062. CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
  1063. FilePath: "config.js",
  1064. },
  1065. allowlist: &config.Allowlist{
  1066. MatchCondition: config.AllowlistMatchAnd,
  1067. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1068. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  1069. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)winter.+`)},
  1070. StopWords: []string{"2024"},
  1071. },
  1072. expected: []report.Finding{
  1073. {
  1074. StartColumn: 50,
  1075. EndColumn: 60,
  1076. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1077. Match: "Summer2024!",
  1078. Secret: "Summer2024!",
  1079. File: "config.js",
  1080. Entropy: 3.095795154571533,
  1081. RuleID: "test-rule",
  1082. },
  1083. },
  1084. },
  1085. "regex OR stopword allowed": {
  1086. fragment: Fragment{},
  1087. allowlist: &config.Allowlist{
  1088. MatchCondition: config.AllowlistMatchOr,
  1089. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1090. StopWords: []string{"winter"},
  1091. },
  1092. },
  1093. }
  1094. raw := `let username = 'james@mail.com';
  1095. let password = 'Summer2024!';`
  1096. for name, tc := range cases {
  1097. t.Run(name, func(t *testing.T) {
  1098. rule := config.Rule{
  1099. RuleID: "test-rule",
  1100. Regex: regexp.MustCompile(`Summer2024!`),
  1101. Allowlists: []*config.Allowlist{
  1102. tc.allowlist,
  1103. },
  1104. }
  1105. d, err := NewDetectorDefaultConfig()
  1106. require.NoError(t, err)
  1107. f := tc.fragment
  1108. f.Raw = raw
  1109. actual := d.detectRule(f, raw, rule, []EncodedSegment{})
  1110. if diff := cmp.Diff(tc.expected, actual); diff != "" {
  1111. t.Errorf("diff: (-want +got)\n%s", diff)
  1112. }
  1113. })
  1114. }
  1115. }
  1116. func moveDotGit(t *testing.T, from, to string) {
  1117. t.Helper()
  1118. repoDirs, err := os.ReadDir("../testdata/repos")
  1119. require.NoError(t, err)
  1120. for _, dir := range repoDirs {
  1121. if to == ".git" {
  1122. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
  1123. if os.IsNotExist(err) {
  1124. // dont want to delete the only copy of .git accidentally
  1125. continue
  1126. }
  1127. os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
  1128. }
  1129. if !dir.IsDir() {
  1130. continue
  1131. }
  1132. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
  1133. if os.IsNotExist(err) {
  1134. continue
  1135. }
  1136. err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
  1137. fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
  1138. require.NoError(t, err)
  1139. }
  1140. }
  1141. // region Windows-specific tests[]
  1142. func TestNormalizeGitleaksIgnorePaths(t *testing.T) {
  1143. d, err := NewDetectorDefaultConfig()
  1144. require.NoError(t, err)
  1145. err = d.AddGitleaksIgnore("../testdata/gitleaksignore/.windowspaths")
  1146. require.NoError(t, err)
  1147. assert.Len(t, d.gitleaksIgnore, 3)
  1148. expected := map[string]struct{}{
  1149. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:4": {},
  1150. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:5": {},
  1151. "b55d88dc151f7022901cda41a03d43e0e508f2b7:test_data/test_local_repo_three_leaks.json:aws-access-token:73": {},
  1152. }
  1153. assert.ElementsMatch(t, maps.Keys(d.gitleaksIgnore), maps.Keys(expected))
  1154. }
  1155. func TestWindowsFileSeparator_RulePath(t *testing.T) {
  1156. logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
  1157. unixRule := config.Rule{
  1158. RuleID: "test-rule",
  1159. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1160. }
  1161. windowsRule := config.Rule{
  1162. RuleID: "test-rule",
  1163. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1164. }
  1165. expected := []report.Finding{
  1166. {
  1167. RuleID: "test-rule",
  1168. Match: "file detected: .m2/settings.xml",
  1169. File: ".m2/settings.xml",
  1170. },
  1171. }
  1172. tests := map[string]struct {
  1173. fragment Fragment
  1174. rule config.Rule
  1175. expected []report.Finding
  1176. }{
  1177. // unix rule
  1178. "unix rule - unix path separator": {
  1179. fragment: Fragment{
  1180. FilePath: `.m2/settings.xml`,
  1181. },
  1182. rule: unixRule,
  1183. expected: expected,
  1184. },
  1185. "unix rule - windows path separator": {
  1186. fragment: Fragment{
  1187. FilePath: `.m2/settings.xml`,
  1188. WindowsFilePath: `.m2\settings.xml`,
  1189. },
  1190. rule: unixRule,
  1191. expected: expected,
  1192. },
  1193. "unix regex+path rule - windows path separator": {
  1194. fragment: Fragment{
  1195. Raw: `<password>s3cr3t</password>`,
  1196. FilePath: `.m2/settings.xml`,
  1197. },
  1198. rule: config.Rule{
  1199. RuleID: "test-rule",
  1200. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1201. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1202. },
  1203. expected: []report.Finding{
  1204. {
  1205. RuleID: "test-rule",
  1206. StartColumn: 1,
  1207. EndColumn: 27,
  1208. Line: "<password>s3cr3t</password>",
  1209. Match: "<password>s3cr3t</password>",
  1210. Secret: "s3cr3t",
  1211. Entropy: 2.251629114151001,
  1212. File: ".m2/settings.xml",
  1213. },
  1214. },
  1215. },
  1216. // windows rule
  1217. "windows rule - unix path separator": {
  1218. fragment: Fragment{
  1219. FilePath: `.m2/settings.xml`,
  1220. },
  1221. rule: windowsRule,
  1222. // This never worked, and continues not to work.
  1223. // Paths should be normalized to use Unix file separators.
  1224. expected: nil,
  1225. },
  1226. "windows rule - windows path separator": {
  1227. fragment: Fragment{
  1228. FilePath: `.m2/settings.xml`,
  1229. WindowsFilePath: `.m2\settings.xml`,
  1230. },
  1231. rule: windowsRule,
  1232. expected: expected,
  1233. },
  1234. "windows regex+path rule - windows path separator": {
  1235. fragment: Fragment{
  1236. Raw: `<password>s3cr3t</password>`,
  1237. FilePath: `.m2/settings.xml`,
  1238. WindowsFilePath: `.m2\settings.xml`,
  1239. },
  1240. rule: config.Rule{
  1241. RuleID: "test-rule",
  1242. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1243. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1244. },
  1245. expected: []report.Finding{
  1246. {
  1247. RuleID: "test-rule",
  1248. StartColumn: 1,
  1249. EndColumn: 27,
  1250. Line: "<password>s3cr3t</password>",
  1251. Match: "<password>s3cr3t</password>",
  1252. Secret: "s3cr3t",
  1253. Entropy: 2.251629114151001,
  1254. File: ".m2/settings.xml",
  1255. },
  1256. }},
  1257. }
  1258. d, err := NewDetectorDefaultConfig()
  1259. require.NoError(t, err)
  1260. for name, test := range tests {
  1261. t.Run(name, func(t *testing.T) {
  1262. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1263. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1264. t.Errorf("diff: (-want +got)\n%s", diff)
  1265. }
  1266. })
  1267. }
  1268. }
  1269. func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
  1270. tests := map[string]struct {
  1271. fragment Fragment
  1272. rule config.Rule
  1273. expected []report.Finding
  1274. }{
  1275. // unix
  1276. "unix path separator - unix rule - OR allowlist path-only": {
  1277. fragment: Fragment{
  1278. Raw: `value: "s3cr3t"`,
  1279. FilePath: `ignoreme/unix.txt`,
  1280. },
  1281. rule: config.Rule{
  1282. RuleID: "unix-rule",
  1283. Regex: regexp.MustCompile(`s3cr3t`),
  1284. Allowlists: []*config.Allowlist{
  1285. {
  1286. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1287. },
  1288. },
  1289. },
  1290. expected: nil,
  1291. },
  1292. "unix path separator - windows rule - OR allowlist path-only": {
  1293. fragment: Fragment{
  1294. Raw: `value: "s3cr3t"`,
  1295. FilePath: `ignoreme/unix.txt`,
  1296. },
  1297. rule: config.Rule{
  1298. RuleID: "windows-rule",
  1299. Regex: regexp.MustCompile(`s3cr3t`),
  1300. Allowlists: []*config.Allowlist{
  1301. {
  1302. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1303. },
  1304. },
  1305. },
  1306. // Windows separators in regex don't work for unix.
  1307. expected: []report.Finding{
  1308. {
  1309. RuleID: "windows-rule",
  1310. StartColumn: 9,
  1311. EndColumn: 14,
  1312. Line: `value: "s3cr3t"`,
  1313. Match: `s3cr3t`,
  1314. Secret: `s3cr3t`,
  1315. File: "ignoreme/unix.txt",
  1316. Entropy: 2.251629114151001,
  1317. },
  1318. },
  1319. },
  1320. "unix path separator - unix rule - AND allowlist path+stopwords": {
  1321. fragment: Fragment{
  1322. Raw: `value: "f4k3s3cr3t"`,
  1323. FilePath: `ignoreme/unix.txt`,
  1324. },
  1325. rule: config.Rule{
  1326. RuleID: "unix-rule",
  1327. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1328. Allowlists: []*config.Allowlist{
  1329. {
  1330. MatchCondition: config.AllowlistMatchAnd,
  1331. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1332. StopWords: []string{"f4k3"},
  1333. },
  1334. },
  1335. },
  1336. expected: nil,
  1337. },
  1338. "unix path separator - windows rule - AND allowlist path+stopwords": {
  1339. fragment: Fragment{
  1340. Raw: `value: "f4k3s3cr3t"`,
  1341. FilePath: `ignoreme/unix.txt`,
  1342. },
  1343. rule: config.Rule{
  1344. RuleID: "windows-rule",
  1345. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1346. Allowlists: []*config.Allowlist{
  1347. {
  1348. MatchCondition: config.AllowlistMatchAnd,
  1349. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1350. StopWords: []string{"f4k3"},
  1351. },
  1352. },
  1353. },
  1354. expected: []report.Finding{
  1355. {
  1356. RuleID: "windows-rule",
  1357. StartColumn: 1,
  1358. EndColumn: 19,
  1359. Line: `value: "f4k3s3cr3t"`,
  1360. Match: `value: "f4k3s3cr3t"`,
  1361. Secret: `value: "f4k3s3cr3t"`,
  1362. File: "ignoreme/unix.txt",
  1363. Entropy: 3.892407178878784,
  1364. },
  1365. },
  1366. },
  1367. // windows
  1368. "windows path separator - unix rule - OR allowlist path-only": {
  1369. fragment: Fragment{
  1370. Raw: `value: "s3cr3t"`,
  1371. FilePath: `ignoreme/windows.txt`,
  1372. WindowsFilePath: `ignoreme\windows.txt`,
  1373. },
  1374. rule: config.Rule{
  1375. RuleID: "unix-rule",
  1376. Regex: regexp.MustCompile(`s3cr3t`),
  1377. Allowlists: []*config.Allowlist{
  1378. {
  1379. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1380. },
  1381. },
  1382. },
  1383. expected: nil,
  1384. },
  1385. "windows path separator - windows rule - OR allowlist path-only": {
  1386. fragment: Fragment{
  1387. Raw: `value: "s3cr3t"`,
  1388. FilePath: `ignoreme/windows.txt`,
  1389. WindowsFilePath: `ignoreme\windows.txt`,
  1390. },
  1391. rule: config.Rule{
  1392. RuleID: "windows-rule",
  1393. Regex: regexp.MustCompile(`s3cr3t`),
  1394. Allowlists: []*config.Allowlist{
  1395. {
  1396. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1397. },
  1398. },
  1399. },
  1400. expected: nil,
  1401. },
  1402. "windows path separator - unix rule - AND allowlist path+stopwords": {
  1403. fragment: Fragment{
  1404. Raw: `value: "f4k3s3cr3t"`,
  1405. FilePath: `ignoreme/unix.txt`,
  1406. WindowsFilePath: `ignoreme\windows.txt`,
  1407. },
  1408. rule: config.Rule{
  1409. RuleID: "unix-rule",
  1410. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1411. Allowlists: []*config.Allowlist{
  1412. {
  1413. MatchCondition: config.AllowlistMatchAnd,
  1414. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1415. StopWords: []string{"f4k3"},
  1416. },
  1417. },
  1418. },
  1419. expected: nil,
  1420. },
  1421. "windows path separator - windows rule - AND allowlist path+stopwords": {
  1422. fragment: Fragment{
  1423. Raw: `value: "f4k3s3cr3t"`,
  1424. FilePath: `ignoreme/unix.txt`,
  1425. WindowsFilePath: `ignoreme\windows.txt`,
  1426. },
  1427. rule: config.Rule{
  1428. RuleID: "windows-rule",
  1429. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1430. Allowlists: []*config.Allowlist{
  1431. {
  1432. MatchCondition: config.AllowlistMatchAnd,
  1433. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1434. StopWords: []string{"f4k3"},
  1435. },
  1436. },
  1437. },
  1438. expected: nil,
  1439. },
  1440. }
  1441. d, err := NewDetectorDefaultConfig()
  1442. require.NoError(t, err)
  1443. for name, test := range tests {
  1444. t.Run(name, func(t *testing.T) {
  1445. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1446. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1447. t.Errorf("diff: (-want +got)\n%s", diff)
  1448. }
  1449. })
  1450. }
  1451. }
  1452. //endregion