Debian Codegraph @

tests/cli/test_asm.py

raw
1 import contextlib
2 import json
3 import os.path
4 from io import StringIO
5
6 import pytest
7 import responses
8 from responses import matchers
9 from responses.matchers import json_params_matcher
10
11 from censys.cli import main as cli_main
12 from censys.cli.commands.asm import get_seeds_from_xml
13 from tests.asm.utils import INVENTORY_URL, V1_URL, WORKSPACE_ID
14 from tests.cli.test_config import TEST_CONFIG_PATH
15 from tests.utils import CensysTestCase
16
17 SEEDS_JSON = [
18 {"value": 0, "type": "ASN"},
19 {"value": 0, "type": "IP_ADDRESS"},
20 {"value": 0, "type": "DOMAIN_NAME"},
21 {"value": 0, "type": "CIDR"},
22 ]
23 XML_SEEDS = [
24 {"value": "45.33.32.156", "type": "IP_ADDRESS"},
25 {"value": "scanme.nmap.org", "type": "DOMAIN_NAME"},
26 ]
27 ADD_SEEDS_JSON = {
28 "addedSeeds": [
29 {
30 "source": "API",
31 "createdOn": "string",
32 "id": 0,
33 "type": "ASN",
34 "value": 0,
35 "label": "string",
36 },
37 {
38 "source": "API",
39 "createdOn": "string",
40 "id": 0,
41 "type": "IP_ADDRESS",
42 "value": "string",
43 "label": "string",
44 },
45 {
46 "source": "API",
47 "createdOn": "string",
48 "id": 0,
49 "type": "DOMAIN_NAME",
50 "value": "string",
51 "label": "string",
52 },
53 {
54 "source": "API",
55 "createdOn": "string",
56 "id": 0,
57 "type": "CIDR",
58 "value": "string",
59 "label": "string",
60 },
61 ],
62 "skippedReservedSeeds": ["string", 0],
63 }
64
65 GET_SEEDS_JSON = {
66 "seeds": [
67 {
68 "id": 1,
69 "type": "ASN",
70 "value": 0,
71 "label": "Test",
72 "source": "API",
73 "createdOn": "2022-11-01T12:34:23.111142Z",
74 },
75 {
76 "id": 2,
77 "type": "IP_ADDRESS",
78 "value": "1.2.3.4",
79 "label": "Test",
80 "source": "API",
81 "createdOn": "2022-11-01T12:34:23.111142Z",
82 },
83 {
84 "id": 3,
85 "type": "DOMAIN_NAME",
86 "value": "foo.com",
87 "label": "Test",
88 "source": "API",
89 "createdOn": "2022-11-01T12:34:23.111142Z",
90 },
91 {
92 "id": 4,
93 "type": "CIDR",
94 "value": "200.200.200.0/24",
95 "label": "Test",
96 "source": "API",
97 "createdOn": "2022-11-01T12:34:23.111142Z",
98 },
99 {
100 "id": 5,
101 "type": "IP_ADDRESS",
102 "value": "5.6.7.8",
103 "label": "Test 2",
104 "source": "API",
105 "createdOn": "2022-11-01T12:34:23.111142Z",
106 },
107 ]
108 }
109
110 GET_SAVED_QUERIES_JSON = {
111 "results": [
112 {
113 "queryId": "1",
114 "queryName": "foo domain",
115 "query": "domain: foo.com",
116 "createdAt": "2024-01-01T01:00:00.000Z",
117 },
118 {
119 "queryId": "2",
120 "queryName": "bar domain",
121 "query": "domain: bar.com",
122 "createdAt": "2024-01-01T01:00:00.000Z",
123 },
124 ],
125 "totalResults": 2,
126 }
127
128 ADD_SAVED_QUERY_JSON = {
129 "result": {
130 "createdAt": "2024-01-01T01:00:00.000Z",
131 "query": "domain: foo.com",
132 "queryName": "Test",
133 "queryId": "100",
134 },
135 }
136
137 SAVED_QUERY_JSON = {
138 "result": {
139 "queryId": "100",
140 "queryName": "foo domain",
141 "query": "domain: foo.com",
142 "createdAt": "2024-01-01T01:00:00.000Z",
143 },
144 "totalResults": 1,
145 }
146
147 SEARCH_JSON = {
148 "totalHits": 3,
149 "queryDurationMillis": 50,
150 "hits": [
151 {"_details": {}, "domain": {"name": "foo.com"}, "type": "DOMAIN"},
152 {
153 "_details": {},
154 "domain": {"name": "bar.foo.com"},
155 "type": "DOMAIN",
156 },
157 {
158 "_details": {},
159 "domain": {"name": "b.foo.com"},
160 "type": "DOMAIN",
161 },
162 ],
163 }
164
165 SEARCH_JSON_PAGE_1 = {
166 "totalHits": 5,
167 "nextCursor": "eyJmaWx0ZXIiOnt9LCJzdGFydCI6MjA3MTJ9",
168 "queryDurationMillis": 50,
169 "hits": [
170 {"_details": {}, "domain": {"name": "foo.com"}, "type": "DOMAIN"},
171 {
172 "_details": {},
173 "domain": {"name": "bar.foo.com"},
174 "type": "DOMAIN",
175 },
176 ],
177 }
178
179 SEARCH_JSON_PAGE_2 = {
180 "totalHits": 5,
181 "nextCursor": "eyJmaWx0ZXIiOnt9LCJzdGFydCI6MjA3MTJ8",
182 "previousCursor": "eyJmaWx0ZXIiOnt9LCJzdGFydCI6MjA3MTJ9",
183 "queryDurationMillis": 50,
184 "hits": [
185 {
186 "_details": {},
187 "domain": {"name": "b.foo.com"},
188 "type": "DOMAIN",
189 },
190 {
191 "_details": {},
192 "domain": {"name": "a.foo.com"},
193 "type": "DOMAIN",
194 },
195 ],
196 }
197
198 SEARCH_JSON_PAGE_3 = {
199 "totalHits": 5,
200 "previousCursor": "eyJmaWx0ZXIiOnt9LCJzdGFydCI6MjA3MTJ8",
201 "queryDurationMillis": 50,
202 "hits": [
203 {
204 "_details": {},
205 "domain": {"name": "r.foo.com"},
206 "type": "DOMAIN",
207 },
208 ],
209 }
210
211 SEARCH_JSON_PAGINATED = {
212 "totalHits": 5,
213 "previousCursor": "eyJmaWx0ZXIiOnt9LCJzdGFydCI6MjA3MTJ8",
214 "queryDurationMillis": 50,
215 "hits": [
216 {"_details": {}, "domain": {"name": "foo.com"}, "type": "DOMAIN"},
217 {
218 "_details": {},
219 "domain": {"name": "bar.foo.com"},
220 "type": "DOMAIN",
221 },
222 {
223 "_details": {},
224 "domain": {"name": "b.foo.com"},
225 "type": "DOMAIN",
226 },
227 {
228 "_details": {},
229 "domain": {"name": "a.foo.com"},
230 "type": "DOMAIN",
231 },
232 {
233 "_details": {},
234 "domain": {"name": "r.foo.com"},
235 "type": "DOMAIN",
236 },
237 ],
238 }
239
240 SAVED_QUERY_ID = "12345"
241 SAVED_QUERY_NAME = "Test query"
242
243 TEST_XML_PATH = os.path.join(os.path.dirname(__file__), "test.xml")
244
245
246 class CensysASMCliTest(CensysTestCase):
247 def test_add_seeds(self):
248 # Mock
249 self.patch_args(["censys", "asm", "add-seeds", "-j", json.dumps(SEEDS_JSON)], asm_auth=True)
250 self.responses.add(
251 responses.POST,
252 V1_URL + "/seeds",
253 status=200,
254 json=ADD_SEEDS_JSON,
255 )
256
257 # Actual call
258 temp_stdout = StringIO()
259 with contextlib.redirect_stdout(temp_stdout):
260 cli_main()
261
262 # Assertions
263 assert "Added 4 seeds" in temp_stdout.getvalue()
264
265 def test_add_seeds_no_type(self):
266 # Mock
267 self.patch_args(["censys", "asm", "add-seeds", "-j", json.dumps(["1.1.1.1"])], asm_auth=True)
268 self.responses.add(
269 responses.POST,
270 V1_URL + "/seeds",
271 status=200,
272 json=ADD_SEEDS_JSON,
273 match=[json_params_matcher({"seeds": [{"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""}]})],
274 )
275
276 # Actual call
277 cli_main()
278
279 def test_add_seeds_multi_type(self):
280 # Mock
281 self.patch_args(
282 [
283 "censys",
284 "asm",
285 "add-seeds",
286 "-j",
287 json.dumps(
288 [
289 {"value": "1.1.1.1"},
290 {"value": "192.168. 0.15/24", "type": "CIDR"},
291 ]
292 ),
293 ],
294 asm_auth=True,
295 )
296 self.responses.add(
297 responses.POST,
298 V1_URL + "/seeds",
299 status=200,
300 json=ADD_SEEDS_JSON,
301 match=[
302 json_params_matcher(
303 {
304 "seeds": [
305 {"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""},
306 {"value": "192.168. 0.15/24", "type": "CIDR", "label": ""},
307 ]
308 }
309 )
310 ],
311 )
312
313 # Actual call
314 cli_main()
315
316 def test_add_seeds_from_stdin(self):
317 # Mock
318 self.patch_args(
319 [
320 "censys",
321 "asm",
322 "add-seeds",
323 "-i",
324 "-",
325 ],
326 asm_auth=True,
327 )
328 self.mocker.patch(
329 "sys.stdin",
330 StringIO(
331 json.dumps(
332 [
333 {"value": "1.1.1.1"},
334 {"value": "192.168. 0.15/24", "type": "CIDR"},
335 ]
336 )
337 ),
338 )
339 self.responses.add(
340 responses.POST,
341 V1_URL + "/seeds",
342 status=200,
343 json=ADD_SEEDS_JSON,
344 match=[
345 json_params_matcher(
346 {
347 "seeds": [
348 {"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""},
349 {"value": "192.168. 0.15/24", "type": "CIDR", "label": ""},
350 ]
351 }
352 )
353 ],
354 )
355
356 # Actual call
357 cli_main()
358
359 def test_add_seeds_from_file_json(self):
360 # Mock
361 self.patch_args(
362 [
363 "censys",
364 "asm",
365 "add-seeds",
366 "-i",
367 "test.json",
368 ],
369 asm_auth=True,
370 )
371 self.mocker.patch(
372 "builtins.open",
373 new_callable=self.mocker.mock_open,
374 read_data=json.dumps(
375 [
376 {"value": "1.1.1.1"},
377 {"value": "192.168.0.15/24", "type": "CIDR"},
378 ]
379 ),
380 )
381 self.responses.add(
382 responses.POST,
383 V1_URL + "/seeds",
384 status=200,
385 json=ADD_SEEDS_JSON,
386 match=[
387 json_params_matcher(
388 {
389 "seeds": [
390 {"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""},
391 {"value": "192.168.0.15/24", "type": "CIDR", "label": ""},
392 ]
393 }
394 )
395 ],
396 )
397
398 # Actual call
399 cli_main()
400
401 def test_add_seeds_from_file_csv(self):
402 # Mock
403 self.patch_args(
404 [
405 "censys",
406 "asm",
407 "add-seeds",
408 "--csv",
409 "-i",
410 "seeds.csv",
411 ],
412 asm_auth=True,
413 )
414 # Just to make sure we're reading from the fake file
415 self.mocker.patch("censys.common.config.CONFIG_PATH", TEST_CONFIG_PATH)
416 self.mocker.patch(
417 "builtins.open",
418 new_callable=self.mocker.mock_open,
419 read_data="\n".join(["type,value", "IP_ADDRESS,1.1.1.1", "CIDR,192.168.0.15/24"]),
420 )
421 self.responses.add(
422 responses.POST,
423 V1_URL + "/seeds",
424 status=200,
425 json=ADD_SEEDS_JSON,
426 match=[
427 json_params_matcher(
428 {
429 "seeds": [
430 {"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""},
431 {"value": "192.168.0.15/24", "type": "CIDR", "label": ""},
432 ]
433 }
434 )
435 ],
436 )
437
438 # Actual call
439 cli_main()
440
441 def test_add_seeds_from_file_csv_without_flag(self):
442 # Mock
443 self.patch_args(
444 [
445 "censys",
446 "asm",
447 "add-seeds",
448 "-i",
449 "seeds.csv",
450 ],
451 asm_auth=True,
452 )
453 # Just to make sure we're reading from the fake file
454 self.mocker.patch("censys.common.config.CONFIG_PATH", TEST_CONFIG_PATH)
455 self.mocker.patch(
456 "builtins.open",
457 new_callable=self.mocker.mock_open,
458 read_data="\n".join(["type,value", "IP_ADDRESS,1.1.1.1", "CIDR,192.168.0.15/24"]),
459 )
460 self.responses.add(
461 responses.POST,
462 V1_URL + "/seeds",
463 status=200,
464 json=ADD_SEEDS_JSON,
465 match=[
466 json_params_matcher(
467 {
468 "seeds": [
469 {"value": "1.1.1.1", "type": "IP_ADDRESS", "label": ""},
470 {"value": "192.168.0.15/24", "type": "CIDR", "label": ""},
471 ]
472 }
473 )
474 ],
475 )
476
477 # Actual call
478 cli_main()
479
480 def test_add_seeds_invalid_json(self):
481 # Mock
482 self.patch_args(
483 ["censys", "asm", "add-seeds", "-j", "<html><div>not json</div>"],
484 asm_auth=True,
485 )
486
487 # Actual call/error raising
488 with pytest.raises(SystemExit, match="1"):
489 cli_main()
490
491 def test_add_seeds_bad_json(self):
492 # Mock
493 self.patch_args(["censys", "asm", "add-seeds", "-j", json.dumps([12345])], asm_auth=True)
494
495 # Actual call
496 temp_stdout = StringIO()
497 with (
498 pytest.raises(SystemExit, match="1"),
499 contextlib.redirect_stdout(temp_stdout),
500 ):
501 cli_main()
502
503 # Assertions
504 assert "Invalid seed" in temp_stdout.getvalue()
505
506 def test_add_seeds_partial(self):
507 # Mock
508 self.patch_args(["censys", "asm", "add-seeds", "-j", json.dumps(SEEDS_JSON)], asm_auth=True)
509 partial_json = ADD_SEEDS_JSON.copy()
510 partial_json["addedSeeds"] = partial_json["addedSeeds"][1:]
511 self.responses.add(
512 responses.POST,
513 V1_URL + "/seeds",
514 status=200,
515 json=partial_json,
516 )
517
518 # Actual call
519 temp_stdout = StringIO()
520 with contextlib.redirect_stdout(temp_stdout):
521 cli_main()
522
523 # Assertions
524 assert "Added 3 seeds" in temp_stdout.getvalue()
525 assert "Seeds not added: 1" in temp_stdout.getvalue()
526
527 def test_add_seeds_none(self):
528 # Mock
529 self.patch_args(["censys", "asm", "add-seeds", "-j", json.dumps(SEEDS_JSON)], asm_auth=True)
530 partial_json = ADD_SEEDS_JSON.copy()
531 partial_json["addedSeeds"] = []
532 self.responses.add(
533 responses.POST,
534 V1_URL + "/seeds",
535 status=200,
536 json=partial_json,
537 )
538
539 # Actual call
540 temp_stdout = StringIO()
541 with (
542 pytest.raises(SystemExit, match="1"),
543 contextlib.redirect_stdout(temp_stdout),
544 ):
545 cli_main()
546
547 # Assertions
548 assert "No seeds were added. (Run with -v to get more info)" in temp_stdout.getvalue()
549
550 def test_get_seeds_from_xml(self):
551 # Actual call
552 seeds = get_seeds_from_xml(str(TEST_XML_PATH))
553
554 # Assertions
555 assert seeds == XML_SEEDS
556
557 def test_add_seeds_from_xml_file(self):
558 # Mock
559 self.patch_args(
560 [
561 "censys",
562 "asm",
563 "add-seeds",
564 "--nmap-xml",
565 str(TEST_XML_PATH),
566 ],
567 asm_auth=True,
568 )
569 self.responses.add(
570 responses.POST,
571 V1_URL + "/seeds",
572 status=200,
573 json=ADD_SEEDS_JSON,
574 match=[
575 json_params_matcher(
576 {
577 "seeds": [
578 {
579 "value": "45.33.32.156",
580 "type": "IP_ADDRESS",
581 "label": "",
582 },
583 {
584 "value": "scanme.nmap.org",
585 "type": "DOMAIN_NAME",
586 "label": "",
587 },
588 ]
589 }
590 )
591 ],
592 )
593
594 # Actual call
595 cli_main()
596
597 def test_add_seeds_from_invalid_xml_file(self):
598 # Mock
599 self.patch_args(
600 [
601 "censys",
602 "asm",
603 "add-seeds",
604 "--nmap-xml",
605 str(TEST_XML_PATH),
606 ],
607 asm_auth=True,
608 )
609 self.mocker.patch(
610 "xml.etree.ElementTree.open",
611 new_callable=self.mocker.mock_open,
612 read_data="<html><div>not xml</div>",
613 )
614
615 # Actual call
616 with pytest.raises(SystemExit, match="1"):
617 cli_main()
618
619 def test_delete_all_seeds_force_one_seed(self):
620 # Mock
621 self.patch_args(
622 [
623 "censys",
624 "asm",
625 "delete-all-seeds",
626 "--force",
627 ],
628 asm_auth=True,
629 )
630 self.responses.add(
631 responses.GET,
632 V1_URL + "/seeds",
633 status=200,
634 json={"seeds": [item for item in GET_SEEDS_JSON["seeds"] if item["value"] == "1.2.3.4"]},
635 match=[matchers.query_param_matcher({})],
636 )
637 self.responses.add(
638 responses.DELETE,
639 V1_URL + "/seeds/2",
640 status=200,
641 match=[matchers.query_param_matcher({})],
642 )
643
644 # Actual call
645 temp_stdout = StringIO()
646 with contextlib.redirect_stdout(temp_stdout):
647 cli_main()
648
649 # Assertions
650 assert len(self.responses.calls) == 2 # make sure both requests were seen
651 assert "Deleted 1 of 1 total seeds." in temp_stdout.getvalue()
652
653 def test_delete_all_seeds_force(self):
654 # Mock
655 #
656 # The idea is that delete-all-seeds will call GET to get seeds, we'll give it back the
657 # two IP_ADDRESS seeds (just to cut down the list to test), and then we should see it call
658 # DELETE on each of the seed IDs we gave it back, and then it will report on the number of
659 # seeds deleted
660 #
661 self.patch_args(
662 [
663 "censys",
664 "asm",
665 "delete-all-seeds",
666 "--force",
667 ],
668 asm_auth=True,
669 )
670 self.responses.add(
671 responses.GET,
672 V1_URL + "/seeds",
673 status=200,
674 json={"seeds": [item for item in GET_SEEDS_JSON["seeds"] if item["type"] == "IP_ADDRESS"]},
675 match=[matchers.query_param_matcher({})],
676 )
677 self.responses.add(
678 responses.DELETE,
679 V1_URL + "/seeds/2",
680 status=200,
681 match=[matchers.query_param_matcher({})],
682 )
683 self.responses.add(
684 responses.DELETE,
685 V1_URL + "/seeds/5",
686 status=200,
687 match=[matchers.query_param_matcher({})],
688 )
689
690 # Actual call
691 temp_stdout = StringIO()
692 with contextlib.redirect_stdout(temp_stdout):
693 cli_main()
694
695 # Assertions
696 assert len(self.responses.calls) == 3 # make sure all three requests were seen
697 assert "Deleted 2 of 2 total seeds." in temp_stdout.getvalue()
698
699 def test_delete_all_seeds_yes(self):
700 # Mock
701 #
702 # The idea is that delete-all-seeds will call GET to get seeds, we'll give it back the
703 # two IP_ADDRESS seeds (just to cut down the list to test), and then we should see it call
704 # DELETE on each of the seed IDs we gave it back, and then it will report on the number of
705 # seeds deleted
706 #
707 self.patch_args(
708 [
709 "censys",
710 "asm",
711 "delete-all-seeds",
712 ],
713 asm_auth=True,
714 )
715 self.responses.add(
716 responses.GET,
717 V1_URL + "/seeds",
718 status=200,
719 json={"seeds": [item for item in GET_SEEDS_JSON["seeds"] if item["type"] == "IP_ADDRESS"]},
720 match=[matchers.query_param_matcher({})],
721 )
722 self.responses.add(
723 responses.DELETE,
724 V1_URL + "/seeds/2",
725 status=200,
726 match=[matchers.query_param_matcher({})],
727 )
728 self.responses.add(
729 responses.DELETE,
730 V1_URL + "/seeds/5",
731 status=200,
732 match=[matchers.query_param_matcher({})],
733 )
734 self.mocker.patch("builtins.input", side_effect=["y"]) # answer 'y' to are you sure
735
736 # Actual call
737 temp_stdout = StringIO()
738 with contextlib.redirect_stdout(temp_stdout):
739 cli_main()
740
741 # Assertions
742 assert len(self.responses.calls) == 3 # make sure all three requests were seen
743 assert "Deleted 2 of 2 total seeds." in temp_stdout.getvalue()
744
745 def test_delete_all_seeds_no(self):
746 # Mock
747 self.patch_args(
748 [
749 "censys",
750 "asm",
751 "delete-all-seeds",
752 ],
753 asm_auth=True,
754 )
755 self.mocker.patch("builtins.input", side_effect=["n"])
756
757 # Actual call
758 with pytest.raises(SystemExit, match="1"):
759 cli_main()
760
761 def test_delete_seeds_by_ip(self):
762 # Mock
763 self.patch_args(
764 [
765 "censys",
766 "asm",
767 "delete-seeds",
768 "-j",
769 json.dumps(["1.2.3.4", "5.6.7.8", "9.9.9.9"]),
770 ],
771 asm_auth=True,
772 )
773 self.responses.add(
774 responses.GET,
775 V1_URL + "/seeds",
776 status=200,
777 json=GET_SEEDS_JSON,
778 match=[matchers.query_param_matcher({})],
779 )
780 self.responses.add(
781 responses.DELETE,
782 V1_URL + "/seeds/2",
783 status=200,
784 match=[matchers.query_param_matcher({})],
785 )
786 self.responses.add(
787 responses.DELETE,
788 V1_URL + "/seeds/5",
789 status=200,
790 match=[matchers.query_param_matcher({})],
791 )
792
793 # Actual call
794 temp_stdout = StringIO()
795 with contextlib.redirect_stdout(temp_stdout):
796 cli_main()
797
798 # Assertions
799 assert len(self.responses.calls) == 3 # make sure all three requests were seen
800 assert "Deleted 2 seeds.\nUnable to delete 1 seeds because they were not present.\n" in temp_stdout.getvalue()
801
802 def test_delete_seed_by_id(self):
803 # Mock
804 self.patch_args(
805 ["censys", "asm", "delete-seeds", "-j", json.dumps([{"id": 2}])],
806 asm_auth=True,
807 )
808 self.responses.add(
809 responses.GET,
810 V1_URL + "/seeds",
811 status=200,
812 json=GET_SEEDS_JSON,
813 match=[matchers.query_param_matcher({})],
814 )
815 self.responses.add(
816 responses.DELETE,
817 V1_URL + "/seeds/2",
818 status=200,
819 match=[matchers.query_param_matcher({})],
820 )
821
822 # Actual call
823 temp_stdout = StringIO()
824 with contextlib.redirect_stdout(temp_stdout):
825 cli_main()
826
827 # Assertions
828 assert len(self.responses.calls) == 2 # make sure all three requests were seen
829 assert "Deleted 1 seeds." in temp_stdout.getvalue()
830
831 def test_delete_seeds_by_id(self):
832 # Mock
833 self.patch_args(
834 [
835 "censys",
836 "asm",
837 "delete-seeds",
838 "-j",
839 json.dumps([{"id": 2}, {"id": 5}]),
840 ],
841 asm_auth=True,
842 )
843 self.responses.add(
844 responses.GET,
845 V1_URL + "/seeds",
846 status=200,
847 json=GET_SEEDS_JSON,
848 match=[matchers.query_param_matcher({})],
849 )
850 self.responses.add(
851 responses.DELETE,
852 V1_URL + "/seeds/2",
853 status=200,
854 match=[matchers.query_param_matcher({})],
855 )
856 self.responses.add(
857 responses.DELETE,
858 V1_URL + "/seeds/5",
859 status=200,
860 match=[matchers.query_param_matcher({})],
861 )
862
863 # Actual call
864 temp_stdout = StringIO()
865 with contextlib.redirect_stdout(temp_stdout):
866 cli_main()
867
868 # Assertions
869 assert len(self.responses.calls) == 3 # make sure all three requests were seen
870 assert "Deleted 2 seeds." in temp_stdout.getvalue()
871
872 def test_delete_seeds_by_csv(self):
873 # Mock
874 self.patch_args(
875 [
876 "censys",
877 "asm",
878 "delete-seeds",
879 "--csv",
880 "-i",
881 "seeds.csv",
882 ],
883 asm_auth=True,
884 )
885 # Just to make sure we're reading from the fake file
886 self.mocker.patch("censys.common.config.CONFIG_PATH", TEST_CONFIG_PATH)
887 self.mocker.patch(
888 "builtins.open",
889 new_callable=self.mocker.mock_open,
890 read_data="\n".join(["type,value", "IP_ADDRESS,1.2.3.4", "CIDR,200.200.200.0/24"]),
891 )
892
893 self.responses.add(
894 responses.GET,
895 V1_URL + "/seeds",
896 status=200,
897 json=GET_SEEDS_JSON,
898 match=[matchers.query_param_matcher({})],
899 )
900 self.responses.add(
901 responses.DELETE,
902 V1_URL + "/seeds/2",
903 status=200,
904 match=[matchers.query_param_matcher({})],
905 )
906 self.responses.add(
907 responses.DELETE,
908 V1_URL + "/seeds/4",
909 status=200,
910 match=[matchers.query_param_matcher({})],
911 )
912
913 # Actual call
914 temp_stdout = StringIO()
915 with contextlib.redirect_stdout(temp_stdout):
916 cli_main()
917
918 # Assertions
919 assert len(self.responses.calls) == 3 # make sure all three requests were seen
920 assert "Deleted 2 seeds." in temp_stdout.getvalue()
921
922 def test_delete_seeds_by_asm_csv(self):
923 # Mock
924 self.patch_args(
925 [
926 "censys",
927 "asm",
928 "delete-seeds",
929 "--csv",
930 "-i",
931 "seeds.csv",
932 ],
933 asm_auth=True,
934 )
935 # Just to make sure we're reading from the fake file
936 self.mocker.patch("censys.common.config.CONFIG_PATH", TEST_CONFIG_PATH)
937 self.mocker.patch(
938 "builtins.open",
939 new_callable=self.mocker.mock_open,
940 read_data="\n".join(["Type,Value", "IP_ADDRESS,1.2.3.4", "CIDR,200.200.200.0/24"]),
941 )
942
943 self.responses.add(
944 responses.GET,
945 V1_URL + "/seeds",
946 status=200,
947 json=GET_SEEDS_JSON,
948 match=[matchers.query_param_matcher({})],
949 )
950 self.responses.add(
951 responses.DELETE,
952 V1_URL + "/seeds/2",
953 status=200,
954 match=[matchers.query_param_matcher({})],
955 )
956 self.responses.add(
957 responses.DELETE,
958 V1_URL + "/seeds/4",
959 status=200,
960 match=[matchers.query_param_matcher({})],
961 )
962
963 # Actual call
964 temp_stdout = StringIO()
965 with contextlib.redirect_stdout(temp_stdout):
966 cli_main()
967
968 # Assertions
969 assert len(self.responses.calls) == 3 # make sure all three requests were seen
970 assert "Deleted 2 seeds." in temp_stdout.getvalue()
971
972 def test_delete_seeds_nonexistent_id(self):
973 # Mock
974 self.patch_args(
975 ["censys", "asm", "delete-seeds", "-j", json.dumps([{"id": 100}])],
976 asm_auth=True,
977 )
978 self.responses.add(
979 responses.GET,
980 V1_URL + "/seeds",
981 status=200,
982 json=GET_SEEDS_JSON,
983 match=[matchers.query_param_matcher({})],
984 )
985 self.responses.add(
986 responses.DELETE,
987 V1_URL + "/seeds/100",
988 status=404,
989 match=[matchers.query_param_matcher({})],
990 body=json.dumps(
991 {
992 "message": "Unable to Find Seed",
993 "errorCode": 10014,
994 "details": [{"id": 100}],
995 }
996 ),
997 )
998
999 # Actual call
1000 temp_stdout = StringIO()
1001 with contextlib.redirect_stdout(temp_stdout):
1002 cli_main()
1003
1004 # Assertions
1005 assert len(self.responses.calls) == 2 # make sure all three requests were seen
1006 assert "Deleted 0 seeds.\nUnable to delete 1 seeds because they were not present.\n" in temp_stdout.getvalue()
1007
1008 def test_delete_seeds_multiple_nonexistent_id(self):
1009 # Mock
1010 self.patch_args(
1011 [
1012 "censys",
1013 "asm",
1014 "delete-seeds",
1015 "-j",
1016 json.dumps([{"id": 100}, {"id": 101}]),
1017 ],
1018 asm_auth=True,
1019 )
1020 self.responses.add(
1021 responses.GET,
1022 V1_URL + "/seeds",
1023 status=200,
1024 json=GET_SEEDS_JSON,
1025 match=[matchers.query_param_matcher({})],
1026 )
1027 self.responses.add(
1028 responses.DELETE,
1029 V1_URL + "/seeds/100",
1030 status=404,
1031 match=[matchers.query_param_matcher({})],
1032 body=json.dumps(
1033 {
1034 "message": "Unable to Find Seed",
1035 "errorCode": 10014,
1036 "details": [{"id": 100}],
1037 }
1038 ),
1039 )
1040 self.responses.add(
1041 responses.DELETE,
1042 V1_URL + "/seeds/101",
1043 status=404,
1044 match=[matchers.query_param_matcher({})],
1045 body=json.dumps(
1046 {
1047 "message": "Unable to Find Seed",
1048 "errorCode": 10014,
1049 "details": [{"id": 101}],
1050 }
1051 ),
1052 )
1053
1054 # Actual call
1055 temp_stdout = StringIO()
1056 with contextlib.redirect_stdout(temp_stdout):
1057 cli_main()
1058
1059 # Assertions
1060 assert len(self.responses.calls) == 3 # make sure all three requests were seen
1061 assert "Deleted 0 seeds.\nUnable to delete 2 seeds because they were not present.\n" in temp_stdout.getvalue()
1062
1063 def test_delete_seeds_no_id_or_ip(self):
1064 # Mock
1065 self.patch_args(
1066 ["censys", "asm", "delete-seeds", "-j", json.dumps([{"foo": 100}])],
1067 asm_auth=True,
1068 )
1069 self.responses.add(
1070 responses.GET,
1071 V1_URL + "/seeds",
1072 status=200,
1073 json=GET_SEEDS_JSON,
1074 match=[matchers.query_param_matcher({})],
1075 )
1076
1077 # Actual call
1078 temp_stdout = StringIO()
1079 with (
1080 pytest.raises(SystemExit, match="0"),
1081 contextlib.redirect_stdout(temp_stdout),
1082 ):
1083 cli_main()
1084
1085 # Assertions
1086 assert "Error, no seed id or value for seed.\nNo seeds to delete.\n" in temp_stdout.getvalue()
1087
1088 def test_delete_seeds_id_and_value(self):
1089 # Mock
1090 self.patch_args(
1091 [
1092 "censys",
1093 "asm",
1094 "delete-seeds",
1095 "-j",
1096 json.dumps([{"id": 1, "value": "1.2.3.4"}]),
1097 ],
1098 asm_auth=True,
1099 )
1100 self.responses.add(
1101 responses.GET,
1102 V1_URL + "/seeds",
1103 status=200,
1104 json=GET_SEEDS_JSON,
1105 match=[matchers.query_param_matcher({})],
1106 )
1107 self.responses.add(
1108 responses.DELETE,
1109 V1_URL + "/seeds/2",
1110 status=200,
1111 match=[matchers.query_param_matcher({})],
1112 )
1113
1114 # Actual call
1115 temp_stdout = StringIO()
1116 with contextlib.redirect_stdout(temp_stdout):
1117 cli_main()
1118
1119 # Assertions
1120 assert "Deleted 1 seeds.\n" in temp_stdout.getvalue()
1121
1122 def test_delete_labeled_seeds(self):
1123 # Mock
1124 self.patch_args(["censys", "asm", "delete-labeled-seeds", "--label", "Test"], asm_auth=True)
1125 self.responses.add(
1126 responses.DELETE,
1127 V1_URL + "/seeds",
1128 status=200,
1129 json=GET_SEEDS_JSON,
1130 match=[matchers.query_param_matcher({"label": "Test"})],
1131 )
1132
1133 # Actual call
1134 temp_stdout = StringIO()
1135 with contextlib.redirect_stdout(temp_stdout):
1136 cli_main()
1137
1138 # Assertions
1139 assert 'Deleted seeds with label "Test".\n' in temp_stdout.getvalue()
1140
1141 def test_delete_labeled_seeds_without_label(self):
1142 # Mock
1143 self.patch_args(
1144 [
1145 "censys",
1146 "asm",
1147 "delete-labeled-seeds",
1148 ],
1149 asm_auth=True,
1150 )
1151
1152 # Actual call
1153 with pytest.raises(SystemExit, match="2"):
1154 cli_main()
1155
1156 def test_replace_labeled_seeds(self):
1157 # Mock
1158 self.patch_args(
1159 [
1160 "censys",
1161 "asm",
1162 "replace-labeled-seeds",
1163 "--label",
1164 "Test",
1165 "-j",
1166 json.dumps(
1167 [
1168 {"value": "1.1.1.1"},
1169 {
1170 "value": "192.168. 0.15/24",
1171 "type": "CIDR",
1172 "label": "Test Label",
1173 },
1174 ]
1175 ),
1176 ],
1177 asm_auth=True,
1178 )
1179 self.responses.add(
1180 responses.PUT,
1181 V1_URL + "/seeds",
1182 status=200,
1183 json={
1184 "removedSeeds": [],
1185 "skippedReservedSeeds": [],
1186 "addedSeeds": [
1187 {
1188 "id": 100,
1189 "value": "1.1.1.1",
1190 "type": "IP_ADDRESS",
1191 },
1192 {
1193 "id": 101,
1194 "value": "192.168. 0.15/24",
1195 "type": "CIDR",
1196 },
1197 ],
1198 },
1199 match=[matchers.query_param_matcher({"label": "Test", "force": True})],
1200 )
1201
1202 # Actual call
1203 temp_stdout = StringIO()
1204 with contextlib.redirect_stdout(temp_stdout):
1205 cli_main()
1206
1207 # Assertions
1208 assert "Removed 0 seeds. Added 2 seeds. Skipped 0 reserved seeds." in temp_stdout.getvalue()
1209
1210 def test_replace_labeled_seeds_without_label(self):
1211 # Mock
1212 self.patch_args(
1213 [
1214 "censys",
1215 "asm",
1216 "replace-labeled-seeds",
1217 ],
1218 asm_auth=True,
1219 )
1220
1221 # Actual call
1222 with pytest.raises(SystemExit, match="2"):
1223 cli_main()
1224
1225 def test_list_seeds_json(self):
1226 # Mock
1227 self.patch_args(
1228 [
1229 "censys",
1230 "asm",
1231 "list-seeds",
1232 ],
1233 asm_auth=True,
1234 )
1235 self.responses.add(
1236 responses.GET,
1237 V1_URL + "/seeds",
1238 status=200,
1239 json=GET_SEEDS_JSON,
1240 match=[matchers.query_param_matcher({})],
1241 )
1242
1243 temp_stdout = StringIO()
1244
1245 # Actual call
1246 with contextlib.redirect_stdout(temp_stdout):
1247 cli_main()
1248
1249 # Assertions
1250 actual_json = json.loads(temp_stdout.getvalue())
1251 assert actual_json == GET_SEEDS_JSON["seeds"]
1252
1253 def test_list_seeds_csv(self):
1254 # Mock
1255 self.patch_args(
1256 [
1257 "censys",
1258 "asm",
1259 "list-seeds",
1260 "--csv",
1261 ],
1262 asm_auth=True,
1263 )
1264 self.responses.add(
1265 responses.GET,
1266 V1_URL + "/seeds",
1267 status=200,
1268 json=GET_SEEDS_JSON,
1269 match=[matchers.query_param_matcher({})],
1270 )
1271
1272 # Actual call
1273 temp_stdout = StringIO()
1274 with contextlib.redirect_stdout(temp_stdout):
1275 cli_main()
1276
1277 # Assertions
1278 expected_output = (
1279 "\n".join(
1280 [
1281 "id,type,value,label,source,createdOn",
1282 "1,ASN,0,Test,API,2022-11-01T12:34:23.111142Z",
1283 "2,IP_ADDRESS,1.2.3.4,Test,API,2022-11-01T12:34:23.111142Z",
1284 "3,DOMAIN_NAME,foo.com,Test,API,2022-11-01T12:34:23.111142Z",
1285 "4,CIDR,200.200.200.0/24,Test,API,2022-11-01T12:34:23.111142Z",
1286 "5,IP_ADDRESS,5.6.7.8,Test 2,API,2022-11-01T12:34:23.111142Z",
1287 ]
1288 )
1289 + "\n"
1290 )
1291 assert expected_output in temp_stdout.getvalue()
1292
1293 def test_list_seeds_type_ip(self):
1294 # Mock
1295 self.patch_args(
1296 [
1297 "censys",
1298 "asm",
1299 "list-seeds",
1300 "--type",
1301 "IP_ADDRESS",
1302 "--csv",
1303 ],
1304 asm_auth=True,
1305 )
1306 self.responses.add(
1307 responses.GET,
1308 V1_URL + "/seeds",
1309 status=200,
1310 json={"seeds": [item for item in GET_SEEDS_JSON["seeds"] if item["type"] == "IP_ADDRESS"]},
1311 match=[matchers.query_param_matcher({"type": "IP_ADDRESS"})],
1312 )
1313
1314 # Actual call
1315 temp_stdout = StringIO()
1316 with contextlib.redirect_stdout(temp_stdout):
1317 cli_main()
1318
1319 # Assertions
1320 expected_output = (
1321 "\n".join(
1322 [
1323 "id,type,value,label,source,createdOn",
1324 "2,IP_ADDRESS,1.2.3.4,Test,API,2022-11-01T12:34:23.111142Z",
1325 "5,IP_ADDRESS,5.6.7.8,Test 2,API,2022-11-01T12:34:23.111142Z",
1326 ]
1327 )
1328 + "\n"
1329 )
1330 assert expected_output in temp_stdout.getvalue()
1331
1332 def test_list_seeds_label_test(self):
1333 # Mock
1334 self.patch_args(
1335 [
1336 "censys",
1337 "asm",
1338 "list-seeds",
1339 "--label",
1340 "Test",
1341 "--csv",
1342 ],
1343 asm_auth=True,
1344 )
1345 self.responses.add(
1346 responses.GET,
1347 V1_URL + "/seeds",
1348 status=200,
1349 json={"seeds": [item for item in GET_SEEDS_JSON["seeds"] if item["label"] == "Test"]},
1350 match=[matchers.query_param_matcher({"label": "Test"})],
1351 )
1352
1353 # Actual call
1354 temp_stdout = StringIO()
1355 with contextlib.redirect_stdout(temp_stdout):
1356 cli_main()
1357
1358 # Assertions
1359 expected_output = (
1360 "\n".join(
1361 [
1362 "id,type,value,label,source,createdOn",
1363 "1,ASN,0,Test,API,2022-11-01T12:34:23.111142Z",
1364 "2,IP_ADDRESS,1.2.3.4,Test,API,2022-11-01T12:34:23.111142Z",
1365 "3,DOMAIN_NAME,foo.com,Test,API,2022-11-01T12:34:23.111142Z",
1366 "4,CIDR,200.200.200.0/24,Test,API,2022-11-01T12:34:23.111142Z",
1367 ]
1368 )
1369 + "\n"
1370 )
1371 assert expected_output in temp_stdout.getvalue()
1372
1373 def test_list_saved_queries_json(self):
1374 # Mock
1375 self.patch_args(
1376 [
1377 "censys",
1378 "asm",
1379 "list-saved-queries",
1380 ],
1381 asm_auth=True,
1382 )
1383 self.responses.add(
1384 responses.GET,
1385 INVENTORY_URL + "/v1/saved-query",
1386 status=200,
1387 json=GET_SAVED_QUERIES_JSON,
1388 match=[matchers.query_param_matcher({"pageSize": 50, "page": 1})],
1389 )
1390
1391 # Actual call
1392 temp_stdout = StringIO()
1393 with contextlib.redirect_stdout(temp_stdout):
1394 cli_main()
1395
1396 # Assertions
1397 actual_json = json.loads(temp_stdout.getvalue())
1398 assert actual_json == GET_SAVED_QUERIES_JSON
1399
1400 def test_list_saved_queries_csv(self):
1401 # Mock
1402 self.patch_args(
1403 [
1404 "censys",
1405 "asm",
1406 "list-saved-queries",
1407 "--csv",
1408 ],
1409 asm_auth=True,
1410 )
1411 self.responses.add(
1412 responses.GET,
1413 INVENTORY_URL + "/v1/saved-query",
1414 status=200,
1415 json=GET_SAVED_QUERIES_JSON,
1416 match=[matchers.query_param_matcher({"pageSize": 50, "page": 1})],
1417 )
1418
1419 # Actual call
1420 temp_stdout = StringIO()
1421 with contextlib.redirect_stdout(temp_stdout):
1422 cli_main()
1423
1424 # Assertions
1425 expected_output = (
1426 "\n".join(
1427 [
1428 "queryId,queryName,query,createdAt",
1429 "1,foo domain,domain: foo.com,2024-01-01T01:00:00.000Z",
1430 "2,bar domain,domain: bar.com,2024-01-01T01:00:00.000Z",
1431 ]
1432 )
1433 + "\n"
1434 )
1435 assert expected_output in temp_stdout.getvalue()
1436
1437 def test_list_saved_queries_page_2(self):
1438 # Mock
1439 self.patch_args(
1440 [
1441 "censys",
1442 "asm",
1443 "list-saved-queries",
1444 "--csv",
1445 "--page",
1446 "2",
1447 ],
1448 asm_auth=True,
1449 )
1450 self.responses.add(
1451 responses.GET,
1452 INVENTORY_URL + "/v1/saved-query",
1453 status=200,
1454 json=GET_SAVED_QUERIES_JSON,
1455 match=[matchers.query_param_matcher({"pageSize": 50, "page": 2})],
1456 )
1457
1458 # Actual call
1459 temp_stdout = StringIO()
1460 with contextlib.redirect_stdout(temp_stdout):
1461 cli_main()
1462
1463 # Assertions
1464 expected_output = (
1465 "\n".join(
1466 [
1467 "queryId,queryName,query,createdAt",
1468 "1,foo domain,domain: foo.com,2024-01-01T01:00:00.000Z",
1469 "2,bar domain,domain: bar.com,2024-01-01T01:00:00.000Z",
1470 ]
1471 )
1472 + "\n"
1473 )
1474 assert expected_output in temp_stdout.getvalue()
1475
1476 def test_list_saved_queries_page_size_1(self):
1477 # Mock
1478 self.patch_args(
1479 [
1480 "censys",
1481 "asm",
1482 "list-saved-queries",
1483 "--csv",
1484 "--page-size",
1485 "1",
1486 ],
1487 asm_auth=True,
1488 )
1489 self.responses.add(
1490 responses.GET,
1491 INVENTORY_URL + "/v1/saved-query",
1492 status=200,
1493 json={
1494 "totalResults": "1",
1495 "results": [GET_SAVED_QUERIES_JSON["results"][0]],
1496 },
1497 match=[matchers.query_param_matcher({"pageSize": 1, "page": 1})],
1498 )
1499
1500 # Actual call
1501 temp_stdout = StringIO()
1502 with contextlib.redirect_stdout(temp_stdout):
1503 cli_main()
1504
1505 # Assertions
1506 expected_output = (
1507 "\n".join(
1508 [
1509 "queryId,queryName,query,createdAt",
1510 "1,foo domain,domain: foo.com,2024-01-01T01:00:00.000Z",
1511 ]
1512 )
1513 + "\n"
1514 )
1515 assert expected_output in temp_stdout.getvalue()
1516
1517 def test_list_saved_queries_query_name_prefix(self):
1518 # Mock
1519 self.patch_args(
1520 [
1521 "censys",
1522 "asm",
1523 "list-saved-queries",
1524 "--csv",
1525 "--query-name-prefix",
1526 "foo",
1527 ],
1528 asm_auth=True,
1529 )
1530 self.responses.add(
1531 responses.GET,
1532 INVENTORY_URL + "/v1/saved-query",
1533 status=200,
1534 json={
1535 "totalResults": 2,
1536 "results": [query for query in GET_SAVED_QUERIES_JSON["results"] if "foo" in query["queryName"]],
1537 },
1538 match=[matchers.query_param_matcher({"pageSize": 50, "page": 1, "queryNamePrefix": "foo"})],
1539 )
1540
1541 # Actual call
1542 temp_stdout = StringIO()
1543 with contextlib.redirect_stdout(temp_stdout):
1544 cli_main()
1545
1546 # Assertions
1547 expected_output = (
1548 "\n".join(
1549 [
1550 "queryId,queryName,query,createdAt",
1551 "1,foo domain,domain: foo.com,2024-01-01T01:00:00.000Z",
1552 ]
1553 )
1554 + "\n"
1555 )
1556 assert expected_output in temp_stdout.getvalue()
1557
1558 def test_list_saved_queries_filter_term(self):
1559 # Mock
1560 self.patch_args(
1561 [
1562 "censys",
1563 "asm",
1564 "list-saved-queries",
1565 "--csv",
1566 "--filter-term",
1567 "domain",
1568 ],
1569 asm_auth=True,
1570 )
1571 self.responses.add(
1572 responses.GET,
1573 INVENTORY_URL + "/v1/saved-query",
1574 status=200,
1575 json=GET_SAVED_QUERIES_JSON,
1576 match=[matchers.query_param_matcher({"pageSize": 50, "page": 1, "filterTerm": "domain"})],
1577 )
1578
1579 # Actual call
1580 temp_stdout = StringIO()
1581 with contextlib.redirect_stdout(temp_stdout):
1582 cli_main()
1583
1584 # Assertions
1585 expected_output = (
1586 "\n".join(
1587 [
1588 "queryId,queryName,query,createdAt",
1589 "1,foo domain,domain: foo.com,2024-01-01T01:00:00.000Z",
1590 "2,bar domain,domain: bar.com,2024-01-01T01:00:00.000Z",
1591 ]
1592 )
1593 + "\n"
1594 )
1595 assert expected_output in temp_stdout.getvalue()
1596
1597 def test_list_saved_queries_keyerror(self):
1598 # Mock
1599 self.patch_args(
1600 [
1601 "censys",
1602 "asm",
1603 "list-saved-queries",
1604 "--csv",
1605 ],
1606 asm_auth=True,
1607 )
1608 self.responses.add(
1609 responses.GET,
1610 INVENTORY_URL + "/v1/saved-query",
1611 status=200,
1612 json={},
1613 match=[matchers.query_param_matcher({"pageSize": 50, "page": 1})],
1614 )
1615
1616 # Actual call
1617 with pytest.raises(SystemExit, match="1"):
1618 cli_main()
1619
1620 def test_add_saved_query(self):
1621 # Mock
1622 self.patch_args(
1623 [
1624 "censys",
1625 "asm",
1626 "add-saved-query",
1627 "--query-name",
1628 "Test",
1629 "--query",
1630 "domain: foo.com",
1631 ],
1632 asm_auth=True,
1633 )
1634 self.responses.add(
1635 responses.POST,
1636 INVENTORY_URL + "/v1/saved-query",
1637 status=200,
1638 json=ADD_SAVED_QUERY_JSON,
1639 match=[
1640 json_params_matcher(
1641 {
1642 "queryName": "Test",
1643 "query": "domain: foo.com",
1644 }
1645 )
1646 ],
1647 )
1648
1649 # Actual call
1650 temp_stdout = StringIO()
1651 with contextlib.redirect_stdout(temp_stdout):
1652 cli_main()
1653
1654 # Assertions
1655 assert (
1656 "Added saved query.\nQuery name: Test\nQuery: domain: foo.com\nQuery ID: 100\nCreated at: 2024-01-01T01:00:00.000Z\n"
1657 in temp_stdout.getvalue()
1658 )
1659
1660 def test_add_saved_query_failed(self):
1661 # Mock
1662 self.patch_args(
1663 [
1664 "censys",
1665 "asm",
1666 "add-saved-query",
1667 "--query-name",
1668 "Test",
1669 "--query",
1670 "domain: foo.com",
1671 ],
1672 asm_auth=True,
1673 )
1674 self.responses.add(
1675 responses.POST,
1676 INVENTORY_URL + "/v1/saved-query",
1677 status=0,
1678 json={
1679 "details": [{"details": "go here"}],
1680 "error": "string",
1681 "statusCode": 0,
1682 },
1683 match=[
1684 json_params_matcher(
1685 {
1686 "queryName": "Test",
1687 "query": "domain: foo.com",
1688 }
1689 )
1690 ],
1691 )
1692
1693 # Actual call
1694 with pytest.raises(SystemExit, match="1"):
1695 cli_main()
1696
1697 def test_get_saved_query_by_id(self):
1698 # Mock
1699 self.patch_args(
1700 ["censys", "asm", "get-saved-query-by-id", "--query-id", "100"],
1701 asm_auth=True,
1702 )
1703 self.responses.add(
1704 responses.GET,
1705 INVENTORY_URL + "/v1/saved-query/100",
1706 status=200,
1707 json=SAVED_QUERY_JSON,
1708 match=[matchers.query_param_matcher({})],
1709 )
1710
1711 # Actual call
1712 temp_stdout = StringIO()
1713 with contextlib.redirect_stdout(temp_stdout):
1714 cli_main()
1715
1716 # Assertions
1717 assert (
1718 "Query name: foo domain\nQuery: domain: foo.com\nQuery ID: 100\nCreated at: 2024-01-01T01:00:00.000Z\n"
1719 in temp_stdout.getvalue()
1720 )
1721
1722 def test_get_saved_query_by_id_failed(self):
1723 # Mock
1724 self.patch_args(
1725 ["censys", "asm", "get-saved-query-by-id", "--query-id", "100"],
1726 asm_auth=True,
1727 )
1728 self.responses.add(
1729 responses.GET,
1730 INVENTORY_URL + "/v1/saved-query/100",
1731 status=0,
1732 json={
1733 "details": [{"details": "go here"}],
1734 "error": "string",
1735 "statusCode": 0,
1736 },
1737 match=[matchers.query_param_matcher({})],
1738 )
1739
1740 # Actual call
1741 with pytest.raises(SystemExit, match="1"):
1742 cli_main()
1743
1744 def test_edit_saved_query_by_id(self):
1745 # Mock
1746 self.patch_args(
1747 [
1748 "censys",
1749 "asm",
1750 "edit-saved-query-by-id",
1751 "--query-id",
1752 "100",
1753 "--query-name",
1754 "foo domain",
1755 "--query",
1756 "domain: foo.com",
1757 ],
1758 asm_auth=True,
1759 )
1760 self.responses.add(
1761 responses.PUT,
1762 INVENTORY_URL + "/v1/saved-query/100",
1763 status=200,
1764 json=SAVED_QUERY_JSON,
1765 match=[
1766 json_params_matcher(
1767 {
1768 "queryName": "foo domain",
1769 "query": "domain: foo.com",
1770 }
1771 )
1772 ],
1773 )
1774
1775 # Actual call
1776 temp_stdout = StringIO()
1777 with contextlib.redirect_stdout(temp_stdout):
1778 cli_main()
1779
1780 # Assertions
1781 assert (
1782 "Edited saved query.\nQuery name: foo domain\nQuery: domain: foo.com\nQuery ID: 100\nCreated at: 2024-01-01T01:00:00.000Z\n"
1783 in temp_stdout.getvalue()
1784 )
1785
1786 def test_edit_saved_query_by_id_failed(self):
1787 # Mock
1788 self.patch_args(
1789 [
1790 "censys",
1791 "asm",
1792 "edit-saved-query-by-id",
1793 "--query-id",
1794 "100",
1795 "--query-name",
1796 "foo domain",
1797 "--query",
1798 "domain: foo.com",
1799 ],
1800 asm_auth=True,
1801 )
1802 self.responses.add(
1803 responses.PUT,
1804 INVENTORY_URL + "/v1/saved-query/100",
1805 status=0,
1806 json={
1807 "details": [{"details": "go here"}],
1808 "error": "string",
1809 "statusCode": 0,
1810 },
1811 match=[
1812 json_params_matcher(
1813 {
1814 "queryName": "foo domain",
1815 "query": "domain: foo.com",
1816 }
1817 )
1818 ],
1819 )
1820
1821 # Actual call
1822 with pytest.raises(SystemExit, match="1"):
1823 cli_main()
1824
1825 def test_delete_saved_query_by_id(self):
1826 # Mock
1827 self.patch_args(
1828 ["censys", "asm", "delete-saved-query-by-id", "--query-id", "100"],
1829 asm_auth=True,
1830 )
1831 self.responses.add(
1832 responses.DELETE,
1833 INVENTORY_URL + "/v1/saved-query/100",
1834 status=200,
1835 json={},
1836 match=[matchers.query_param_matcher({})],
1837 )
1838
1839 # Actual call
1840 temp_stdout = StringIO()
1841 with contextlib.redirect_stdout(temp_stdout):
1842 cli_main()
1843
1844 # Assertions
1845 assert "Deleted saved query with ID 100." in temp_stdout.getvalue()
1846
1847 def test_delete_saved_query_by_id_failed(self):
1848 # Mock
1849 self.patch_args(
1850 ["censys", "asm", "delete-saved-query-by-id", "--query-id", "100"],
1851 asm_auth=True,
1852 )
1853 self.responses.add(
1854 responses.DELETE,
1855 INVENTORY_URL + "/v1/saved-query/100",
1856 status=0,
1857 json={
1858 "details": [{"details": "go here"}],
1859 "error": "string",
1860 "statusCode": 0,
1861 },
1862 match=[matchers.query_param_matcher({})],
1863 )
1864
1865 # Actual call
1866 with pytest.raises(SystemExit, match="1"):
1867 cli_main()
1868
1869 def test_execute_saved_query_by_name(self):
1870 # Mock
1871 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
1872 mock_request.return_value = WORKSPACE_ID
1873 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_queries")
1874 mock_query.return_value = {
1875 "results": [
1876 {
1877 "queryId": "1",
1878 "queryName": "foo domain",
1879 "query": "domain: foo.com",
1880 "createdAt": "2024-01-01T01:00:00.000Z",
1881 }
1882 ]
1883 }
1884 self.patch_args(
1885 [
1886 "censys",
1887 "asm",
1888 "execute-saved-query-by-name",
1889 "--query-name",
1890 "foo domain",
1891 ],
1892 asm_auth=True,
1893 )
1894 self.responses.add(
1895 responses.GET,
1896 INVENTORY_URL + "/v1",
1897 status=200,
1898 json=SEARCH_JSON,
1899 match=[
1900 matchers.query_param_matcher(
1901 {
1902 "workspaces": WORKSPACE_ID,
1903 "query": "domain: foo.com",
1904 "pageSize": 50,
1905 }
1906 )
1907 ],
1908 )
1909
1910 # Actual call
1911 temp_stdout = StringIO()
1912 with contextlib.redirect_stdout(temp_stdout):
1913 cli_main()
1914
1915 # Assertions
1916 actual_json = json.loads(temp_stdout.getvalue())
1917 assert actual_json == SEARCH_JSON
1918
1919 def test_execute_saved_query_by_name_not_found(self):
1920 # Mock
1921 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_queries")
1922 mock_query.return_value = {"results": []}
1923 self.patch_args(
1924 [
1925 "censys",
1926 "asm",
1927 "execute-saved-query-by-name",
1928 "--query-name",
1929 "nonexistent query name",
1930 ],
1931 asm_auth=True,
1932 )
1933
1934 # Actual call
1935 temp_stdout = StringIO()
1936 with (
1937 pytest.raises(SystemExit, match="1"),
1938 contextlib.redirect_stdout(temp_stdout),
1939 ):
1940 cli_main()
1941
1942 # Assertions
1943 assert "No saved query found with that name." in temp_stdout.getvalue()
1944
1945 def test_execute_saved_query_by_name_failed(self):
1946 # Mock
1947 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
1948 mock_request.return_value = WORKSPACE_ID
1949 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_queries")
1950 mock_query.return_value = {
1951 "results": [
1952 {
1953 "queryId": "1",
1954 "queryName": "foo domain",
1955 "query": "domain: foo.com",
1956 "createdAt": "2024-01-01T01:00:00.000Z",
1957 }
1958 ]
1959 }
1960 self.patch_args(
1961 [
1962 "censys",
1963 "asm",
1964 "execute-saved-query-by-name",
1965 "--query-name",
1966 "foo domain",
1967 ],
1968 asm_auth=True,
1969 )
1970 self.responses.add(
1971 responses.GET,
1972 INVENTORY_URL + "/v1",
1973 status=500,
1974 json={},
1975 match=[
1976 matchers.query_param_matcher(
1977 {
1978 "workspaces": WORKSPACE_ID,
1979 "query": "domain: foo.com",
1980 "pageSize": 50,
1981 }
1982 )
1983 ],
1984 )
1985
1986 # Actual call
1987 temp_stdout = StringIO()
1988 with (
1989 pytest.raises(SystemExit, match="1"),
1990 contextlib.redirect_stdout(temp_stdout),
1991 ):
1992 cli_main()
1993
1994 # Assertions
1995 assert "Failed to execute saved query." in temp_stdout.getvalue()
1996
1997 def test_execute_saved_query_by_name_invalid_page_size(self):
1998 # Mock
1999 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2000 mock_request.return_value = WORKSPACE_ID
2001 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_queries")
2002 mock_query.return_value = {
2003 "results": [
2004 {
2005 "queryId": "1",
2006 "queryName": "foo domain",
2007 "query": "domain: foo.com",
2008 "createdAt": "2024-01-01T01:00:00.000Z",
2009 }
2010 ]
2011 }
2012 self.patch_args(
2013 [
2014 "censys",
2015 "asm",
2016 "execute-saved-query-by-name",
2017 "--query-name",
2018 "foo domain",
2019 "--page-size",
2020 "1001",
2021 ],
2022 asm_auth=True,
2023 )
2024
2025 # Actual call
2026 temp_stdout = StringIO()
2027 with (
2028 pytest.raises(SystemExit, match="1"),
2029 contextlib.redirect_stdout(temp_stdout),
2030 ):
2031 cli_main()
2032
2033 # Assertions
2034 assert "page size must be within [0,1000]" in temp_stdout.getvalue()
2035
2036 def test_execute_saved_query_by_id(self):
2037 # Mock
2038 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2039 mock_request.return_value = WORKSPACE_ID
2040 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_query_by_id")
2041 mock_query.return_value = SAVED_QUERY_JSON
2042 self.patch_args(
2043 [
2044 "censys",
2045 "asm",
2046 "execute-saved-query-by-id",
2047 "--query-id",
2048 "100",
2049 ],
2050 asm_auth=True,
2051 )
2052 self.responses.add(
2053 responses.GET,
2054 INVENTORY_URL + "/v1",
2055 status=200,
2056 json=SEARCH_JSON,
2057 match=[
2058 matchers.query_param_matcher(
2059 {
2060 "workspaces": WORKSPACE_ID,
2061 "query": "domain: foo.com",
2062 "pageSize": 50,
2063 }
2064 )
2065 ],
2066 )
2067
2068 # Actual call
2069 temp_stdout = StringIO()
2070 with contextlib.redirect_stdout(temp_stdout):
2071 cli_main()
2072
2073 # Assertions
2074 actual_json = json.loads(temp_stdout.getvalue())
2075 assert actual_json == SEARCH_JSON
2076
2077 def test_execute_saved_query_by_id_not_found(self):
2078 # Mock
2079 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_query_by_id")
2080 mock_query.return_value = {
2081 "status_code": 404,
2082 "error": "No query found with ID: 500",
2083 }
2084 self.patch_args(
2085 [
2086 "censys",
2087 "asm",
2088 "execute-saved-query-by-id",
2089 "--query-id",
2090 "500",
2091 ],
2092 asm_auth=True,
2093 )
2094
2095 # Actual call
2096 temp_stdout = StringIO()
2097 with (
2098 pytest.raises(SystemExit, match="1"),
2099 contextlib.redirect_stdout(temp_stdout),
2100 ):
2101 cli_main()
2102
2103 # Assertions
2104 assert "No saved query found with that ID." in temp_stdout.getvalue()
2105
2106 def test_execute_saved_query_by_id_failed(self):
2107 # Mock
2108 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2109 mock_request.return_value = WORKSPACE_ID
2110 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_query_by_id")
2111 mock_query.return_value = SAVED_QUERY_JSON
2112 self.patch_args(
2113 [
2114 "censys",
2115 "asm",
2116 "execute-saved-query-by-id",
2117 "--query-id",
2118 "100",
2119 ],
2120 asm_auth=True,
2121 )
2122 self.responses.add(
2123 responses.GET,
2124 INVENTORY_URL + "/v1",
2125 status=500,
2126 json={},
2127 match=[
2128 matchers.query_param_matcher(
2129 {
2130 "workspaces": WORKSPACE_ID,
2131 "query": "domain: foo.com",
2132 "pageSize": 50,
2133 }
2134 )
2135 ],
2136 )
2137
2138 # Actual call
2139 temp_stdout = StringIO()
2140 with (
2141 pytest.raises(SystemExit, match="1"),
2142 contextlib.redirect_stdout(temp_stdout),
2143 ):
2144 cli_main()
2145
2146 # Assertions
2147 assert "Failed to execute saved query." in temp_stdout.getvalue()
2148
2149 def test_execute_saved_query_by_id_invalid_page_size(self):
2150 # Mock
2151 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2152 mock_request.return_value = WORKSPACE_ID
2153 mock_query = self.mocker.patch("censys.asm.SavedQueries.get_saved_queries")
2154 mock_query.return_value = SAVED_QUERY_JSON
2155 self.patch_args(
2156 [
2157 "censys",
2158 "asm",
2159 "execute-saved-query-by-id",
2160 "--query-id",
2161 "100",
2162 "--page-size",
2163 "1001",
2164 ],
2165 asm_auth=True,
2166 )
2167
2168 # Actual call
2169 temp_stdout = StringIO()
2170 with (
2171 pytest.raises(SystemExit, match="1"),
2172 contextlib.redirect_stdout(temp_stdout),
2173 ):
2174 cli_main()
2175
2176 # Assertions
2177 assert "page size must be within [0,1000]" in temp_stdout.getvalue()
2178
2179 def test_search(self):
2180 # Mock
2181 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2182 mock_request.return_value = WORKSPACE_ID
2183 self.patch_args(
2184 [
2185 "censys",
2186 "asm",
2187 "search",
2188 "--query",
2189 "domain: foo.com",
2190 ],
2191 asm_auth=True,
2192 )
2193 self.responses.add(
2194 responses.GET,
2195 INVENTORY_URL + "/v1",
2196 status=200,
2197 json=SEARCH_JSON,
2198 match=[
2199 matchers.query_param_matcher(
2200 {
2201 "workspaces": WORKSPACE_ID,
2202 "query": "domain: foo.com",
2203 "pageSize": 50,
2204 }
2205 )
2206 ],
2207 )
2208
2209 # Actual call
2210 temp_stdout = StringIO()
2211 with contextlib.redirect_stdout(temp_stdout):
2212 cli_main()
2213
2214 # Assertions
2215 actual_json = json.loads(temp_stdout.getvalue())
2216 assert actual_json == SEARCH_JSON
2217
2218 def test_search_failed(self):
2219 # Mock
2220 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2221 mock_request.return_value = WORKSPACE_ID
2222 self.patch_args(
2223 [
2224 "censys",
2225 "asm",
2226 "search",
2227 "--query",
2228 "domain: foo.com",
2229 ],
2230 asm_auth=True,
2231 )
2232 self.responses.add(
2233 responses.GET,
2234 INVENTORY_URL + "/v1",
2235 status=500,
2236 json={},
2237 match=[
2238 matchers.query_param_matcher(
2239 {
2240 "workspaces": WORKSPACE_ID,
2241 "query": "domain: foo.com",
2242 "pageSize": 50,
2243 }
2244 )
2245 ],
2246 )
2247
2248 # Actual call
2249 temp_stdout = StringIO()
2250 with (
2251 pytest.raises(SystemExit, match="1"),
2252 contextlib.redirect_stdout(temp_stdout),
2253 ):
2254 cli_main()
2255
2256 # Assertions
2257 assert "Failed to execute query." in temp_stdout.getvalue()
2258
2259 def test_search_paginated_all(self):
2260 # Mock
2261 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2262 mock_request.return_value = WORKSPACE_ID
2263 self.patch_args(
2264 [
2265 "censys",
2266 "asm",
2267 "search",
2268 "--query",
2269 "domain: foo.com",
2270 "--page-size",
2271 "2",
2272 "--pages",
2273 "-1",
2274 ],
2275 asm_auth=True,
2276 )
2277 self.responses.add(
2278 responses.GET,
2279 INVENTORY_URL + "/v1",
2280 status=200,
2281 json=SEARCH_JSON_PAGE_1,
2282 match=[
2283 matchers.query_param_matcher(
2284 {
2285 "workspaces": WORKSPACE_ID,
2286 "query": "domain: foo.com",
2287 "pageSize": 2,
2288 }
2289 )
2290 ],
2291 )
2292 self.responses.add(
2293 responses.GET,
2294 INVENTORY_URL + "/v1",
2295 status=200,
2296 json=SEARCH_JSON_PAGE_2,
2297 match=[
2298 matchers.query_param_matcher(
2299 {
2300 "workspaces": WORKSPACE_ID,
2301 "cursor": SEARCH_JSON_PAGE_1["nextCursor"],
2302 "query": "domain: foo.com",
2303 "pageSize": 2,
2304 }
2305 )
2306 ],
2307 )
2308 self.responses.add(
2309 responses.GET,
2310 INVENTORY_URL + "/v1",
2311 status=200,
2312 json=SEARCH_JSON_PAGE_3,
2313 match=[
2314 matchers.query_param_matcher(
2315 {
2316 "workspaces": WORKSPACE_ID,
2317 "cursor": SEARCH_JSON_PAGE_2["nextCursor"],
2318 "query": "domain: foo.com",
2319 "pageSize": 2,
2320 }
2321 )
2322 ],
2323 )
2324
2325 # Actual call
2326 temp_stdout = StringIO()
2327 with contextlib.redirect_stdout(temp_stdout):
2328 cli_main()
2329
2330 # Assertions
2331 actual_json = json.loads(temp_stdout.getvalue())
2332 assert actual_json == SEARCH_JSON_PAGINATED
2333
2334 def test_search_paginated_partial(self):
2335 # Mock
2336 mock_request = self.mocker.patch("censys.asm.api.CensysAsmAPI.get_workspace_id")
2337 mock_request.return_value = WORKSPACE_ID
2338 self.patch_args(
2339 [
2340 "censys",
2341 "asm",
2342 "search",
2343 "--query",
2344 "domain: foo.com",
2345 "--page-size",
2346 "2",
2347 ],
2348 asm_auth=True,
2349 )
2350 self.responses.add(
2351 responses.GET,
2352 INVENTORY_URL + "/v1",
2353 status=200,
2354 json=SEARCH_JSON_PAGE_1,
2355 match=[
2356 matchers.query_param_matcher(
2357 {
2358 "workspaces": WORKSPACE_ID,
2359 "query": "domain: foo.com",
2360 "pageSize": 2,
2361 }
2362 )
2363 ],
2364 )
2365
2366 # Actual call
2367 temp_stdout = StringIO()
2368 with contextlib.redirect_stdout(temp_stdout):
2369 cli_main()
2370
2371 # Assertions
2372 actual_json = json.loads(temp_stdout.getvalue())
2373 assert actual_json == SEARCH_JSON_PAGE_1