Example #1
0
    def test_successful_empty_json_response(self, mock):
        mock_response = Response()
        mock_response.status_code = 200
        mock.return_value = mock_response
        base = CensysAPIBase("url")

        self.assertEqual({}, base._make_call(base._session.get, "endpoint"))
Example #2
0
    def __init__(
        self,
        api_id: Optional[str] = None,
        api_secret: Optional[str] = None,
        url: Optional[str] = DEFAULT_URL,
        **kwargs,
    ):
        CensysAPIBase.__init__(self, url, **kwargs)

        # Gets config file
        config = get_config()

        # Try to get credentials
        self._api_id = (api_id or os.getenv("CENSYS_API_ID")
                        or config.get(DEFAULT, "api_id"))
        self._api_secret = (api_secret or os.getenv("CENSYS_API_SECRET")
                            or config.get(DEFAULT, "api_secret"))
        if not self._api_id or not self._api_secret:
            raise CensysException("No API ID or API secret configured.")

        self._session.auth = (self._api_id, self._api_secret)

        # Generate concrete paths to be called
        self.search_path = f"search/{self.INDEX_NAME}"
        self.view_path = f"view/{self.INDEX_NAME}"
        self.report_path = f"report/{self.INDEX_NAME}"

        # Confirm setup
        self.account()
Example #3
0
    def test_successful_empty_json_response(self):
        self.responses.add(
            responses.GET,
            TEST_URL + TEST_ENDPOINT,
            status=200,
            body=None,
        )
        base = CensysAPIBase(TEST_URL)

        assert base._get(TEST_ENDPOINT) == {}
Example #4
0
    def test_proxies(self, mock=None):
        mock.get(
            self.ACCOUNT_URL,
            json=self.ACCOUNT_JSON,
        )

        proxies = {"https": self.HTTPS_PROXY}
        api = CensysAPIBase(proxies=proxies)
        api.account()
        self.assertDictEqual(proxies, mock.last_request.proxies)
Example #5
0
    def test_successful_error_json_response(self):
        self.responses.add(
            responses.GET,
            TEST_URL + TEST_ENDPOINT,
            status=200,
            json=ERROR_JSON,
        )
        base = CensysAPIBase(TEST_URL)

        with pytest.raises(CensysAPIException, match=ERROR_JSON["error"]):
            base._get(TEST_ENDPOINT)
Example #6
0
    def test_warn_http_proxies(self, mock=None):
        mock.get(
            self.ACCOUNT_URL,
            json=self.ACCOUNT_JSON,
        )

        with self.assertWarns(UserWarning):
            api = CensysAPIBase(proxies=self.PROXIES)
            api.account()

        self.assertDictEqual({"https": self.HTTPS_PROXY},
                             mock.last_request.proxies)
Example #7
0
    def test_invalid_json_response(self):
        self.responses.add(
            responses.GET,
            TEST_URL + TEST_ENDPOINT,
            status=400,
            body="<html><h1>Definitely not JSON</h1>",
        )
        base = CensysAPIBase(TEST_URL)

        with pytest.raises(
            CensysAPIException, match="is not valid JSON and cannot be decoded"
        ):
            base._get(TEST_ENDPOINT)
Example #8
0
    def __init__(self, api_key: Optional[str] = None, **kwargs):
        url = kwargs.pop("url", self.DEFAULT_URL)
        CensysAPIBase.__init__(self, url=url, **kwargs)

        # Gets config file
        config = get_config()

        # Try to get credentials
        self._api_key = (api_key or os.getenv("CENSYS_ASM_API_KEY")
                         or config.get(DEFAULT, "asm_api_key"))

        if not self._api_key:
            raise CensysMissingApiKeyException("No ASM API key configured.")

        self._session.headers.update({
            "Content-Type": "application/json",
            "Censys-Api-Key": self._api_key
        })
Example #9
0
def cli_config(_):  # pragma: no cover
    """
    config subcommand.

    Args:
        _: Argparse Namespace.
    """

    api_id_prompt = "Censys API ID"
    api_secret_prompt = "Censys API Secret"

    config = get_config()
    api_id = config.get(DEFAULT, "api_id")
    api_secret = config.get(DEFAULT, "api_secret")

    if api_id and api_secret:
        redacted_id = api_id.replace(api_id[:32], 32 * "*")
        redacted_secret = api_secret.replace(api_secret[:28], 28 * "*")
        api_id_prompt = f"{api_id_prompt} [{redacted_id}]"
        api_secret_prompt = f"{api_secret_prompt} [{redacted_secret}]"

    api_id = input(api_id_prompt + ": ").strip() or api_id
    api_secret = input(api_secret_prompt + ": ").strip() or api_secret

    if not (api_id and api_secret):
        print("Please enter valid credentials")
        sys.exit(1)

    try:
        client = CensysAPIBase(api_id, api_secret)
        account = client.account()
        email = account.get("email")

        # Assumes that login was successfully
        config.set(DEFAULT, "api_id", api_id)
        config.set(DEFAULT, "api_secret", api_secret)

        write_config(config)
        print(f"\nSuccessfully authenticated for {email}")
        sys.exit(0)
    except CensysUnauthorizedException:
        print("Failed to authenticate")
        sys.exit(1)
Example #10
0
    def test_no_api_url(self):
        with self.assertRaises(CensysException) as context:
            CensysAPIBase()

        self.assertIn("No API url configured.", str(context.exception))
Example #11
0
    def test_base_get_exception_class(self):
        base = CensysAPIBase("url")

        self.assertEqual(base._get_exception_class(Response()), CensysAPIException)
Example #12
0
    def test_no_env(self, mock_file):
        with self.assertRaises(CensysException) as context:
            CensysAPIBase()

        self.assertIn("No API ID or API secret configured.", str(context.exception))
Example #13
0
 def setUpClass(cls):
     cls._api = CensysAPIBase()
Example #14
0
 def test_proxies(self):
     base = CensysAPIBase(TEST_URL, proxies={"http": "test", "https": "tests"})
     assert list(base._session.proxies.keys()) == ["https"]
Example #15
0
 def test_no_api_url(self):
     with pytest.raises(CensysException, match="No API url configured."):
         CensysAPIBase()
Example #16
0
    def test_base_get_exception_class(self):
        base = CensysAPIBase("url")

        assert base._get_exception_class(Response()) == CensysAPIException