detect_test.go 48 KB

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