class Connection(insightconnect_plugin_runtime.Connection):
    def __init__(self):
        super(self.__class__, self).__init__(input=ConnectionSchema())
        self.api_key = None
        self.server = None
        self.user_agent = None
        self.gn_client = None

    def connect(self, params):
        self.api_key = params.get("credentials").get("secretKey", "")
        self.server = "https://api.greynoise.io"
        self.user_agent = f"rapid7-insightconnect-v{self.meta.version}"
        self.gn_client = GreyNoise(api_server=self.server, api_key=self.api_key, integration_name=self.user_agent)
        self.logger.info("Connect: Connecting...")

    def test(self):
        try:
            resp = self.gn_client.test_connection()

        except RequestFailure as e:
            if e.args[0] == 401:
                raise ConnectionTestException(preset=ConnectionTestException.Preset.API_KEY, data=e.args[1])
            elif e.args[0] == 429:
                raise ConnectionTestException(preset=ConnectionTestException.Preset.RATE_LIMIT, data=e.args[1])
            elif e.args[0] == 500:
                raise ConnectionTestException(preset=ConnectionTestException.Preset.SERVER_ERROR, data=e.args[1])

        return resp
def validate_api_key(api_key, logger=None):
    """
    Validate the API key using the actual lightweight call to the GreyNoise API.

    Returns false only when 401 code is thrown, indicating the unauthorised access.
    :param api_key:
    :param logger:
    """
    if logger:
        logger.debug("Validating the api key...")

    try:
        api_client = GreyNoise(api_key=api_key,
                               timeout=120,
                               integration_name=INTEGRATION_NAME)
        api_client.test_connection()
        return (True, 'API key is valid')

    except RateLimitError:
        msg = "RateLimitError occured, please contact the Administrator"
        return (False, 'API key not validated, Error: {}'.format(msg))
    except RequestFailure as e:
        response_code, response_message = e.args
        if response_code == 401:
            return (False, 'Unauthorized. Please check your API key.')
        else:
            # Need to handle this, as splunklib is unable to handle the exception with
            # (400, {'error': 'error_reason'}) format
            msg = ("The API call to the GreyNoise API has failed "
                   "with status_code: {} and error: {}").format(
                       response_code, response_message['error'] if isinstance(
                           response_message, dict) else response_message)
            return (False, 'API key not validated, Error: {}'.format(msg))
    except ConnectionError:
        msg = "ConnectionError occured, please check your connection and try again."
        return (False, 'API key not validated, Error: {}'.format(msg))
    except RequestException:
        msg = "An ambiguous exception occured, please try again."
        return (False, 'API key not validated, Error: {}'.format(msg))
    except Exception as e:
        return (False, 'API key not validated, Error: {}'.format(str(e)))