| 1 |
import argparse |
| 2 |
import contextlib |
| 3 |
import json |
| 4 |
import os |
| 5 |
from io import StringIO |
| 6 |
from pathlib import Path |
| 7 |
from typing import Optional |
| 8 |
from urllib.parse import urlencode |
| 9 |
|
| 10 |
import pytest |
| 11 |
import responses |
| 12 |
from requests import PreparedRequest |
| 13 |
from responses import matchers |
| 14 |
|
| 15 |
from censys.cli import main as cli_main |
| 16 |
from censys.cli.commands.search import ( |
| 17 |
CERTIFICATES_AUTOCOMPLETE, |
| 18 |
HOSTS_AUTOCOMPLETE, |
| 19 |
fields_completer, |
| 20 |
) |
| 21 |
from censys.common.exceptions import CensysCLIException, CensysException |
| 22 |
from tests.search.v2.test_certs import SEARCH_CERTS_JSON |
| 23 |
from tests.search.v2.test_hosts import ( |
| 24 |
SEARCH_HOSTS_JSON, |
| 25 |
SERVER_ERROR_JSON, |
| 26 |
TOO_MANY_REQUESTS_ERROR_JSON, |
| 27 |
) |
| 28 |
from tests.utils import V2_URL, CensysTestCase |
| 29 |
|
| 30 |
WROTE_PREFIX = "Wrote results to file" |
| 31 |
|
| 32 |
|
| 33 |
def search_callback(request: PreparedRequest) -> tuple[int, dict[str, str], str]: |
| 34 |
payload = json.loads(request.body) # type: ignore |
| 35 |
resp_body = { |
| 36 |
"result": { |
| 37 |
"query": payload["q"], |
| 38 |
"hits": [{"parsed.names": ["censys.io"], "parsed.issuer.country": "US"}], |
| 39 |
}, |
| 40 |
"links": { |
| 41 |
"prev": None, |
| 42 |
"next": "test-next-cursor", |
| 43 |
}, |
| 44 |
} |
| 45 |
return (200, {}, json.dumps(resp_body)) |
| 46 |
|
| 47 |
|
| 48 |
class CensysCliSearchTest(CensysTestCase): |
| 49 |
def test_search_help(self): |
| 50 |
# Mock |
| 51 |
self.patch_args(["censys", "search", "--help"]) |
| 52 |
|
| 53 |
# Actual call |
| 54 |
temp_stdout = StringIO() |
| 55 |
with contextlib.redirect_stdout(temp_stdout), pytest.raises(SystemExit): |
| 56 |
cli_main() |
| 57 |
|
| 58 |
# Assertions |
| 59 |
assert temp_stdout.getvalue().strip().startswith("usage: censys search") |
| 60 |
|
| 61 |
def test_no_creds(self): |
| 62 |
# Mock |
| 63 |
self.patch_args(["censys", "search", "test"]) |
| 64 |
self.mocker.patch("builtins.open", new_callable=self.mocker.mock_open, read_data="[DEFAULT]") |
| 65 |
self.mocker.patch.dict("os.environ", {"CENSYS_API_ID": "", "CENSYS_API_SECRET": ""}) |
| 66 |
# Actual Call/Assertion |
| 67 |
with pytest.raises(CensysException, match="No API ID or API secret configured."): |
| 68 |
cli_main() |
| 69 |
|
| 70 |
def test_invalid_timeout(self): |
| 71 |
# mock |
| 72 |
self.patch_args( |
| 73 |
[ |
| 74 |
"censys", |
| 75 |
"search", |
| 76 |
"parsed.names: censys.io", |
| 77 |
"--index-type", |
| 78 |
"certificates", |
| 79 |
"--timeout", |
| 80 |
"-1", |
| 81 |
], |
| 82 |
search_auth=True, |
| 83 |
) |
| 84 |
|
| 85 |
# Actual call |
| 86 |
with pytest.raises( |
| 87 |
CensysCLIException, |
| 88 |
match="Timeout must be greater than 0.", |
| 89 |
): |
| 90 |
cli_main() |
| 91 |
|
| 92 |
def test_write_invalid_output_path(self): |
| 93 |
# Setup response |
| 94 |
self.responses.add( |
| 95 |
responses.POST, |
| 96 |
V2_URL + "/certificates/search", |
| 97 |
json=SEARCH_CERTS_JSON, |
| 98 |
) |
| 99 |
# mock |
| 100 |
self.patch_args( |
| 101 |
[ |
| 102 |
"censys", |
| 103 |
"search", |
| 104 |
"parsed.names: censys.io", |
| 105 |
"--index-type", |
| 106 |
"certificates", |
| 107 |
"--fields", |
| 108 |
"parsed.issuer.country", |
| 109 |
"--output", |
| 110 |
"censys-certs.html", |
| 111 |
], |
| 112 |
search_auth=True, |
| 113 |
) |
| 114 |
|
| 115 |
# Actual call |
| 116 |
with pytest.raises( |
| 117 |
CensysCLIException, |
| 118 |
match="JSON is the only valid file format for Search 2.0 responses.", |
| 119 |
): |
| 120 |
cli_main() |
| 121 |
|
| 122 |
def test_write_screen(self): |
| 123 |
# Setup response |
| 124 |
self.responses.add( |
| 125 |
responses.POST, |
| 126 |
V2_URL + "/hosts/search", |
| 127 |
status=200, |
| 128 |
json=SEARCH_HOSTS_JSON, |
| 129 |
match=[ |
| 130 |
matchers.json_params_matcher( |
| 131 |
{ |
| 132 |
"q": "services.service_name: HTTP", |
| 133 |
"per_page": 100, |
| 134 |
"sort": "RELEVANCE", |
| 135 |
"virtual_hosts": "EXCLUDE", |
| 136 |
} |
| 137 |
) |
| 138 |
], |
| 139 |
) |
| 140 |
# Mock |
| 141 |
self.patch_args( |
| 142 |
[ |
| 143 |
"censys", |
| 144 |
"search", |
| 145 |
"services.service_name: HTTP", |
| 146 |
"--index-type", |
| 147 |
"hosts", |
| 148 |
"--pages", |
| 149 |
"1", |
| 150 |
], |
| 151 |
search_auth=True, |
| 152 |
) |
| 153 |
|
| 154 |
temp_stdout = StringIO() |
| 155 |
# Actual call |
| 156 |
with contextlib.redirect_stdout(temp_stdout): |
| 157 |
cli_main() |
| 158 |
|
| 159 |
json_response = json.loads(temp_stdout.getvalue().strip()) |
| 160 |
# Assertions |
| 161 |
assert json_response == SEARCH_HOSTS_JSON["result"]["hits"] |
| 162 |
|
| 163 |
def test_search_virtual_hosts(self): |
| 164 |
# Setup response |
| 165 |
self.responses.add( |
| 166 |
responses.POST, |
| 167 |
V2_URL + "/hosts/search", |
| 168 |
status=200, |
| 169 |
json=SEARCH_HOSTS_JSON, |
| 170 |
match=[ |
| 171 |
matchers.json_params_matcher( |
| 172 |
{ |
| 173 |
"q": "services.service_name: HTTP", |
| 174 |
"per_page": 100, |
| 175 |
"sort": "RELEVANCE", |
| 176 |
"virtual_hosts": "ONLY", |
| 177 |
} |
| 178 |
) |
| 179 |
], |
| 180 |
) |
| 181 |
# Mock |
| 182 |
self.patch_args( |
| 183 |
[ |
| 184 |
"censys", |
| 185 |
"search", |
| 186 |
"services.service_name: HTTP", |
| 187 |
"--index-type", |
| 188 |
"hosts", |
| 189 |
"--pages", |
| 190 |
"1", |
| 191 |
"--virtual-hosts", |
| 192 |
"ONLY", |
| 193 |
], |
| 194 |
search_auth=True, |
| 195 |
) |
| 196 |
|
| 197 |
temp_stdout = StringIO() |
| 198 |
# Actual call |
| 199 |
with contextlib.redirect_stdout(temp_stdout): |
| 200 |
cli_main() |
| 201 |
|
| 202 |
json_response = json.loads(temp_stdout.getvalue().strip()) |
| 203 |
# Assertions |
| 204 |
assert json_response == SEARCH_HOSTS_JSON["result"]["hits"] |
| 205 |
|
| 206 |
def test_search_sort_order(self): |
| 207 |
# Setup response |
| 208 |
self.responses.add( |
| 209 |
responses.POST, |
| 210 |
V2_URL + "/hosts/search", |
| 211 |
status=200, |
| 212 |
json=SEARCH_HOSTS_JSON, |
| 213 |
match=[ |
| 214 |
matchers.json_params_matcher( |
| 215 |
{ |
| 216 |
"q": "services.service_name: HTTP", |
| 217 |
"per_page": 100, |
| 218 |
"sort": "DESCENDING", |
| 219 |
"virtual_hosts": "EXCLUDE", |
| 220 |
} |
| 221 |
) |
| 222 |
], |
| 223 |
) |
| 224 |
# Mock |
| 225 |
self.patch_args( |
| 226 |
[ |
| 227 |
"censys", |
| 228 |
"search", |
| 229 |
"services.service_name: HTTP", |
| 230 |
"--index-type", |
| 231 |
"hosts", |
| 232 |
"--pages", |
| 233 |
"1", |
| 234 |
"--sort-order", |
| 235 |
"DESCENDING", |
| 236 |
], |
| 237 |
search_auth=True, |
| 238 |
) |
| 239 |
|
| 240 |
temp_stdout = StringIO() |
| 241 |
# Actual call |
| 242 |
with contextlib.redirect_stdout(temp_stdout): |
| 243 |
cli_main() |
| 244 |
|
| 245 |
json_response = json.loads(temp_stdout.getvalue().strip()) |
| 246 |
# Assertions |
| 247 |
assert json_response == SEARCH_HOSTS_JSON["result"]["hits"] |
| 248 |
|
| 249 |
def test_write_json(self): |
| 250 |
# Setup response |
| 251 |
self.responses.add( |
| 252 |
responses.POST, |
| 253 |
V2_URL + "/hosts/search", |
| 254 |
status=200, |
| 255 |
json=SEARCH_HOSTS_JSON, |
| 256 |
match=[ |
| 257 |
matchers.json_params_matcher( |
| 258 |
{ |
| 259 |
"q": "services.service_name: HTTP", |
| 260 |
"per_page": 100, |
| 261 |
"sort": "RELEVANCE", |
| 262 |
"virtual_hosts": "EXCLUDE", |
| 263 |
} |
| 264 |
) |
| 265 |
], |
| 266 |
) |
| 267 |
# Mock |
| 268 |
self.patch_args( |
| 269 |
[ |
| 270 |
"censys", |
| 271 |
"search", |
| 272 |
"services.service_name: HTTP", |
| 273 |
"--index-type", |
| 274 |
"hosts", |
| 275 |
"--pages", |
| 276 |
"1", |
| 277 |
"--output", |
| 278 |
"censys-hosts.json", |
| 279 |
], |
| 280 |
search_auth=True, |
| 281 |
) |
| 282 |
|
| 283 |
temp_stdout = StringIO() |
| 284 |
# Actual call |
| 285 |
with contextlib.redirect_stdout(temp_stdout): |
| 286 |
cli_main() |
| 287 |
|
| 288 |
cli_response = temp_stdout.getvalue().strip() |
| 289 |
# Assertions |
| 290 |
assert cli_response.startswith(WROTE_PREFIX) |
| 291 |
|
| 292 |
json_path = cli_response.replace(WROTE_PREFIX, "").strip() |
| 293 |
assert json_path.endswith(".json") |
| 294 |
assert "censys-hosts." in json_path |
| 295 |
|
| 296 |
with open(json_path) as json_file: |
| 297 |
json_response = json.load(json_file) |
| 298 |
|
| 299 |
assert len(json_response) >= 1 |
| 300 |
assert json_response == SEARCH_HOSTS_JSON["result"]["hits"] |
| 301 |
|
| 302 |
# Cleanup |
| 303 |
os.remove(json_path) |
| 304 |
|
| 305 |
def test_write_csv_fail(self): |
| 306 |
# Mock |
| 307 |
self.patch_args( |
| 308 |
[ |
| 309 |
"censys", |
| 310 |
"search", |
| 311 |
"services.service_name: HTTP", |
| 312 |
"--index-type", |
| 313 |
"hosts", |
| 314 |
"--pages", |
| 315 |
"1", |
| 316 |
"--output", |
| 317 |
"censys-hosts.csv", |
| 318 |
], |
| 319 |
search_auth=True, |
| 320 |
) |
| 321 |
# Actual call/error raising |
| 322 |
with pytest.raises( |
| 323 |
CensysCLIException, |
| 324 |
match="JSON is the only valid file format for Search 2.0 responses.", |
| 325 |
): |
| 326 |
cli_main() |
| 327 |
|
| 328 |
@pytest.mark.parametrize( |
| 329 |
("status_code", "json_response"), |
| 330 |
[ |
| 331 |
(429, TOO_MANY_REQUESTS_ERROR_JSON), |
| 332 |
(500, SERVER_ERROR_JSON), |
| 333 |
], |
| 334 |
) |
| 335 |
def test_midway_fail(self, status_code: int, json_response: dict): |
| 336 |
# Setup response |
| 337 |
next_cursor = SEARCH_HOSTS_JSON["result"]["links"]["next"] |
| 338 |
self.responses.add( |
| 339 |
responses.POST, |
| 340 |
V2_URL + "/hosts/search", |
| 341 |
status=200, |
| 342 |
json=SEARCH_HOSTS_JSON, |
| 343 |
match=[ |
| 344 |
matchers.json_params_matcher( |
| 345 |
{ |
| 346 |
"q": "services.service_name: HTTP", |
| 347 |
"per_page": 100, |
| 348 |
"sort": "RELEVANCE", |
| 349 |
"virtual_hosts": "EXCLUDE", |
| 350 |
} |
| 351 |
) |
| 352 |
], |
| 353 |
) |
| 354 |
self.responses.add( |
| 355 |
responses.POST, |
| 356 |
V2_URL + "/hosts/search", |
| 357 |
status=status_code, |
| 358 |
json=json_response, |
| 359 |
match=[ |
| 360 |
matchers.json_params_matcher( |
| 361 |
{ |
| 362 |
"q": "services.service_name: HTTP", |
| 363 |
"per_page": 100, |
| 364 |
"sort": "RELEVANCE", |
| 365 |
"virtual_hosts": "EXCLUDE", |
| 366 |
"cursor": next_cursor, |
| 367 |
} |
| 368 |
) |
| 369 |
], |
| 370 |
) |
| 371 |
# Mock |
| 372 |
self.patch_args( |
| 373 |
[ |
| 374 |
"censys", |
| 375 |
"search", |
| 376 |
"services.service_name: HTTP", |
| 377 |
"--index-type", |
| 378 |
"hosts", |
| 379 |
"--pages", |
| 380 |
"2", |
| 381 |
"--output", |
| 382 |
"censys-hosts.json", |
| 383 |
], |
| 384 |
search_auth=True, |
| 385 |
) |
| 386 |
|
| 387 |
temp_stdout = StringIO() |
| 388 |
# Actual call |
| 389 |
with contextlib.redirect_stdout(temp_stdout): |
| 390 |
cli_main() |
| 391 |
|
| 392 |
cli_response = temp_stdout.getvalue().strip() |
| 393 |
# Assertions |
| 394 |
assert cli_response.startswith(WROTE_PREFIX) |
| 395 |
|
| 396 |
json_path = cli_response.replace(WROTE_PREFIX, "").strip() |
| 397 |
assert json_path.endswith(".json") |
| 398 |
assert "censys-hosts." in json_path |
| 399 |
|
| 400 |
with open(json_path) as json_file: |
| 401 |
json_response = json.load(json_file) |
| 402 |
|
| 403 |
assert len(json_response) >= 1 |
| 404 |
assert json_response == SEARCH_HOSTS_JSON["result"]["hits"] |
| 405 |
|
| 406 |
# Cleanup |
| 407 |
os.remove(json_path) |
| 408 |
|
| 409 |
def test_open_certificates(self): |
| 410 |
# Mock |
| 411 |
self.patch_args( |
| 412 |
[ |
| 413 |
"censys", |
| 414 |
"search", |
| 415 |
"domain: censys.io AND ports: 443", |
| 416 |
"--index-type", |
| 417 |
"certificates", |
| 418 |
"--open", |
| 419 |
], |
| 420 |
) |
| 421 |
mock_open = self.mocker.patch("censys.cli.commands.search.webbrowser.open") |
| 422 |
|
| 423 |
# Actual call/error raising |
| 424 |
with pytest.raises(SystemExit, match="0"): |
| 425 |
cli_main() |
| 426 |
query_str = urlencode({"q": "domain: censys.io AND ports: 443", "resource": "certificates"}) |
| 427 |
# Assertions |
| 428 |
mock_open.assert_called_with( |
| 429 |
f"https://search.censys.io/search?{query_str}" # noqa: E231 |
| 430 |
) |
| 431 |
|
| 432 |
def test_open_hosts(self): |
| 433 |
# Mock |
| 434 |
self.patch_args( |
| 435 |
[ |
| 436 |
"censys", |
| 437 |
"search", |
| 438 |
"services.service_name: HTTP", |
| 439 |
"--index-type", |
| 440 |
"hosts", |
| 441 |
"--open", |
| 442 |
], |
| 443 |
) |
| 444 |
mock_open = self.mocker.patch("censys.cli.commands.search.webbrowser.open") |
| 445 |
# Actual call/error raising |
| 446 |
with pytest.raises(SystemExit, match="0"): |
| 447 |
cli_main() |
| 448 |
query_str = urlencode({"q": "services.service_name: HTTP", "resource": "hosts"}) |
| 449 |
# Assertions |
| 450 |
mock_open.assert_called_with( |
| 451 |
f"https://search.censys.io/search?{query_str}" # noqa: E231 |
| 452 |
) |
| 453 |
|
| 454 |
@pytest.mark.parametrize( |
| 455 |
("index_type", "autocomplete_file", "prefix"), |
| 456 |
[ |
| 457 |
("hosts", HOSTS_AUTOCOMPLETE, ""), |
| 458 |
("hosts", HOSTS_AUTOCOMPLETE, "service"), |
| 459 |
("certificates", CERTIFICATES_AUTOCOMPLETE, ""), |
| 460 |
("invalid", None, ""), |
| 461 |
], |
| 462 |
) |
| 463 |
def test_fields_completer( |
| 464 |
self, |
| 465 |
index_type: str, |
| 466 |
autocomplete_file: Optional[Path], |
| 467 |
prefix: str, |
| 468 |
): |
| 469 |
parsed_args = argparse.Namespace(index_type=index_type) |
| 470 |
if autocomplete_file is None: |
| 471 |
expected_fields = [] |
| 472 |
else: |
| 473 |
expected_fields = json.load(autocomplete_file.open())["data"] |
| 474 |
expected_fields = [ |
| 475 |
field_value for field in expected_fields if not (field_value := field["value"]).endswith(".type") |
| 476 |
] |
| 477 |
if prefix == "": |
| 478 |
expected_fields = expected_fields[:20] |
| 479 |
assert fields_completer(prefix=prefix, parsed_args=parsed_args) == expected_fields |
| 480 |
|
| 481 |
|
| 482 |
if __name__ == "__main__": |
| 483 |
from unittest import main |
| 484 |
|
| 485 |
main() |