{{ message }}
Repository navigation
Expand file tree
/
Copy pathtest_github_dork.py
More file actions
556 lines (459 loc) · 21.2 KB
/
Copy pathtest_github_dork.py
File metadata and controls
556 lines (459 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import csv
import io
import json
import runpy
import sys
import tempfile
import types
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
class FakeGitHubError(Exception):
pass
class FakeForbiddenError(FakeGitHubError):
pass
class FakeServerError(FakeGitHubError):
pass
class FakeAuthenticationFailed(FakeGitHubError):
pass
fake_github3 = types.ModuleType('github3')
fake_github3.GitHub = lambda **kwargs: None
fake_github3.GitHubEnterprise = lambda **kwargs: None
fake_github3.exceptions = types.SimpleNamespace(
ForbiddenError=FakeForbiddenError,
GitHubError=FakeGitHubError,
ServerError=FakeServerError,
AuthenticationFailed=FakeAuthenticationFailed,
)
sys.modules.setdefault('github3', fake_github3)
sys.modules.setdefault('feedparser', types.ModuleType('feedparser'))
from github_dorks import __version__, cli as github_dork # noqa: E402
from github_dorks import dictionaries # noqa: E402
from github_dorks import local as local_module # noqa: E402
from github_dorks import search as search_module # noqa: E402
class SearchResult:
text_matches = ['secret, with comma']
path = 'config/file.env'
score = 42
html_url = 'https://github.example/result'
class GitHubClient:
def search_code(self, query):
self.query = query
return iter([SearchResult()])
class SequenceIterator:
def __init__(self, events):
self.events = iter(events)
def __iter__(self):
return self
def __next__(self):
event = next(self.events)
if isinstance(event, Exception):
raise event
return event
class SearchTests(unittest.TestCase):
def test_creates_public_github_client_from_environment(self):
environment = {'GH_USER': 'user', 'GH_PWD': 'password', 'GH_TOKEN': 'token'}
with patch.object(search_module.github, 'GitHub') as factory:
search_module.create_client(environment)
factory.assert_called_once_with(
username='user', password='password', token='token'
)
def test_creates_enterprise_client_from_environment(self):
environment = {'GH_URL': 'https://github.example', 'GH_TOKEN': 'token'}
with patch.object(search_module.github, 'GitHubEnterprise') as factory:
search_module.create_client(environment)
factory.assert_called_once_with(
url='https://github.example', username=None, password=None,
token='token',
)
def test_writes_valid_csv_and_scopes_query_to_repository(self):
client = GitHubClient()
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
output = Path(directory) / 'results.csv'
dorks.write_text('# comment\nfilename:.env PASSWORD\n', encoding='utf-8')
stats = github_dork.search(
repo_to_search='owner/repo',
gh_dorks_file=str(dorks),
output_filename=str(output),
client=client,
)
with output.open(newline='', encoding='utf-8') as output_file:
rows = list(csv.reader(output_file))
self.assertEqual(client.query, 'filename:.env PASSWORD repo:owner/repo')
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0][0], 'Issue Type (Dork)')
self.assertEqual(rows[1][0], client.query)
self.assertEqual(rows[1][1], "['secret, with comma']")
self.assertEqual(stats.matches, 1)
self.assertEqual(stats.exit_code, 0)
def test_streams_json_document_to_stdout(self):
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('query\n', encoding='utf-8')
stdout = io.StringIO()
stderr = io.StringIO()
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
output_format='json', client=GitHubClient(),
stdout=stdout, stderr=stderr, monotonic=lambda: 10,
)
document = json.loads(stdout.getvalue())
self.assertEqual(document['results'][0]['path'], SearchResult.path)
self.assertEqual(document['summary']['matches'], 1)
self.assertNotIn('Scanning', stdout.getvalue())
self.assertIn('Summary: 1 queries, 1 matches', stderr.getvalue())
def test_streams_typed_json_lines(self):
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('query\n', encoding='utf-8')
stdout = io.StringIO()
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
output_format='jsonl', quiet=True, client=GitHubClient(),
stdout=stdout, stderr=io.StringIO(),
)
records = [json.loads(line) for line in stdout.getvalue().splitlines()]
self.assertEqual([record['type'] for record in records], ['result', 'summary'])
self.assertEqual(records[1]['matches'], 1)
def test_quiet_suppresses_status_but_not_text_results(self):
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('query\n', encoding='utf-8')
stdout = io.StringIO()
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
quiet=True, client=GitHubClient(), stdout=stdout,
)
self.assertIn('Found result', stdout.getvalue())
self.assertNotIn('Scanning', stdout.getvalue())
self.assertNotIn('Summary', stdout.getvalue())
def test_refuses_to_overwrite_output_without_force(self):
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
output = Path(directory) / 'results.json'
dorks.write_text('query\n', encoding='utf-8')
output.write_text('keep me', encoding='utf-8')
with self.assertRaises(FileExistsError):
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
output_filename=str(output), output_format='json',
client=GitHubClient(),
)
self.assertEqual(output.read_text(encoding='utf-8'), 'keep me')
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
output_filename=str(output), output_format='json', force=True,
quiet=True, client=GitHubClient(),
)
self.assertEqual(json.loads(output.read_text())['summary']['matches'], 1)
def test_output_failure_is_fatal(self):
class BrokenStream(io.StringIO):
def write(self, value):
raise OSError('disk full')
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('query\n', encoding='utf-8')
with self.assertRaisesRegex(OSError, 'disk full'):
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
quiet=True, client=GitHubClient(), stdout=BrokenStream(),
)
def test_searches_selected_categories_only(self):
class RecordingClient:
def __init__(self):
self.queries = []
def search_code(self, query):
self.queries.append(query)
return iter([])
client = RecordingClient()
stats = github_dork.search(
repo_to_search='owner/repo', categories=['frameworks'],
quiet=True, client=client, stdout=io.StringIO(),
)
self.assertEqual(stats.queries, 7)
self.assertEqual(len(client.queries), 7)
self.assertTrue(all(query.endswith(' repo:owner/repo') for query in client.queries))
def test_reports_when_no_results_are_found(self):
client = GitHubClient()
client.search_code = lambda query: iter([])
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('filename:.env\n', encoding='utf-8')
stdout = io.StringIO()
stats = github_dork.search(
user_to_search='example', gh_dorks_file=str(dorks),
client=client, stdout=stdout,
)
self.assertIn('No results for your dork search user:example', stdout.getvalue())
self.assertIn('Summary: 1 queries, 0 matches', stdout.getvalue())
self.assertEqual(stats.queries, 1)
def test_rejects_missing_dorks_file_with_clear_error(self):
with self.assertRaisesRegex(Exception, 'dorks file path is not valid'):
github_dork.search(
repo_to_search='owner/repo',
gh_dorks_file='/does/not/exist', client=GitHubClient(),
)
def test_retries_server_error_with_exponential_backoff(self):
client = GitHubClient()
client.search_code = lambda query: SequenceIterator([
FakeServerError('temporary'), FakeServerError('temporary'), SearchResult(),
])
sleeps = []
stats = search_module.ScanStats()
results = list(search_module.iter_search_results(
client, 'query', stats, sleep=sleeps.append,
))
self.assertEqual(len(results), 1)
self.assertIsInstance(results[0], SearchResult)
self.assertEqual(sleeps, [1, 2])
self.assertEqual(stats.retries, 2)
def test_retries_failure_that_starts_a_search(self):
client = GitHubClient()
calls = []
def start_search(query):
calls.append(query)
if len(calls) == 1:
raise FakeServerError('temporary')
return iter([SearchResult()])
client.search_code = start_search
sleeps = []
stats = search_module.ScanStats()
results = list(search_module.iter_search_results(
client, 'query', stats, sleep=sleeps.append,
))
self.assertEqual(len(results), 1)
self.assertEqual(calls, ['query', 'query'])
self.assertEqual(sleeps, [1])
def test_stops_after_retry_limit(self):
client = GitHubClient()
client.search_code = lambda query: SequenceIterator([
FakeServerError('one'), FakeServerError('two'),
FakeServerError('three'),
])
sleeps = []
stats = search_module.ScanStats()
with self.assertRaises(FakeServerError):
list(search_module.iter_search_results(
client, 'query', stats, max_retries=2, sleep=sleeps.append,
))
self.assertEqual(sleeps, [1, 2])
self.assertEqual(stats.retries, 2)
def test_waits_until_search_rate_limit_resets(self):
error = FakeForbiddenError('rate limited')
client = GitHubClient()
client.search_code = lambda query: SequenceIterator([error, SearchResult()])
client.rate_limit = lambda: {
'resources': {'search': {'remaining': 0, 'reset': 109}}
}
sleeps = []
stats = search_module.ScanStats()
list(search_module.iter_search_results(
client, 'query', stats, sleep=sleeps.append, now=lambda: 100,
))
self.assertEqual(sleeps, [10])
def test_continues_after_a_query_fails(self):
class MixedClient:
def search_code(self, query):
if query.startswith('bad'):
return SequenceIterator([FakeGitHubError('invalid query')])
return iter([SearchResult()])
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('bad\ngood\n', encoding='utf-8')
stdout = io.StringIO()
stderr = io.StringIO()
stats = github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
client=MixedClient(), stdout=stdout, stderr=stderr,
)
self.assertEqual(stats.queries, 2)
self.assertEqual(stats.matches, 1)
self.assertEqual(stats.failures, 1)
self.assertEqual(stats.exit_code, 2)
self.assertIn('Query failed: bad repo:owner/repo', stderr.getvalue())
def test_authentication_failure_is_fatal(self):
client = GitHubClient()
client.search_code = lambda query: SequenceIterator([
FakeAuthenticationFailed('bad credentials')
])
with tempfile.TemporaryDirectory() as directory:
dorks = Path(directory) / 'dorks.txt'
dorks.write_text('query\n', encoding='utf-8')
with self.assertRaises(FakeAuthenticationFailed):
github_dork.search(
repo_to_search='owner/repo', gh_dorks_file=str(dorks),
client=client,
)
class CommandLineTests(unittest.TestCase):
def test_lists_categories_without_creating_client(self):
stdout = io.StringIO()
with patch.object(sys, 'argv', ['github-dorks', '--list-categories']):
with patch.object(github_dork, 'create_client') as create_client:
with redirect_stdout(stdout):
self.assertEqual(github_dork.main(), 0)
create_client.assert_not_called()
self.assertEqual(
stdout.getvalue().splitlines(), list(dictionaries.available_categories())
)
def test_parses_output_controls(self):
arguments = [
'-r', 'owner/repo', '--format', 'json', '--output', 'results.json',
'--force', '--verbose',
]
args = github_dork.build_parser().parse_args(arguments)
self.assertEqual(args.output_format, 'json')
self.assertEqual(args.output_filename, 'results.json')
self.assertTrue(args.force)
self.assertTrue(args.verbose)
def test_local_scan_does_not_create_github_client(self):
stats = search_module.ScanStats(matches=1)
with patch.object(sys, 'argv', ['github-dorks', '--local', '.']):
with patch.object(github_dork, 'create_client') as create_client:
with patch.object(github_dork, 'scan_local', return_value=stats):
self.assertEqual(github_dork.main(), 0)
create_client.assert_not_called()
def test_version_comes_from_package_metadata(self):
stdout = io.StringIO()
with patch.object(sys, 'argv', ['github-dorks', '--version']):
with redirect_stdout(stdout), self.assertRaises(SystemExit) as exit_info:
github_dork.main()
self.assertEqual(exit_info.exception.code, 0)
self.assertEqual(stdout.getvalue().strip(), f'github-dorks {__version__}')
def test_returns_partial_failure_exit_code(self):
stats = search_module.ScanStats(failures=1)
with patch.object(sys, 'argv', ['github-dorks', '-r', 'owner/repo']):
with patch.object(github_dork, 'create_client', return_value=object()):
with patch.object(github_dork, 'search', return_value=stats):
self.assertEqual(github_dork.main(), 2)
def test_returns_fatal_exit_code_for_missing_dictionary(self):
stderr = io.StringIO()
arguments = [
'github-dorks', '-r', 'owner/repo', '-d', '/does/not/exist'
]
with patch.object(sys, 'argv', arguments), redirect_stdout(io.StringIO()):
with patch.object(github_dork, 'create_client', return_value=GitHubClient()):
with patch('sys.stderr', stderr):
self.assertEqual(github_dork.main(), 1)
self.assertIn('the dorks file path is not valid', stderr.getvalue())
class LocalScanTests(unittest.TestCase):
def test_parses_qualifiers_or_and_not(self):
query = local_module.parse_query(
'filename:id_rsa OR filename:id_dsa private NOT example'
)
self.assertTrue(query.matches(
Path('id_rsa'), 'keys/id_rsa', 'a private credential'
))
self.assertTrue(query.matches(
Path('id_dsa'), 'keys/id_dsa', 'a private credential'
))
self.assertFalse(query.matches(
Path('id_rsa'), 'keys/id_rsa', 'a private example credential'
))
def test_scans_local_text_files_and_streams_json(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
environment = root / '.env'
environment.write_text(
'GROQ_API_KEY=gsk_live_secret\nSAFE=value\n', encoding='utf-8'
)
(root / 'binary.bin').write_bytes(b'GROQ_API_KEY\0secret')
dorks = root / 'dorks.txt'
dorks.write_text(
'filename:.env "GROQ_API_KEY"\n'
'filename:.env NOT "GROQ_API_KEY"\n',
encoding='utf-8',
)
stdout = io.StringIO()
stats = local_module.scan_local(
root, gh_dorks_file=dorks, output_format='json', quiet=True,
stdout=stdout,
)
document = json.loads(stdout.getvalue())
self.assertEqual(stats.queries, 2)
self.assertEqual(stats.matches, 1)
self.assertEqual(stats.files, 2)
self.assertEqual(document['summary']['files'], 2)
self.assertEqual(document['results'][0]['path'], '.env')
self.assertIn('1: GROQ_API_KEY=', document['results'][0]['text_matches'][0])
def test_skips_oversized_files(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'secret.txt').write_text('SECRET_TOKEN', encoding='utf-8')
dorks = root / 'dorks.txt'
dorks.write_text('SECRET_TOKEN\n', encoding='utf-8')
stats = local_module.scan_local(
root, gh_dorks_file=dorks, max_file_size=5, quiet=True,
stdout=io.StringIO(),
)
self.assertEqual(stats.matches, 0)
def test_does_not_scan_its_own_output_file(self):
with tempfile.TemporaryDirectory() as directory:
base = Path(directory)
root = base / 'source'
root.mkdir()
dorks = base / 'dorks.txt'
dorks.write_text('SECRET_TOKEN\n', encoding='utf-8')
output = root / 'SECRET_TOKEN-results.json'
stats = local_module.scan_local(
root, gh_dorks_file=dorks, output_filename=output,
output_format='json', quiet=True,
)
self.assertEqual(stats.matches, 0)
def test_rejects_missing_local_path(self):
with self.assertRaisesRegex(ValueError, 'local scan path'):
list(local_module.iter_local_files('/does/not/exist'))
class DorkDictionaryTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
dictionary = Path(__file__).parents[1] / 'github-dorks.txt'
cls.lines = dictionary.read_text(encoding='utf-8').splitlines()
cls.dorks = [
line for line in cls.lines
if line and not line.startswith(('#', ';'))
]
def test_has_no_duplicate_dorks(self):
duplicates = sorted({dork for dork in self.dorks if self.dorks.count(dork) > 1})
self.assertEqual(duplicates, [])
def test_has_no_surrounding_whitespace(self):
untrimmed = [line for line in self.lines if line != line.strip()]
self.assertEqual(untrimmed, [])
def test_has_balanced_quotes(self):
malformed = [dork for dork in self.dorks if dork.count('"') % 2]
self.assertEqual(malformed, [])
def test_contains_modern_credential_families(self):
dictionary = '\n'.join(self.dorks)
for marker in (
'github_pat_', 'glpat-', 'pypi-', 'OPENAI_API_KEY',
'ANTHROPIC_API_KEY', 'HF_TOKEN', 'CLOUDFLARE_API_TOKEN',
'SUPABASE_SERVICE_ROLE_KEY', 'sk_live_', 'GROQ_API_KEY',
'PINECONE_API_KEY', 'UPSTASH_REDIS_REST_TOKEN',
'OP_SERVICE_ACCOUNT_TOKEN', 'CLERK_SECRET_KEY',
'NEW_RELIC_LICENSE_KEY', 'PAGERDUTY_API_TOKEN',
):
with self.subTest(marker=marker):
self.assertIn(marker, dictionary)
def test_contains_focused_modern_categories(self):
categories = dictionaries.available_categories()
for category in ('ai', 'identity', 'observability'):
with self.subTest(category=category):
self.assertIn(category, categories)
def test_aggregate_matches_categorized_dictionaries(self):
category_dorks = list(dictionaries.iter_dorks(
dictionaries.category_files().values()
))
self.assertEqual(set(self.dorks), set(category_dorks))
self.assertEqual(len(self.dorks), len(category_dorks))
def test_generated_aggregate_is_current(self):
aggregate = Path(__file__).parents[1] / 'github-dorks.txt'
script = Path(__file__).parents[1] / 'scripts' / 'build-dorks.py'
with tempfile.TemporaryDirectory() as directory:
generated = Path(directory) / 'github-dorks.txt'
runpy.run_path(str(script))['build'](output=generated)
self.assertEqual(
aggregate.read_text(encoding='utf-8'),
generated.read_text(encoding='utf-8'),
)
if __name__ == '__main__':
unittest.main()
You can’t perform that action at this time.
