forked from pirxthepilot/wtfis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_cli.py
645 lines (572 loc) · 20.3 KB
/
test_cli.py
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import json
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from dotenv import load_dotenv
from rich.console import Console
from rich.progress import (
BarColumn,
Progress,
SpinnerColumn,
TaskProgressColumn,
TextColumn,
TimeElapsedColumn,
)
from wtfis.clients.abuseipdb import AbuseIpDbClient
from wtfis.clients.greynoise import GreynoiseClient
from wtfis.clients.ip2whois import Ip2WhoisClient
from wtfis.clients.ipwhois import IpWhoisClient
from wtfis.clients.passivetotal import PTClient
from wtfis.clients.shodan import ShodanClient
from wtfis.clients.urlhaus import UrlHausClient
from wtfis.clients.virustotal import VTClient
from wtfis.exceptions import WtfisException
from wtfis.handlers.domain import DomainHandler
from wtfis.handlers.ip import IpAddressHandler
from wtfis.main import (
generate_entity_handler,
generate_view,
main,
parse_args,
parse_env,
)
from wtfis.models.virustotal import Domain, IpAddress
from wtfis.ui.view import DomainView, IpAddressView
POSSIBLE_ENV_VARS = [
"VT_API_KEY",
"PT_API_KEY",
"PT_API_USER",
"IP2WHOIS_API_KEY",
"SHODAN_API_KEY",
"GREYNOISE_API_KEY",
"ABUSEIPDB_API_KEY",
"WTFIS_DEFAULTS",
]
def unset_env_vars():
for var in POSSIBLE_ENV_VARS:
try:
del os.environ[var]
except KeyError:
pass
def fake_load_dotenv(tmp_path, fake_env_vars):
content = [f"{k} = {v}" for k, v in fake_env_vars.items()]
path = tmp_path / ".env.wtfis"
path.write_text("\n".join(content))
def fake(*_):
load_dotenv(path)
return fake
def simulate_progress(console):
return Progress(
SpinnerColumn(finished_text="[green]✓"),
TextColumn("[bold]{task.description}"),
BarColumn(),
TaskProgressColumn(),
TimeElapsedColumn(),
console=console,
)
@pytest.fixture()
def fake_load_dotenv_1(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
"PT_API_KEY": "bar",
"PT_API_USER": "[email protected]",
"IP2WHOIS_API_KEY": "alice",
"SHODAN_API_KEY": "hunter2",
"GREYNOISE_API_KEY": "upupdowndown",
"ABUSEIPDB_API_KEY": "dummy",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
@pytest.fixture()
def fake_load_dotenv_2(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
"SHODAN_API_KEY": "hunter2",
"WTFIS_DEFAULTS": "-s -1",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
@pytest.fixture()
def fake_load_dotenv_3(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
"WTFIS_DEFAULTS": "--no-color",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
@pytest.fixture()
def fake_load_dotenv_4(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
"GREYNOISE_API_KEY": "bar",
"ABUSEIPDB_API_KEY": "dummy",
"WTFIS_DEFAULTS": "-g -u -a",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
@pytest.fixture()
def fake_load_dotenv_vt_whois(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
@pytest.fixture()
def fake_load_dotenv_ip2whois(tmp_path):
fake_env_vars = {
"VT_API_KEY": "foo",
"IP2WHOIS_API_KEY": "alice",
}
return fake_load_dotenv(tmp_path, fake_env_vars)
class TestArgs:
def test_basic(self):
with patch(
"sys.argv",
[
"main",
"www.example.com",
],
):
args = parse_args()
assert args.entity == "www.example.com"
assert args.max_resolutions == 3
assert args.no_color is False
assert args.one_column is False
assert args.use_shodan is False
assert args.use_greynoise is False
assert args.use_urlhaus is False
def test_display(self):
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-n",
"-1",
],
):
args = parse_args()
assert args.no_color is True
assert args.one_column is True
def test_max_resolutions_ok(self):
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-m",
"8",
],
):
args = parse_args()
assert args.max_resolutions == 8
def test_max_resolutions_error_1(self, capsys):
with pytest.raises(SystemExit) as e:
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-m",
"11",
],
):
parse_args()
capture = capsys.readouterr()
assert (
capture.err
== "usage: main [-h]\nmain: error: Maximum --max-resolutions value is 10\n"
)
assert e.type == SystemExit
assert e.value.code == 2
def test_max_resolutions_error_2(self, capsys):
with pytest.raises(SystemExit) as e:
with patch(
"sys.argv",
[
"main",
"1.1.1.1",
"-m",
"5",
],
):
parse_args()
capture = capsys.readouterr()
assert capture.err == (
"usage: main [-h]\nmain: error: --max-resolutions is not "
"applicable to IPs\n"
)
assert e.type == SystemExit
assert e.value.code == 2
def test_shodan_ok(self):
os.environ["SHODAN_API_KEY"] = "foo"
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-s",
],
):
args = parse_args()
assert args.use_shodan is True
del os.environ["SHODAN_API_KEY"]
def test_shodan_error(self, capsys):
with pytest.raises(SystemExit) as e:
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-s",
],
):
parse_args()
capture = capsys.readouterr()
assert (
capture.err == "usage: main [-h]\nmain: error: SHODAN_API_KEY is not set\n"
)
assert e.type == SystemExit
assert e.value.code == 2
def test_greynoise_ok(self):
os.environ["GREYNOISE_API_KEY"] = "foo"
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-g",
],
):
args = parse_args()
assert args.use_greynoise is True
del os.environ["GREYNOISE_API_KEY"]
def test_greynoise_error(self, capsys):
with pytest.raises(SystemExit) as e:
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-g",
],
):
parse_args()
capture = capsys.readouterr()
assert (
capture.err
== "usage: main [-h]\nmain: error: GREYNOISE_API_KEY is not set\n"
)
assert e.type == SystemExit
assert e.value.code == 2
def test_urlhaus(self):
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-u",
],
):
args = parse_args()
assert args.use_urlhaus is True
def test_abuseipdb_ok(self):
os.environ["ABUSEIPDB_API_KEY"] = "foo"
with patch(
"sys.argv",
[
"main",
"1.1.1.1",
"-a",
],
):
args = parse_args()
assert args.use_abuseipdb is True
del os.environ["ABUSEIPDB_API_KEY"]
def test_abuseipdb_error(self, capsys):
with pytest.raises(SystemExit) as e:
with patch(
"sys.argv",
[
"main",
"1.1.1.1",
"-a",
],
):
parse_args()
capture = capsys.readouterr()
assert (
capture.err
== "usage: main [-h]\nmain: error: ABUSEIPDB_API_KEY is not set\n"
)
assert e.type == SystemExit
assert e.value.code == 2
class TestEnvs:
def test_env_file(self, fake_load_dotenv_1):
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
parse_env()
assert os.environ["VT_API_KEY"] == "foo"
assert os.environ["PT_API_KEY"] == "bar"
assert os.environ["PT_API_USER"] == "[email protected]"
assert os.environ["IP2WHOIS_API_KEY"] == "alice"
assert os.environ["SHODAN_API_KEY"] == "hunter2"
assert os.environ["GREYNOISE_API_KEY"] == "upupdowndown"
assert os.environ["ABUSEIPDB_API_KEY"] == "dummy"
unset_env_vars()
@patch("wtfis.main.load_dotenv", MagicMock())
def test_required_env_vars(self):
os.environ["VT_API_KEY"] = "foo"
parse_env()
unset_env_vars()
@patch("wtfis.main.load_dotenv", MagicMock())
@patch("wtfis.main.Path.exists")
def test_error(self, mock_exists, capsys):
mock_exists.return_value = False
with pytest.raises(SystemExit) as e:
parse_env()
capture = capsys.readouterr()
assert capture.err == (
"Error: Environment variable VT_API_KEY not set\n"
f"Env file {Path().home() / '.env.wtfis'} was not found either. "
"Did you forget?\n"
)
assert e.type == SystemExit
assert e.value.code == 1
class TestDefaults:
def test_defaults_1(self, fake_load_dotenv_2):
with patch("wtfis.main.load_dotenv", fake_load_dotenv_2):
with patch(
"sys.argv",
[
"main",
"www.example.com",
],
):
parse_env()
args = parse_args()
assert args.entity == "www.example.com"
assert args.max_resolutions == 3
assert args.no_color is False
assert args.one_column is True
assert args.use_shodan is True
assert args.use_greynoise is False
assert args.use_urlhaus is False
unset_env_vars()
def test_defaults_2(self, fake_load_dotenv_2):
with patch("wtfis.main.load_dotenv", fake_load_dotenv_2):
with patch(
"sys.argv",
[
"main",
"www.example.com",
"-s",
],
):
parse_env()
args = parse_args()
assert args.entity == "www.example.com"
assert args.max_resolutions == 3
assert args.no_color is False
assert args.one_column is True
assert args.use_shodan is False
assert args.use_greynoise is False
assert args.use_urlhaus is False
unset_env_vars()
def test_defaults_3(self, fake_load_dotenv_3):
with patch("wtfis.main.load_dotenv", fake_load_dotenv_3):
with patch(
"sys.argv",
[
"main",
"www.example.com",
],
):
parse_env()
args = parse_args()
assert args.entity == "www.example.com"
assert args.max_resolutions == 3
assert args.no_color is True
assert args.one_column is False
assert args.use_shodan is False
assert args.use_greynoise is False
assert args.use_urlhaus is False
unset_env_vars()
def test_defaults_4(self, fake_load_dotenv_4):
with patch("wtfis.main.load_dotenv", fake_load_dotenv_4):
with patch(
"sys.argv",
[
"main",
"1.1.1.1",
"-u",
],
):
parse_env()
args = parse_args()
assert args.entity == "1.1.1.1"
assert args.no_color is False
assert args.one_column is False
assert args.use_shodan is False
assert args.use_greynoise is True
assert args.use_urlhaus is False
assert args.use_abuseipdb is True
unset_env_vars()
class TestGenEntityHandler:
"""Tests for the generate_entity_handler function"""
@patch("sys.argv", ["main", "www.example[.]com"])
def test_handler_domain_1(self, fake_load_dotenv_1):
"""Domain with default params"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert isinstance(entity, DomainHandler)
assert entity.entity == "www.example.com"
assert entity.max_resolutions == 3
assert entity.console == console
assert entity.progress == progress
assert isinstance(entity._vt, VTClient)
assert isinstance(entity._geoasn, IpWhoisClient)
assert isinstance(entity._whois, PTClient)
assert entity._shodan is None
assert entity._greynoise is None
assert entity._urlhaus is None
assert entity._abuseipdb is None
unset_env_vars()
@patch("sys.argv", ["main", "www.example[.]com", "-s", "-g", "-u", "-m", "5"])
def test_handler_domain_2(self, fake_load_dotenv_1):
"""Domain with Shodan and Greynoise and non-default max_resolutions"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert entity.max_resolutions == 5
assert isinstance(entity._geoasn, IpWhoisClient)
assert isinstance(entity._whois, PTClient)
assert isinstance(entity._shodan, ShodanClient)
assert isinstance(entity._greynoise, GreynoiseClient)
assert isinstance(entity._urlhaus, UrlHausClient)
unset_env_vars()
@patch("sys.argv", ["main", "www.example[.]com"])
def test_handler_domain_3(self, fake_load_dotenv_vt_whois):
"""Domain using default Ip2Whois for whois"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_vt_whois):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert isinstance(entity._whois, VTClient)
unset_env_vars()
@patch("sys.argv", ["main", "www.example[.]com"])
def test_handler_domain_4(self, fake_load_dotenv_ip2whois):
"""Domain using default Ip2Whois for whois"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_ip2whois):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert isinstance(entity._whois, Ip2WhoisClient)
unset_env_vars()
@patch("sys.argv", ["main", "1[.]1[.]1[.]1"])
def test_handler_ip_1(self, fake_load_dotenv_1):
"""IP with default params"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert isinstance(entity, IpAddressHandler)
assert entity.entity == "1.1.1.1"
assert entity.console == console
assert entity.progress == progress
assert isinstance(entity._vt, VTClient)
assert isinstance(entity._geoasn, IpWhoisClient)
assert isinstance(entity._whois, PTClient)
assert entity._greynoise is None
assert entity._urlhaus is None
unset_env_vars()
@patch("sys.argv", ["main", "1[.]1[.]1[.]1", "-s", "-g", "-u", "-a"])
def test_handler_ip_2(self, fake_load_dotenv_1):
"""IP with various options"""
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
parse_env()
console = Console()
progress = (simulate_progress(console),)
entity = generate_entity_handler(parse_args(), console, progress)
assert isinstance(entity._geoasn, IpWhoisClient)
assert isinstance(entity._whois, PTClient)
assert isinstance(entity._shodan, ShodanClient)
assert isinstance(entity._greynoise, GreynoiseClient)
assert isinstance(entity._urlhaus, UrlHausClient)
assert isinstance(entity._abuseipdb, AbuseIpDbClient)
unset_env_vars()
class TestGenView:
"""Tests for the generate_view function"""
@patch("wtfis.main.DomainView", return_value=MagicMock(spec=DomainView))
def test_view_domain_1(self, m_domain_view, test_data):
"""Domain view with default params"""
entity = DomainHandler(
entity=MagicMock(),
console=MagicMock(),
progress=MagicMock(),
vt_client=MagicMock(),
ip_geoasn_client=MagicMock(),
whois_client=MagicMock(),
shodan_client=MagicMock(),
greynoise_client=MagicMock(),
abuseipdb_client=MagicMock(),
urlhaus_client=MagicMock(),
)
entity.vt_info = Domain.model_validate(
json.loads(test_data("vt_domain_gist.json"))
)
entity.whois = MagicMock()
entity.ip_enrich = MagicMock()
view = generate_view(MagicMock(), MagicMock(), entity)
assert isinstance(view, DomainView)
@patch("wtfis.main.IpAddressView", return_value=MagicMock(spec=IpAddressView))
def test_view_ip_1(self, m_ip_view, test_data):
"""IP address view with default params"""
entity = IpAddressHandler(
entity=MagicMock(),
console=MagicMock(),
progress=MagicMock(),
vt_client=MagicMock(),
ip_geoasn_client=MagicMock(),
whois_client=MagicMock(),
shodan_client=MagicMock(),
greynoise_client=MagicMock(),
abuseipdb_client=MagicMock(),
urlhaus_client=MagicMock(),
)
entity.vt_info = IpAddress.model_validate(
json.loads(test_data("vt_ip_1.1.1.1.json"))
)
entity.whois = MagicMock()
entity.ip_enrich = MagicMock()
view = generate_view(MagicMock(), MagicMock(), entity)
assert isinstance(view, IpAddressView)
def test_view_error(self):
"""IP address view with default params"""
with pytest.raises(WtfisException):
generate_view(MagicMock(), MagicMock(), "foobar")
class TestMain:
@patch("sys.argv", ["main", "www.example.com"])
@patch("wtfis.main.Console", return_value=Console())
@patch("wtfis.main.parse_args")
@patch("wtfis.main.get_progress")
@patch("wtfis.main.generate_entity_handler", return_value=MagicMock())
@patch("wtfis.main.generate_view", return_value=MagicMock())
def test_main_default(
self, m_view, m_handler, m_progress, m_args, m_console, fake_load_dotenv_1
):
"""Test all calls with default values"""
m_args.return_value = parse_args()
m_progress.return_value = simulate_progress(m_console())
with patch("wtfis.main.load_dotenv", fake_load_dotenv_1):
main()
m_args.assert_called_once_with()
m_handler.assert_called_once_with(m_args(), m_console(), m_progress())
m_handler().fetch_data.assert_called_once_with()
m_handler().print_warnings.assert_called_once_with()
m_view.assert_called_once_with(m_args(), m_console(), m_handler())
m_view().print.assert_called_once_with(one_column=False)
unset_env_vars()