detect_test.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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 path when extending": {
  364. cfgName: "valid/allowlist_rule_extend_default",
  365. fragment: Fragment{
  366. Raw: `token = "aebfab88-7596-481d-82e8-c60c8f7de0c0"`,
  367. FilePath: "path/to/your/problematic/file.js",
  368. },
  369. },
  370. "allowlist - ignore regex": {
  371. cfgName: "valid/allowlist_rule_regex",
  372. fragment: Fragment{
  373. Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
  374. FilePath: "tmp.go",
  375. },
  376. },
  377. // Base64-decoding
  378. "detect base64": {
  379. cfgName: "base64_encoded",
  380. fragment: Fragment{
  381. Raw: b64TestValues,
  382. FilePath: "tmp.go",
  383. },
  384. expectedFindings: []report.Finding{
  385. { // Plain text key captured by normal rule
  386. Description: "Private Key",
  387. Secret: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  388. Match: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  389. File: "tmp.go",
  390. Line: "\n-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  391. RuleID: "private-key",
  392. Tags: []string{"key", "private"},
  393. StartLine: 2,
  394. EndLine: 5,
  395. StartColumn: 2,
  396. EndColumn: 26,
  397. Entropy: 5.350665,
  398. },
  399. { // Encoded key captured by custom b64 regex rule
  400. Description: "Private Key",
  401. Secret: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
  402. Match: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
  403. File: "tmp.go",
  404. Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
  405. RuleID: "b64-encoded-private-key",
  406. Tags: []string{"key", "private"},
  407. StartLine: 8,
  408. EndLine: 8,
  409. StartColumn: 16,
  410. EndColumn: 207,
  411. Entropy: 5.3861146,
  412. },
  413. { // Encoded key captured by plain text rule using the decoder
  414. Description: "Private Key",
  415. Secret: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  416. Match: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
  417. File: "tmp.go",
  418. Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
  419. RuleID: "private-key",
  420. Tags: []string{"key", "private", "decoded:base64", "decode-depth:1"},
  421. StartLine: 8,
  422. EndLine: 8,
  423. StartColumn: 16,
  424. EndColumn: 207,
  425. Entropy: 5.350665,
  426. },
  427. { // Encoded AWS config with a access key id inside a JWT
  428. Description: "AWS IAM Unique Identifier",
  429. Secret: "ASIAIOSFODNN7LXM10JI",
  430. Match: " ASIAIOSFODNN7LXM10JI",
  431. File: "tmp.go",
  432. Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
  433. RuleID: "aws-iam-unique-identifier",
  434. Tags: []string{"aws", "identifier", "decoded:base64", "decode-depth:2"},
  435. StartLine: 11,
  436. EndLine: 11,
  437. StartColumn: 39,
  438. EndColumn: 344,
  439. Entropy: 3.6841838,
  440. },
  441. { // Encoded AWS config with a secret access key inside a JWT
  442. Description: "AWS Secret Access Key",
  443. Secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
  444. Match: "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
  445. File: "tmp.go",
  446. Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
  447. RuleID: "aws-secret-access-key",
  448. Tags: []string{"aws", "secret", "decoded:base64", "decode-depth:2"},
  449. StartLine: 11,
  450. EndLine: 11,
  451. StartColumn: 39,
  452. EndColumn: 344,
  453. Entropy: 4.721928,
  454. },
  455. { // Encoded Small secret at the end to make sure it's picked up by the decoding
  456. Description: "Small Secret",
  457. Secret: "small-secret",
  458. Match: "small-secret",
  459. File: "tmp.go",
  460. Line: "\nc21hbGwtc2VjcmV0",
  461. RuleID: "small-secret",
  462. Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
  463. StartLine: 15,
  464. EndLine: 15,
  465. StartColumn: 2,
  466. EndColumn: 17,
  467. Entropy: 3.0849626,
  468. },
  469. { // Secret where the decoded match goes outside the encoded value
  470. Description: "Overlapping",
  471. Secret: "decoded-secret-value",
  472. Match: "secret=decoded-secret-value",
  473. File: "tmp.go",
  474. Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=",
  475. RuleID: "overlapping",
  476. Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
  477. StartLine: 18,
  478. EndLine: 18,
  479. StartColumn: 2,
  480. EndColumn: 36,
  481. Entropy: 3.3037016,
  482. },
  483. { // Secret where the decoded match goes outside the encoded value and then encoded again
  484. Description: "Overlapping",
  485. Secret: "decoded-secret-value",
  486. Match: "secret=decoded-secret-value",
  487. File: "tmp.go",
  488. Line: "\nc2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=",
  489. RuleID: "overlapping",
  490. Tags: []string{"overlapping", "decoded:base64", "decode-depth:2"},
  491. StartLine: 20,
  492. EndLine: 20,
  493. StartColumn: 2,
  494. EndColumn: 49,
  495. Entropy: 3.3037016,
  496. },
  497. { // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good)
  498. Description: "Make sure this would be detected with no allowlist",
  499. Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw",
  500. Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"",
  501. File: "tmp.go",
  502. Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"",
  503. RuleID: "decoded-password-dont-ignore",
  504. Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"},
  505. StartLine: 23,
  506. EndLine: 23,
  507. StartColumn: 2,
  508. EndColumn: 68,
  509. Entropy: 4.5841837,
  510. },
  511. },
  512. },
  513. }
  514. for name, tt := range tests {
  515. t.Run(name, func(t *testing.T) {
  516. viper.Reset()
  517. viper.AddConfigPath(configPath)
  518. viper.SetConfigName(tt.cfgName)
  519. viper.SetConfigType("toml")
  520. err := viper.ReadInConfig()
  521. require.NoError(t, err)
  522. var vc config.ViperConfig
  523. err = viper.Unmarshal(&vc)
  524. require.NoError(t, err)
  525. cfg, err := vc.Translate()
  526. cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
  527. assert.Equal(t, tt.wantError, err)
  528. d := NewDetector(cfg)
  529. d.MaxDecodeDepth = maxDecodeDepth
  530. d.baselinePath = tt.baselinePath
  531. findings := d.Detect(tt.fragment)
  532. assert.ElementsMatch(t, tt.expectedFindings, findings)
  533. })
  534. }
  535. }
  536. // TestFromGit tests the FromGit function
  537. func TestFromGit(t *testing.T) {
  538. // TODO: Fix this test on windows.
  539. if runtime.GOOS == "windows" {
  540. t.Skipf("TODO: this fails on Windows: [git] fatal: bad object refs/remotes/origin/main?")
  541. return
  542. }
  543. tests := []struct {
  544. cfgName string
  545. source string
  546. logOpts string
  547. expectedFindings []report.Finding
  548. }{
  549. {
  550. source: filepath.Join(repoBasePath, "small"),
  551. cfgName: "simple", // the remote url is `git@github.com:gitleaks/test.git`
  552. expectedFindings: []report.Finding{
  553. {
  554. RuleID: "aws-access-key",
  555. Description: "AWS Access Key",
  556. StartLine: 20,
  557. EndLine: 20,
  558. StartColumn: 19,
  559. EndColumn: 38,
  560. Line: "\n awsToken := \"AKIALALEMEL33243OLIA\"",
  561. Secret: "AKIALALEMEL33243OLIA",
  562. Match: "AKIALALEMEL33243OLIA",
  563. Entropy: 3.0841837,
  564. File: "main.go",
  565. Date: "2021-11-02T23:37:53Z",
  566. Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
  567. Author: "Zachary Rice",
  568. Email: "zricer@protonmail.com",
  569. Message: "Accidentally add a secret",
  570. Tags: []string{"key", "AWS"},
  571. Fingerprint: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587:main.go:aws-access-key:20",
  572. Link: "https://github.com/gitleaks/test/blob/1b6da43b82b22e4eaa10bcf8ee591e91abbfc587/main.go#L20",
  573. },
  574. {
  575. RuleID: "aws-access-key",
  576. Description: "AWS Access Key",
  577. StartLine: 9,
  578. EndLine: 9,
  579. StartColumn: 17,
  580. EndColumn: 36,
  581. Secret: "AKIALALEMEL33243OLIA",
  582. Match: "AKIALALEMEL33243OLIA",
  583. Line: "\n\taws_token := \"AKIALALEMEL33243OLIA\"",
  584. File: "foo/foo.go",
  585. Date: "2021-11-02T23:48:06Z",
  586. Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
  587. Author: "Zach Rice",
  588. Email: "zricer@protonmail.com",
  589. Message: "adding foo package with secret",
  590. Tags: []string{"key", "AWS"},
  591. Entropy: 3.0841837,
  592. Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
  593. Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
  594. },
  595. },
  596. },
  597. {
  598. source: filepath.Join(repoBasePath, "small"),
  599. logOpts: "--all foo...",
  600. cfgName: "simple",
  601. expectedFindings: []report.Finding{
  602. {
  603. RuleID: "aws-access-key",
  604. Description: "AWS Access Key",
  605. StartLine: 9,
  606. EndLine: 9,
  607. StartColumn: 17,
  608. EndColumn: 36,
  609. Secret: "AKIALALEMEL33243OLIA",
  610. Line: "\n\taws_token := \"AKIALALEMEL33243OLIA\"",
  611. Match: "AKIALALEMEL33243OLIA",
  612. Date: "2021-11-02T23:48:06Z",
  613. File: "foo/foo.go",
  614. Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
  615. Author: "Zach Rice",
  616. Email: "zricer@protonmail.com",
  617. Message: "adding foo package with secret",
  618. Tags: []string{"key", "AWS"},
  619. Entropy: 3.0841837,
  620. Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
  621. Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
  622. },
  623. },
  624. },
  625. }
  626. moveDotGit(t, "dotGit", ".git")
  627. defer moveDotGit(t, ".git", "dotGit")
  628. for _, tt := range tests {
  629. t.Run(strings.Join([]string{tt.cfgName, tt.source, tt.logOpts}, "/"), func(t *testing.T) {
  630. viper.AddConfigPath(configPath)
  631. viper.SetConfigName("simple")
  632. viper.SetConfigType("toml")
  633. err := viper.ReadInConfig()
  634. require.NoError(t, err)
  635. var vc config.ViperConfig
  636. err = viper.Unmarshal(&vc)
  637. require.NoError(t, err)
  638. cfg, err := vc.Translate()
  639. require.NoError(t, err)
  640. detector := NewDetector(cfg)
  641. var ignorePath string
  642. info, err := os.Stat(tt.source)
  643. require.NoError(t, err)
  644. if info.IsDir() {
  645. ignorePath = filepath.Join(tt.source, ".gitleaksignore")
  646. } else {
  647. ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
  648. }
  649. err = detector.AddGitleaksIgnore(ignorePath)
  650. require.NoError(t, err)
  651. gitCmd, err := sources.NewGitLogCmd(tt.source, tt.logOpts)
  652. require.NoError(t, err)
  653. remote := NewRemoteInfo(scm.UnknownPlatform, tt.source)
  654. findings, err := detector.DetectGit(gitCmd, remote)
  655. require.NoError(t, err)
  656. for _, f := range findings {
  657. f.Match = "" // remove lines cause copying and pasting them has some wack formatting
  658. }
  659. assert.ElementsMatch(t, tt.expectedFindings, findings)
  660. })
  661. }
  662. }
  663. func TestFromGitStaged(t *testing.T) {
  664. tests := []struct {
  665. cfgName string
  666. source string
  667. logOpts string
  668. expectedFindings []report.Finding
  669. }{
  670. {
  671. source: filepath.Join(repoBasePath, "staged"),
  672. cfgName: "simple",
  673. expectedFindings: []report.Finding{
  674. {
  675. RuleID: "aws-access-key",
  676. Description: "AWS Access Key",
  677. StartLine: 7,
  678. EndLine: 7,
  679. StartColumn: 18,
  680. EndColumn: 37,
  681. Line: "\n\taws_token2 := \"AKIALALEMEL33243OLIA\" // this one is not",
  682. Match: "AKIALALEMEL33243OLIA",
  683. Secret: "AKIALALEMEL33243OLIA",
  684. File: "api/api.go",
  685. SymlinkFile: "",
  686. Commit: "",
  687. Entropy: 3.0841837,
  688. Author: "",
  689. Email: "",
  690. Date: "0001-01-01T00:00:00Z",
  691. Message: "",
  692. Tags: []string{
  693. "key",
  694. "AWS",
  695. },
  696. Fingerprint: "api/api.go:aws-access-key:7",
  697. Link: "",
  698. },
  699. },
  700. },
  701. }
  702. moveDotGit(t, "dotGit", ".git")
  703. defer moveDotGit(t, ".git", "dotGit")
  704. for _, tt := range tests {
  705. viper.AddConfigPath(configPath)
  706. viper.SetConfigName("simple")
  707. viper.SetConfigType("toml")
  708. err := viper.ReadInConfig()
  709. require.NoError(t, err)
  710. var vc config.ViperConfig
  711. err = viper.Unmarshal(&vc)
  712. require.NoError(t, err)
  713. cfg, err := vc.Translate()
  714. require.NoError(t, err)
  715. detector := NewDetector(cfg)
  716. err = detector.AddGitleaksIgnore(filepath.Join(tt.source, ".gitleaksignore"))
  717. require.NoError(t, err)
  718. gitCmd, err := sources.NewGitDiffCmd(tt.source, true)
  719. require.NoError(t, err)
  720. remote := NewRemoteInfo(scm.UnknownPlatform, tt.source)
  721. findings, err := detector.DetectGit(gitCmd, remote)
  722. require.NoError(t, err)
  723. for _, f := range findings {
  724. f.Match = "" // remove lines cause copying and pasting them has some wack formatting
  725. }
  726. assert.ElementsMatch(t, tt.expectedFindings, findings)
  727. }
  728. }
  729. // TestFromFiles tests the FromFiles function
  730. func TestFromFiles(t *testing.T) {
  731. tests := []struct {
  732. cfgName string
  733. source string
  734. expectedFindings []report.Finding
  735. }{
  736. {
  737. source: filepath.Join(repoBasePath, "nogit"),
  738. cfgName: "simple",
  739. expectedFindings: []report.Finding{
  740. {
  741. RuleID: "aws-access-key",
  742. Description: "AWS Access Key",
  743. StartLine: 20,
  744. EndLine: 20,
  745. StartColumn: 16,
  746. EndColumn: 35,
  747. Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
  748. Match: "AKIALALEMEL33243OLIA",
  749. Secret: "AKIALALEMEL33243OLIA",
  750. File: "../testdata/repos/nogit/main.go",
  751. SymlinkFile: "",
  752. Tags: []string{"key", "AWS"},
  753. Entropy: 3.0841837,
  754. Fingerprint: "../testdata/repos/nogit/main.go:aws-access-key:20",
  755. },
  756. },
  757. },
  758. {
  759. source: filepath.Join(repoBasePath, "nogit", "main.go"),
  760. cfgName: "simple",
  761. expectedFindings: []report.Finding{
  762. {
  763. RuleID: "aws-access-key",
  764. Description: "AWS Access Key",
  765. StartLine: 20,
  766. EndLine: 20,
  767. StartColumn: 16,
  768. EndColumn: 35,
  769. Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
  770. Match: "AKIALALEMEL33243OLIA",
  771. Secret: "AKIALALEMEL33243OLIA",
  772. File: "../testdata/repos/nogit/main.go",
  773. Tags: []string{"key", "AWS"},
  774. Entropy: 3.0841837,
  775. Fingerprint: "../testdata/repos/nogit/main.go:aws-access-key:20",
  776. },
  777. },
  778. },
  779. {
  780. source: filepath.Join(repoBasePath, "nogit", "api.go"),
  781. cfgName: "simple",
  782. expectedFindings: []report.Finding{},
  783. },
  784. {
  785. source: filepath.Join(repoBasePath, "nogit", ".env.prod"),
  786. cfgName: "generic",
  787. expectedFindings: []report.Finding{
  788. {
  789. RuleID: "generic-api-key",
  790. Description: "Generic API Key",
  791. StartLine: 4,
  792. EndLine: 4,
  793. StartColumn: 5,
  794. EndColumn: 35,
  795. Line: "\nDB_PASSWORD=8ae31cacf141669ddfb5da",
  796. Match: "PASSWORD=8ae31cacf141669ddfb5da",
  797. Secret: "8ae31cacf141669ddfb5da",
  798. File: "../testdata/repos/nogit/.env.prod",
  799. Tags: []string{},
  800. Entropy: 3.5383105,
  801. Fingerprint: "../testdata/repos/nogit/.env.prod:generic-api-key:4",
  802. },
  803. },
  804. },
  805. }
  806. for _, tt := range tests {
  807. t.Run(tt.cfgName+" - "+tt.source, func(t *testing.T) {
  808. viper.AddConfigPath(configPath)
  809. viper.SetConfigName(tt.cfgName)
  810. viper.SetConfigType("toml")
  811. err := viper.ReadInConfig()
  812. require.NoError(t, err)
  813. var vc config.ViperConfig
  814. err = viper.Unmarshal(&vc)
  815. require.NoError(t, err)
  816. cfg, _ := vc.Translate()
  817. detector := NewDetector(cfg)
  818. info, err := os.Stat(tt.source)
  819. require.NoError(t, err)
  820. var ignorePath string
  821. if info.IsDir() {
  822. ignorePath = filepath.Join(tt.source, ".gitleaksignore")
  823. } else {
  824. ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
  825. }
  826. err = detector.AddGitleaksIgnore(ignorePath)
  827. require.NoError(t, err)
  828. detector.FollowSymlinks = true
  829. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
  830. require.NoError(t, err)
  831. findings, err := detector.DetectFiles(paths)
  832. require.NoError(t, err)
  833. // TODO: Temporary mitigation.
  834. // https://github.com/gitleaks/gitleaks/issues/1641
  835. normalizedFindings := make([]report.Finding, len(findings))
  836. for i, f := range findings {
  837. if strings.HasSuffix(f.Line, "\r") {
  838. f.Line = strings.ReplaceAll(f.Line, "\r", "")
  839. }
  840. if strings.HasSuffix(f.Match, "\r") {
  841. f.EndColumn = f.EndColumn - 1
  842. f.Match = strings.ReplaceAll(f.Match, "\r", "")
  843. }
  844. normalizedFindings[i] = f
  845. }
  846. assert.ElementsMatch(t, tt.expectedFindings, normalizedFindings)
  847. })
  848. }
  849. }
  850. func TestDetectWithSymlinks(t *testing.T) {
  851. // TODO: Fix this test on windows.
  852. if runtime.GOOS == "windows" {
  853. t.Skipf("TODO: this returns no results on windows, I'm not sure why.")
  854. return
  855. }
  856. tests := []struct {
  857. cfgName string
  858. source string
  859. expectedFindings []report.Finding
  860. }{
  861. {
  862. source: filepath.Join(repoBasePath, "symlinks/file_symlink"),
  863. cfgName: "simple",
  864. expectedFindings: []report.Finding{
  865. {
  866. RuleID: "apkey",
  867. Description: "Asymmetric Private Key",
  868. StartLine: 1,
  869. EndLine: 1,
  870. StartColumn: 1,
  871. EndColumn: 35,
  872. Match: "-----BEGIN OPENSSH PRIVATE KEY-----",
  873. Secret: "-----BEGIN OPENSSH PRIVATE KEY-----",
  874. Line: "-----BEGIN OPENSSH PRIVATE KEY-----",
  875. File: "../testdata/repos/symlinks/source_file/id_ed25519",
  876. SymlinkFile: "../testdata/repos/symlinks/file_symlink/symlinked_id_ed25519",
  877. Tags: []string{"key", "AsymmetricPrivateKey"},
  878. Entropy: 3.587164,
  879. Fingerprint: "../testdata/repos/symlinks/source_file/id_ed25519:apkey:1",
  880. },
  881. },
  882. },
  883. }
  884. for _, tt := range tests {
  885. viper.AddConfigPath(configPath)
  886. viper.SetConfigName("simple")
  887. viper.SetConfigType("toml")
  888. err := viper.ReadInConfig()
  889. require.NoError(t, err)
  890. var vc config.ViperConfig
  891. err = viper.Unmarshal(&vc)
  892. require.NoError(t, err)
  893. cfg, _ := vc.Translate()
  894. detector := NewDetector(cfg)
  895. detector.FollowSymlinks = true
  896. paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
  897. require.NoError(t, err)
  898. findings, err := detector.DetectFiles(paths)
  899. require.NoError(t, err)
  900. assert.ElementsMatch(t, tt.expectedFindings, findings)
  901. }
  902. }
  903. func TestDetectRuleAllowlist(t *testing.T) {
  904. cases := map[string]struct {
  905. fragment Fragment
  906. allowlist *config.Allowlist
  907. expected []report.Finding
  908. }{
  909. // Commit / path
  910. "commit allowed": {
  911. fragment: Fragment{
  912. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  913. },
  914. allowlist: &config.Allowlist{
  915. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  916. },
  917. },
  918. "path allowed": {
  919. fragment: Fragment{
  920. FilePath: "package-lock.json",
  921. },
  922. allowlist: &config.Allowlist{
  923. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  924. },
  925. },
  926. "commit AND path allowed": {
  927. fragment: Fragment{
  928. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  929. FilePath: "package-lock.json",
  930. },
  931. allowlist: &config.Allowlist{
  932. MatchCondition: config.AllowlistMatchAnd,
  933. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  934. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  935. },
  936. },
  937. "commit AND path NOT allowed": {
  938. fragment: Fragment{
  939. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  940. FilePath: "package.json",
  941. },
  942. allowlist: &config.Allowlist{
  943. MatchCondition: config.AllowlistMatchAnd,
  944. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  945. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  946. },
  947. expected: []report.Finding{
  948. {
  949. StartColumn: 50,
  950. EndColumn: 60,
  951. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  952. Match: "Summer2024!",
  953. Secret: "Summer2024!",
  954. File: "package.json",
  955. Entropy: 3.095795154571533,
  956. RuleID: "test-rule",
  957. },
  958. },
  959. },
  960. "commit AND path NOT allowed - other conditions": {
  961. fragment: Fragment{
  962. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  963. FilePath: "package-lock.json",
  964. },
  965. allowlist: &config.Allowlist{
  966. MatchCondition: config.AllowlistMatchAnd,
  967. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  968. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  969. Regexes: []*regexp.Regexp{regexp.MustCompile("password")},
  970. },
  971. expected: []report.Finding{
  972. {
  973. StartColumn: 50,
  974. EndColumn: 60,
  975. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  976. Match: "Summer2024!",
  977. Secret: "Summer2024!",
  978. File: "package-lock.json",
  979. Entropy: 3.095795154571533,
  980. RuleID: "test-rule",
  981. },
  982. },
  983. },
  984. "commit OR path allowed": {
  985. fragment: Fragment{
  986. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  987. FilePath: "package-lock.json",
  988. },
  989. allowlist: &config.Allowlist{
  990. MatchCondition: config.AllowlistMatchOr,
  991. Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
  992. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  993. },
  994. },
  995. // Regex / stopwords
  996. "regex allowed": {
  997. fragment: Fragment{},
  998. allowlist: &config.Allowlist{
  999. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1000. },
  1001. },
  1002. "stopwords allowed": {
  1003. fragment: Fragment{},
  1004. allowlist: &config.Allowlist{
  1005. StopWords: []string{"summer"},
  1006. },
  1007. },
  1008. "regex AND stopword allowed": {
  1009. fragment: Fragment{},
  1010. allowlist: &config.Allowlist{
  1011. MatchCondition: config.AllowlistMatchAnd,
  1012. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1013. StopWords: []string{"2024"},
  1014. },
  1015. },
  1016. "regex AND stopword allowed - other conditions": {
  1017. fragment: Fragment{
  1018. CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
  1019. FilePath: "config.js",
  1020. },
  1021. allowlist: &config.Allowlist{
  1022. MatchCondition: config.AllowlistMatchAnd,
  1023. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1024. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  1025. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1026. StopWords: []string{"2024"},
  1027. },
  1028. },
  1029. "regex AND stopword NOT allowed - non-git, other conditions": {
  1030. fragment: Fragment{
  1031. FilePath: "config.js",
  1032. },
  1033. allowlist: &config.Allowlist{
  1034. MatchCondition: config.AllowlistMatchAnd,
  1035. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1036. Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
  1037. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1038. StopWords: []string{"2024"},
  1039. },
  1040. expected: []report.Finding{
  1041. {
  1042. StartColumn: 50,
  1043. EndColumn: 60,
  1044. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1045. Match: "Summer2024!",
  1046. Secret: "Summer2024!",
  1047. File: "config.js",
  1048. Entropy: 3.095795154571533,
  1049. RuleID: "test-rule",
  1050. },
  1051. },
  1052. },
  1053. "regex AND stopword NOT allowed": {
  1054. fragment: Fragment{},
  1055. allowlist: &config.Allowlist{
  1056. MatchCondition: config.AllowlistMatchAnd,
  1057. Regexes: []*regexp.Regexp{
  1058. regexp.MustCompile(`(?i)winter.+`),
  1059. },
  1060. StopWords: []string{"2024"},
  1061. },
  1062. expected: []report.Finding{
  1063. {
  1064. StartColumn: 50,
  1065. EndColumn: 60,
  1066. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1067. Match: "Summer2024!",
  1068. Secret: "Summer2024!",
  1069. Entropy: 3.095795154571533,
  1070. RuleID: "test-rule",
  1071. },
  1072. },
  1073. },
  1074. "regex AND stopword NOT allowed - other conditions": {
  1075. fragment: Fragment{
  1076. CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
  1077. FilePath: "config.js",
  1078. },
  1079. allowlist: &config.Allowlist{
  1080. MatchCondition: config.AllowlistMatchAnd,
  1081. Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
  1082. Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
  1083. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)winter.+`)},
  1084. StopWords: []string{"2024"},
  1085. },
  1086. expected: []report.Finding{
  1087. {
  1088. StartColumn: 50,
  1089. EndColumn: 60,
  1090. Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
  1091. Match: "Summer2024!",
  1092. Secret: "Summer2024!",
  1093. File: "config.js",
  1094. Entropy: 3.095795154571533,
  1095. RuleID: "test-rule",
  1096. },
  1097. },
  1098. },
  1099. "regex OR stopword allowed": {
  1100. fragment: Fragment{},
  1101. allowlist: &config.Allowlist{
  1102. MatchCondition: config.AllowlistMatchOr,
  1103. Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
  1104. StopWords: []string{"winter"},
  1105. },
  1106. },
  1107. }
  1108. raw := `let username = 'james@mail.com';
  1109. let password = 'Summer2024!';`
  1110. for name, tc := range cases {
  1111. t.Run(name, func(t *testing.T) {
  1112. rule := config.Rule{
  1113. RuleID: "test-rule",
  1114. Regex: regexp.MustCompile(`Summer2024!`),
  1115. Allowlists: []*config.Allowlist{
  1116. tc.allowlist,
  1117. },
  1118. }
  1119. d, err := NewDetectorDefaultConfig()
  1120. require.NoError(t, err)
  1121. f := tc.fragment
  1122. f.Raw = raw
  1123. actual := d.detectRule(f, raw, rule, []EncodedSegment{})
  1124. if diff := cmp.Diff(tc.expected, actual); diff != "" {
  1125. t.Errorf("diff: (-want +got)\n%s", diff)
  1126. }
  1127. })
  1128. }
  1129. }
  1130. func moveDotGit(t *testing.T, from, to string) {
  1131. t.Helper()
  1132. repoDirs, err := os.ReadDir("../testdata/repos")
  1133. require.NoError(t, err)
  1134. for _, dir := range repoDirs {
  1135. if to == ".git" {
  1136. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
  1137. if os.IsNotExist(err) {
  1138. // dont want to delete the only copy of .git accidentally
  1139. continue
  1140. }
  1141. os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
  1142. }
  1143. if !dir.IsDir() {
  1144. continue
  1145. }
  1146. _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
  1147. if os.IsNotExist(err) {
  1148. continue
  1149. }
  1150. err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
  1151. fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
  1152. require.NoError(t, err)
  1153. }
  1154. }
  1155. // region Windows-specific tests[]
  1156. func TestNormalizeGitleaksIgnorePaths(t *testing.T) {
  1157. d, err := NewDetectorDefaultConfig()
  1158. require.NoError(t, err)
  1159. err = d.AddGitleaksIgnore("../testdata/gitleaksignore/.windowspaths")
  1160. require.NoError(t, err)
  1161. assert.Len(t, d.gitleaksIgnore, 3)
  1162. expected := map[string]struct{}{
  1163. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:4": {},
  1164. "foo/bar/gitleaks-false-positive.yaml:aws-access-token:5": {},
  1165. "b55d88dc151f7022901cda41a03d43e0e508f2b7:test_data/test_local_repo_three_leaks.json:aws-access-token:73": {},
  1166. }
  1167. assert.ElementsMatch(t, maps.Keys(d.gitleaksIgnore), maps.Keys(expected))
  1168. }
  1169. func TestWindowsFileSeparator_RulePath(t *testing.T) {
  1170. unixRule := config.Rule{
  1171. RuleID: "test-rule",
  1172. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1173. }
  1174. windowsRule := config.Rule{
  1175. RuleID: "test-rule",
  1176. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1177. }
  1178. expected := []report.Finding{
  1179. {
  1180. RuleID: "test-rule",
  1181. Match: "file detected: .m2/settings.xml",
  1182. File: ".m2/settings.xml",
  1183. },
  1184. }
  1185. tests := map[string]struct {
  1186. fragment Fragment
  1187. rule config.Rule
  1188. expected []report.Finding
  1189. }{
  1190. // unix rule
  1191. "unix rule - unix path separator": {
  1192. fragment: Fragment{
  1193. FilePath: `.m2/settings.xml`,
  1194. },
  1195. rule: unixRule,
  1196. expected: expected,
  1197. },
  1198. "unix rule - windows path separator": {
  1199. fragment: Fragment{
  1200. FilePath: `.m2/settings.xml`,
  1201. WindowsFilePath: `.m2\settings.xml`,
  1202. },
  1203. rule: unixRule,
  1204. expected: expected,
  1205. },
  1206. "unix regex+path rule - windows path separator": {
  1207. fragment: Fragment{
  1208. Raw: `<password>s3cr3t</password>`,
  1209. FilePath: `.m2/settings.xml`,
  1210. },
  1211. rule: config.Rule{
  1212. RuleID: "test-rule",
  1213. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1214. Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
  1215. },
  1216. expected: []report.Finding{
  1217. {
  1218. RuleID: "test-rule",
  1219. StartColumn: 1,
  1220. EndColumn: 27,
  1221. Line: "<password>s3cr3t</password>",
  1222. Match: "<password>s3cr3t</password>",
  1223. Secret: "s3cr3t",
  1224. Entropy: 2.251629114151001,
  1225. File: ".m2/settings.xml",
  1226. },
  1227. },
  1228. },
  1229. // windows rule
  1230. "windows rule - unix path separator": {
  1231. fragment: Fragment{
  1232. FilePath: `.m2/settings.xml`,
  1233. },
  1234. rule: windowsRule,
  1235. // This never worked, and continues not to work.
  1236. // Paths should be normalized to use Unix file separators.
  1237. expected: nil,
  1238. },
  1239. "windows rule - windows path separator": {
  1240. fragment: Fragment{
  1241. FilePath: `.m2/settings.xml`,
  1242. WindowsFilePath: `.m2\settings.xml`,
  1243. },
  1244. rule: windowsRule,
  1245. expected: expected,
  1246. },
  1247. "windows regex+path rule - windows path separator": {
  1248. fragment: Fragment{
  1249. Raw: `<password>s3cr3t</password>`,
  1250. FilePath: `.m2/settings.xml`,
  1251. WindowsFilePath: `.m2\settings.xml`,
  1252. },
  1253. rule: config.Rule{
  1254. RuleID: "test-rule",
  1255. Regex: regexp.MustCompile(`<password>(.+?)</password>`),
  1256. Path: regexp.MustCompile(`(^|\\)\.m2\\settings\.xml`),
  1257. },
  1258. expected: []report.Finding{
  1259. {
  1260. RuleID: "test-rule",
  1261. StartColumn: 1,
  1262. EndColumn: 27,
  1263. Line: "<password>s3cr3t</password>",
  1264. Match: "<password>s3cr3t</password>",
  1265. Secret: "s3cr3t",
  1266. Entropy: 2.251629114151001,
  1267. File: ".m2/settings.xml",
  1268. },
  1269. }},
  1270. }
  1271. d, err := NewDetectorDefaultConfig()
  1272. require.NoError(t, err)
  1273. for name, test := range tests {
  1274. t.Run(name, func(t *testing.T) {
  1275. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1276. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1277. t.Errorf("diff: (-want +got)\n%s", diff)
  1278. }
  1279. })
  1280. }
  1281. }
  1282. func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
  1283. tests := map[string]struct {
  1284. fragment Fragment
  1285. rule config.Rule
  1286. expected []report.Finding
  1287. }{
  1288. // unix
  1289. "unix path separator - unix rule - OR allowlist path-only": {
  1290. fragment: Fragment{
  1291. Raw: `value: "s3cr3t"`,
  1292. FilePath: `ignoreme/unix.txt`,
  1293. },
  1294. rule: config.Rule{
  1295. RuleID: "unix-rule",
  1296. Regex: regexp.MustCompile(`s3cr3t`),
  1297. Allowlists: []*config.Allowlist{
  1298. {
  1299. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1300. },
  1301. },
  1302. },
  1303. expected: nil,
  1304. },
  1305. "unix path separator - windows rule - OR allowlist path-only": {
  1306. fragment: Fragment{
  1307. Raw: `value: "s3cr3t"`,
  1308. FilePath: `ignoreme/unix.txt`,
  1309. },
  1310. rule: config.Rule{
  1311. RuleID: "windows-rule",
  1312. Regex: regexp.MustCompile(`s3cr3t`),
  1313. Allowlists: []*config.Allowlist{
  1314. {
  1315. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1316. },
  1317. },
  1318. },
  1319. // Windows separators in regex don't work for unix.
  1320. expected: []report.Finding{
  1321. {
  1322. RuleID: "windows-rule",
  1323. StartColumn: 9,
  1324. EndColumn: 14,
  1325. Line: `value: "s3cr3t"`,
  1326. Match: `s3cr3t`,
  1327. Secret: `s3cr3t`,
  1328. File: "ignoreme/unix.txt",
  1329. Entropy: 2.251629114151001,
  1330. },
  1331. },
  1332. },
  1333. "unix path separator - unix rule - AND allowlist path+stopwords": {
  1334. fragment: Fragment{
  1335. Raw: `value: "f4k3s3cr3t"`,
  1336. FilePath: `ignoreme/unix.txt`,
  1337. },
  1338. rule: config.Rule{
  1339. RuleID: "unix-rule",
  1340. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1341. Allowlists: []*config.Allowlist{
  1342. {
  1343. MatchCondition: config.AllowlistMatchAnd,
  1344. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1345. StopWords: []string{"f4k3"},
  1346. },
  1347. },
  1348. },
  1349. expected: nil,
  1350. },
  1351. "unix path separator - windows rule - AND allowlist path+stopwords": {
  1352. fragment: Fragment{
  1353. Raw: `value: "f4k3s3cr3t"`,
  1354. FilePath: `ignoreme/unix.txt`,
  1355. },
  1356. rule: config.Rule{
  1357. RuleID: "windows-rule",
  1358. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1359. Allowlists: []*config.Allowlist{
  1360. {
  1361. MatchCondition: config.AllowlistMatchAnd,
  1362. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1363. StopWords: []string{"f4k3"},
  1364. },
  1365. },
  1366. },
  1367. expected: []report.Finding{
  1368. {
  1369. RuleID: "windows-rule",
  1370. StartColumn: 1,
  1371. EndColumn: 19,
  1372. Line: `value: "f4k3s3cr3t"`,
  1373. Match: `value: "f4k3s3cr3t"`,
  1374. Secret: `value: "f4k3s3cr3t"`,
  1375. File: "ignoreme/unix.txt",
  1376. Entropy: 3.892407178878784,
  1377. },
  1378. },
  1379. },
  1380. // windows
  1381. "windows path separator - unix rule - OR allowlist path-only": {
  1382. fragment: Fragment{
  1383. Raw: `value: "s3cr3t"`,
  1384. FilePath: `ignoreme/windows.txt`,
  1385. WindowsFilePath: `ignoreme\windows.txt`,
  1386. },
  1387. rule: config.Rule{
  1388. RuleID: "unix-rule",
  1389. Regex: regexp.MustCompile(`s3cr3t`),
  1390. Allowlists: []*config.Allowlist{
  1391. {
  1392. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1393. },
  1394. },
  1395. },
  1396. expected: nil,
  1397. },
  1398. "windows path separator - windows rule - OR allowlist path-only": {
  1399. fragment: Fragment{
  1400. Raw: `value: "s3cr3t"`,
  1401. FilePath: `ignoreme/windows.txt`,
  1402. WindowsFilePath: `ignoreme\windows.txt`,
  1403. },
  1404. rule: config.Rule{
  1405. RuleID: "windows-rule",
  1406. Regex: regexp.MustCompile(`s3cr3t`),
  1407. Allowlists: []*config.Allowlist{
  1408. {
  1409. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1410. },
  1411. },
  1412. },
  1413. expected: nil,
  1414. },
  1415. "windows path separator - unix rule - AND allowlist path+stopwords": {
  1416. fragment: Fragment{
  1417. Raw: `value: "f4k3s3cr3t"`,
  1418. FilePath: `ignoreme/unix.txt`,
  1419. WindowsFilePath: `ignoreme\windows.txt`,
  1420. },
  1421. rule: config.Rule{
  1422. RuleID: "unix-rule",
  1423. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1424. Allowlists: []*config.Allowlist{
  1425. {
  1426. MatchCondition: config.AllowlistMatchAnd,
  1427. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
  1428. StopWords: []string{"f4k3"},
  1429. },
  1430. },
  1431. },
  1432. expected: nil,
  1433. },
  1434. "windows path separator - windows rule - AND allowlist path+stopwords": {
  1435. fragment: Fragment{
  1436. Raw: `value: "f4k3s3cr3t"`,
  1437. FilePath: `ignoreme/unix.txt`,
  1438. WindowsFilePath: `ignoreme\windows.txt`,
  1439. },
  1440. rule: config.Rule{
  1441. RuleID: "windows-rule",
  1442. Regex: regexp.MustCompile(`value: "[^"]+"`),
  1443. Allowlists: []*config.Allowlist{
  1444. {
  1445. MatchCondition: config.AllowlistMatchAnd,
  1446. Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
  1447. StopWords: []string{"f4k3"},
  1448. },
  1449. },
  1450. },
  1451. expected: nil,
  1452. },
  1453. }
  1454. d, err := NewDetectorDefaultConfig()
  1455. require.NoError(t, err)
  1456. for name, test := range tests {
  1457. t.Run(name, func(t *testing.T) {
  1458. actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{})
  1459. if diff := cmp.Diff(test.expected, actual); diff != "" {
  1460. t.Errorf("diff: (-want +got)\n%s", diff)
  1461. }
  1462. })
  1463. }
  1464. }
  1465. //endregion