def test_requests_exception(self):
        """Exception during API call should be AnymailAPIError"""
        # (The post itself raises an error -- different from returning a failure response)
        from requests.exceptions import SSLError  # a low-level requests exception
        self.mock_request.side_effect = SSLError("Something bad")
        with self.assertRaisesMessage(AnymailRequestsAPIError, "Something bad") as cm:
            self.message.send()
        self.assertIsInstance(cm.exception, SSLError)  # also retains specific requests exception class

        # Make sure fail_silently is respected
        self.mock_request.side_effect = SSLError("Something bad")
        sent = mail.send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**'], fail_silently=True)
        self.assertEqual(sent, 0)
Exemple #2
0
    def download_code(self):
        '''
        获取验证码图片
        :return:
        '''
        try:
            url = "https://kyfw.12306.cn/passport/captcha/captcha-image64?login_site=E&module=login&rand=sjrand&_={}".format(
                int(time.time() * 1000))
            response = self.session.get(url)
            result = response.json()
            if result.get('result_code') == "0":
                if result.get('image'):
                    return result.get('image')
                raise SSLError('返回数据为空')
            elif result.get('result_code') == -4:
                print(result.get("result_message"))
                return False

        except SSLError:
            time.sleep(self.retry_time)
            return self.download_code()

        except:
            print("生成验证码失败")
            return False
Exemple #3
0
 def download_code(self):
     img_path = './tkcode.png'
     url = API_AUTH_CODE_BASE64_DOWNLOAD.format(random=random.random())
     # code_path = self.data_path + 'code.png'
     try:
         UserLog.add_quick_log(UserLog.MESSAGE_DOWNLAODING_THE_CODE).flush()
         # response = self.session.save_to_file(url, code_path)  # TODO 返回错误情况
         response = self.session.get(url)
         result = response.json().get('image')
         if result:
             try:
                 with open(img_path, 'wb', encoding="utf-8") as img:
                     img.write(base64.b64decode(result))
                     # img.write(result)
             except Exception:
                 with open(img_path, 'wb') as img:
                     img.write(base64.b64decode(result))
             return result
         raise SSLError('返回数据为空')
     except SSLError as e:
         UserLog.add_quick_log(
             UserLog.MESSAGE_DOWNLAOD_AUTH_CODE_FAIL.format(
                 e, self.retry_time)).flush()
         time.sleep(self.retry_time)
         return self.download_code()
 def mock_get(session, url, timeout):
     if url.startswith('https'):
         raise SSLError("Uh oh")
     return MagicMock(
         status_code=200,
         json=MagicMock(return_value={'tags': None}),
     )
Exemple #5
0
def test_validate_plugin_configuration_incorrect_certificate(
        mocked_request, adyen_plugin):
    plugin = adyen_plugin(apple_pay_cert="cert")
    mocked_request.side_effect = SSLError()
    configuration = PluginConfiguration.objects.get()
    with pytest.raises(ValidationError):
        plugin.validate_plugin_configuration(configuration)
Exemple #6
0
 def test_quilt_yml_unknown_team(self):
     # TODO(dima): This is not a particularly useful test -
     # but it simulates the current behavior in production (an SSL certificate error).
     url = command.get_registry_url('unknown')
     responses.add(responses.GET, url, body=SSLError())
     with pytest.raises(ConnectionError):
         command.install("packages:\n- unknown:baz/bat")
Exemple #7
0
 def test_ssl_exception(self):
     '''Raises a ReppyException on SSL errors.'''
     with mock.patch.object(robots.requests,
                            'get',
                            side_effect=SSLError('Kaboom')):
         with self.assertRaises(robots.exceptions.SSLException):
             robots.Robots.fetch('https://localhost:8080/robots.txt')
Exemple #8
0
 def open(self, request):
     """
     Perform an HTTP GET to the URL in the given suds.transport.Request and returns
     a file-like object of the request body.
     """
     response = None
     try:
         if self.verify_ssl and request.url.startswith('http://'):
             if self.rewrite_to_https:
                 request.url = 'https://' + request.url[7:]
             else:
                 raise SSLError("can't verify SSL certificate with plain HTTP link")
         response = self.session.get(
             url=request.url, 
             data=request.message,
             headers=request.headers,
             proxies=self.proxy,
             verify=self.verify_ssl,
             cert=self.getclientcertificate(),
         )
         response.raise_for_status()
     except SSLError as e:
         raise TransportError(str(e), None)
     except (RequestException, HTTPError, ConnectionError) as e:
         raise TransportError(str(e), None)
     return suds.BytesIO(response.content)
def test_insecure_option_hint_shown_on_ssl_cert_error(capsys, ip, send):
    send.side_effect = SSLError()
    result = ip.run_line_magic('rest', '')
    assert result is None
    assert ip.showtraceback.called_once()
    err = capsys.readouterr()[1]
    assert 'Use `%rest --insecure`' in err
Exemple #10
0
 def test_get_response_exception(self):
     task = Mock(retry=RetryExc)
     session_mock = Mock(post=Mock(side_effect=SSLError("Unsafe bla bla")))
     with patch("treasury.api_requests.Session", lambda: session_mock):
         with patch(
                 "treasury.api_requests.get_exponential_request_retry_countdown",
                 Mock()):
             with self.assertRaises(RetryExc):
                 get_request_response(task, 1)
Exemple #11
0
    def requests_bad_cert_get(*args, **kwargs):
        # Make sure we're passing in the 'verify' argument
        assert 'verify' in kwargs, 'Missing "verify" argument in requests.get(...) call'

        if kwargs['verify']:
            raise SSLError("certificate verification failed for {}".format(args[0]))

        # Return the actual response
        return requests_get_mock(*args, **kwargs)
    def test_identify_unexpected_ssl_error(self):

        helper = self._helper()
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError('unexpected error')
                helper.identify(token)
    def test_identify_invalid_cert_legacy(self):

        helper = self._helper(conf={"ckan.oauth2.legacy_idm": "True"})
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.requests.get') as requests_get_mock:
                requests_get_mock.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.identify(token)
    def test_identify_invalid_cert(self):

        helper = self._helper()
        token = {'access_token': 'OAUTH_TOKEN'}

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.identify(token)
Exemple #15
0
    def send(
            self,
            request,  # type: PreparedRequest
            stream=False,  # type: bool
            timeout=None,  # type: Union[float, Tuple[float, float]]
            verify=True,  # type: bool
            cert=None,  # type: Any
            proxies=None  # type: dict
    ):
        # type: (...) -> Response

        self.configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration(
        )
        self.delegate = NSURLSessionAdapterDelegate.alloc().initWithAdapter_(
            self)
        self.delegate.credential = self.credential
        self.session = NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
            self.configuration,
            self.delegate,
            None,
        )

        nsrequest = build_request(request, timeout)
        self.verify = verify

        # TODO: Support all of this stuff.
        assert not stream
        assert not cert
        assert not proxies

        if request.method in ['PUT', 'POST'] and request.body is not None:
            # These verbs should usually be an upload task to send the correct request headers.
            task = self.session.uploadTaskWithRequest_fromData_(
                nsrequest, buffer(request.body))
        else:
            task = self.session.dataTaskWithRequest_(nsrequest)

        cookiestore = self.configuration.HTTPCookieStorage()

        task.resume()

        while not self.delegate.isDone():
            pass

        response = build_response(request, self.delegate, cookiestore)

        # if self.delegate.error is not None:
        #     raise self.delegate.error

        if self.delegate.SSLError is not None:
            code, message = self.delegate.SSLError
            raise SSLError('{}: {}'.format(code, message),
                           response=response,
                           request=request)

        return response
Exemple #16
0
    def send(self,
             request,
             stream=False,
             timeout=None,
             verify=True,
             cert=None,
             proxies=None):
        """Stream PreparedRequest object. Returns Response object."""

        conn = self.get_connection(request.url, proxies)

        self.cert_verify(conn, request.url, verify, cert)
        url = self.request_url(request, proxies)

        try:
            if hasattr(conn, 'proxy_pool'):
                conn = conn.proxy_pool

            low_conn = conn._get_conn(timeout=timeout)
            low_conn.putrequest(request.method, url, skip_accept_encoding=True)

            for header, value in request.headers.items():
                low_conn.putheader(header, value)

            low_conn.endheaders()

            for i in request.body:
                low_conn.send(i)

            r = low_conn.getresponse()
            resp = HTTPResponse.from_httplib(r,
                                             pool=conn,
                                             connection=low_conn,
                                             preload_content=False,
                                             decode_content=False)

        except socket.error as sockerr:
            raise ConnectionError(sockerr)

        except MaxRetryError as e:
            raise ConnectionError(e)

        except (_SSLError, _HTTPError) as e:
            if isinstance(e, _SSLError):
                raise SSLError(e)
            elif isinstance(e, TimeoutError):
                raise Timeout(e)
            else:
                raise Timeout('Request timed out.')

        r = self.build_response(request, resp)

        if not stream:
            r.content

        return r
Exemple #17
0
    def test_fail_on_ssl(self, get):
        api = Api({})
        get.side_effect = SSLError('Hey hey')

        with self.assertRaises(SystemExit):
            api.request('/me', auth=True)

        api2 = api.clone(sysexit=False)
        with self.assertRaises(ApiException):
            api2.request('/me', auth=True)
Exemple #18
0
    def test_shows_informative_message_when_offline(self):
        # Arrange
        template_retriever = Mock()
        template_retriever.get_templates.side_effect = SSLError()
        list_command_executor = ListCommandExecutor(
            template_retriever=template_retriever, standards=Mock())

        # Assert
        self.assertRaisesRegexp(UsageError, "offline",
                                list_command_executor.list)
Exemple #19
0
    def test_remote_import_sslerror(self, is_cancelled_mock, cancel_mock, start_progress_mock, import_channel_mock):
        SSLERROR = SSLError(['SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac'])

        if 'OpenSSL' in sys.modules:
            from OpenSSL.SSL import Error
            SSLERROR = Error(['SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac'])
        with patch('kolibri.content.utils.transfer.Transfer.next', side_effect=SSLERROR):
            call_command('importchannel', 'network', '197934f144305350b5820c7c4dd8e194')
            cancel_mock.assert_called_with()
            import_channel_mock.assert_not_called()
Exemple #20
0
def monkeypatch_test_client_ssl_exception(
    self,
    method=None,
    url=None,
    headers=None,
    params=None,
    stream=False,
    proxies=None,
    timeout=None,
):
    raise SSLError("Test Proxy Error")
    def test_ssl(self):
        register_uri(GET,
                     self.base_url + 'classes/sms',
                     body=json.dumps(TestClient.RESPONSE_BASIC),
                     content_type='text/plain')

        with patch('com.tdigital.sd.admin.client.request') as req_mock:
            req_mock.side_effect = SSLError('...')
            # Send the request
            self.assertRaises(SdAdminLibraryException, self.client.get,
                              'classes/sms')
Exemple #22
0
def test_health_call_with_ssl_error(route, client, cybercrime_api_request):

    mock_exc = mock.MagicMock()
    mock_exc.reason.args.__getitem__().verify_message \
        = 'self signed certificate'
    cybercrime_api_request.side_effect = SSLError(mock_exc)

    response = client.post(route)

    assert response.status_code == HTTPStatus.OK
    assert response.get_json() == EXPECTED_RESPONSE_SSL_ERROR
Exemple #23
0
    def test_identify_unexpected_ssl_error(self):

        helper = self._helper()
        token = {"access_token": "OAUTH_TOKEN"}

        with self.assertRaises(SSLError):
            with patch("ckanext.oauth2.oauth2.OAuth2Session"
                       ) as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError(
                    "unexpected error")
                helper.identify(token)
    def test_refresh_token_invalid_cert(self):
        username = '******'
        current_token = OAUTH2TOKEN
        helper = self._helper()

        # mock plugin functions
        helper.get_stored_token = MagicMock(return_value=current_token)

        with self.assertRaises(InsecureTransportError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().refresh_token.side_effect = SSLError('(Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'tls_process_server_certificate\', \'certificate verify failed\')],)",),)')
                helper.refresh_token(username)
    def test_refresh_token_unexpected_ssl_error(self):
        username = '******'
        current_token = OAUTH2TOKEN
        helper = self._helper()

        # mock plugin functions
        helper.get_stored_token = MagicMock(return_value=current_token)

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().refresh_token.side_effect = SSLError('unexpected error')
                helper.refresh_token(username)
Exemple #26
0
    def test_identify_invalid_cert(self):

        helper = self._helper()
        token = {"access_token": "OAUTH_TOKEN"}

        with self.assertRaises(InsecureTransportError):
            with patch("ckanext.oauth2.oauth2.OAuth2Session"
                       ) as oauth2_session_mock:
                oauth2_session_mock().get.side_effect = SSLError(
                    "(Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),)"
                )
                helper.identify(token)
Exemple #27
0
    def test_identify_invalid_cert_legacy(self):

        helper = self._helper(conf={"ckan.oauth2.legacy_idm": "True"})
        token = {"access_token": "OAUTH_TOKEN"}

        with self.assertRaises(InsecureTransportError):
            with patch(
                    "ckanext.oauth2.oauth2.requests.get") as requests_get_mock:
                requests_get_mock.side_effect = SSLError(
                    "(Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),)"
                )
                helper.identify(token)
Exemple #28
0
def test_health_call_with_ssl_error(route, client, valid_jwt,
                                    sslerror_expected_payload, get_public_key):
    with patch('requests.get') as get_mock:
        mock_exception = MagicMock()
        mock_exception.reason.args.__getitem__().verify_message \
            = 'self signed certificate'
        get_mock.side_effect = [get_public_key, SSLError(mock_exception)]

        response = client.post(route, headers=headers(valid_jwt()))

        assert response.status_code == HTTPStatus.OK
        assert response.json == sslerror_expected_payload
Exemple #29
0
def test_health_call_ssl_error(route, client, valid_jwt, abuse_api_request):
    mock_exception = mock.MagicMock()
    mock_exception.reason.args.__getitem__().verify_message \
        = 'self signed certificate'
    abuse_api_request.side_effect = SSLError(mock_exception)

    response = client.post(route, headers=headers(valid_jwt))

    assert response.status_code == HTTPStatus.OK

    data = response.get_json()
    assert data == EXPECTED_RESPONSE_SSL_ERROR
    def test_get_token_unexpected_ssl_error(self):
        helper = self._helper()
        token = OAUTH2TOKEN
        httpretty.register_uri(httpretty.POST, helper.token_endpoint, body=json.dumps(token))

        state = b64encode(json.dumps({'came_from': 'initial-page'}))
        oauth2.toolkit.request = make_request(True, 'data.com', 'callback', {'state': state, 'code': 'code'})

        with self.assertRaises(SSLError):
            with patch('ckanext.oauth2.oauth2.OAuth2Session') as oauth2_session_mock:
                oauth2_session_mock().fetch_token.side_effect = SSLError('unexpected error')
                helper.get_token()