Esempio n. 1
0
def test_auth_webbrowser_fail_webserver(capsys):
    """Authentication by WebBrowser with failed to start web browser case."""
    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = True

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ("\r\n".join(
        ["GARBAGE", "User-Agent: snowflake-agent"])).encode("utf-8")
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    # case 1: invalid HTTP request
    auth = AuthByWebBrowser(rest,
                            APPLICATION,
                            webbrowser_pkg=mock_webbrowser,
                            socket_pkg=mock_socket)
    auth.authenticate(AUTHENTICATOR, SERVICE_NAME, ACCOUNT, USER, PASSWORD)
    captured = capsys.readouterr()
    assert captured.out == (
        "Initiating login request with your identity provider. A browser window "
        "should have opened for you to complete the login. If you can't see it, "
        "check existing browser windows, or your OS settings. Press CTRL+C to "
        "abort and try again...\n")
    assert rest._connection.errorhandler.called  # an error
    assert auth.assertion_content is None
def test_auth_webbrowser_fail_webserver():
    """
    Authentication by WebBrowser. fail to start web browser
    """
    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = True

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ('\r\n'.join(
        [u"GARBAGE", u"User-Agent: snowflake-agent"])).encode('utf-8')
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    # case 1: invalid HTTP request
    auth = AuthByWebBrowser(rest,
                            APPLICATION,
                            webbrowser_pkg=mock_webbrowser,
                            socket_pkg=mock_socket)
    auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD)
    assert rest._connection.errorhandler.called  # an error
    assert auth.assertion_content is None
def test_auth_webbrowser_fail_webbrowser():
    """Authentication by WebBrowser with failed to start web browser case."""
    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = False

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ('\r\n'.join([
        "GET /?token=MOCK_TOKEN HTTP/1.1",
        "User-Agent: snowflake-agent"
    ])).encode('utf-8')
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    auth = AuthByWebBrowser(
        rest, APPLICATION, webbrowser_pkg=mock_webbrowser,
        socket_pkg=mock_socket)
    auth.authenticate(
        AUTHENTICATOR, SERVICE_NAME, ACCOUNT, USER, PASSWORD)
    assert rest._connection.errorhandler.called  # an error
    assert auth.assertion_content is None
Esempio n. 4
0
        def __open_connection(self):
            u"""
            Opens a new network connection
            """
            self.converter = self._converter_class(use_sfbinaryformat=False,
                                                   use_numpy=self._numpy)

            self._rest = SnowflakeRestful(
                host=self.host,
                port=self.port,
                protocol=self._protocol,
                inject_client_pause=self._inject_client_pause,
                connection=self)

            if self.host.endswith(u".privatelink.snowflakecomputing.com"):
                ocsp_cache_server = \
                    u'http://ocsp{}/ocsp_response_cache.json'.format(
                        self.host[self.host.index('.'):])
                os.environ[
                    'SF_OCSP_RESPONSE_CACHE_SERVER_URL'] = ocsp_cache_server
            else:
                if 'SF_OCSP_RESPONSE_CACHE_SERVER_URL' in os.environ:
                    del os.environ['SF_OCSP_RESPONSE_CACHE_SERVER_URL']

            auth_instance = AuthByWebBrowser(self.rest,
                                             self.application,
                                             protocol=self._protocol,
                                             host=self.host,
                                             port=self.port,
                                             webbrowser_pkg=WebbrowserPkg,
                                             socket_pkg=SocketPkg)

            if self._session_parameters is None:
                self._session_parameters = {}
            if self._autocommit is not None:
                self._session_parameters['AUTOCOMMIT'] = self._autocommit

            if self._timezone is not None:
                self._session_parameters['TIMEZONE'] = self._timezone

            if self.client_session_keep_alive:
                self._session_parameters['CLIENT_SESSION_KEEP_ALIVE'] = True

            # enable storing temporary credential in a file
            self._session_parameters[
                'CLIENT_STORE_TEMPORARY_CREDENTIAL'] = True

            auth = Auth(self.rest)
            if not auth.read_temporary_credential(self.account, self.user,
                                                  self._session_parameters):
                self.__authenticate(auth_instance)
            else:
                # set the current objects as the session is derived from the id
                # token, and the current objects may be different.
                self._set_current_objects()

            self._password = None  # ensure password won't persist

            if self.client_session_keep_alive:
                self._add_heartbeat()
def test_auth_webbrowser():
    """
    Authentication by WebBrowser positive test case
    """
    ref_token = "MOCK_TOKEN"

    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = True

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ('\r\n'.join(
        [u"GET /?token=MOCK_TOKEN HTTP/1.1",
         u"User-Agent: snowflake-agent"])).encode('utf-8')
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    auth = AuthByWebBrowser(rest,
                            APPLICATION,
                            webbrowser_pkg=mock_webbrowser,
                            socket_pkg=mock_socket)
    auth.authenticate(AUTHENTICATOR, ACCOUNT, USER, PASSWORD)
    assert not rest._connection.errorhandler.called  # no error
    assert auth.assertion_content == ref_token
    body = {u'data': {}}
    auth.update_body(body)
    assert body[u'data'][u'TOKEN'] == ref_token
    assert body[u'data'][u'PROOF_KEY'] == REF_PROOF_KEY
    assert body[u'data'][u'AUTHENTICATOR'] == EXTERNAL_BROWSER_AUTHENTICATOR
Esempio n. 6
0
def test_auth_webbrowser_get():
    """Authentication by WebBrowser positive test case."""
    ref_token = "MOCK_TOKEN"

    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = True

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ("\r\n".join([
        f"GET /?token={ref_token}&confirm=true HTTP/1.1",
        "User-Agent: snowflake-agent",
    ])).encode("utf-8")
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    auth = AuthByWebBrowser(rest,
                            APPLICATION,
                            webbrowser_pkg=mock_webbrowser,
                            socket_pkg=mock_socket)
    auth.authenticate(AUTHENTICATOR, SERVICE_NAME, ACCOUNT, USER, PASSWORD)
    assert not rest._connection.errorhandler.called  # no error
    assert auth.assertion_content == ref_token
    body = {"data": {}}
    auth.update_body(body)
    assert body["data"]["TOKEN"] == ref_token
    assert body["data"]["PROOF_KEY"] == REF_PROOF_KEY
    assert body["data"]["AUTHENTICATOR"] == EXTERNAL_BROWSER_AUTHENTICATOR
Esempio n. 7
0
def test_auth_webbrowser_fail_webbrowser(monkeypatch, capsys, input_text,
                                         expected_error):
    """Authentication by WebBrowser with failed to start web browser case."""
    rest = _init_rest(REF_SSO_URL, REF_PROOF_KEY)
    ref_token = "MOCK_TOKEN"

    # mock webbrowser
    mock_webbrowser = MagicMock()
    mock_webbrowser.open_new.return_value = False

    # mock socket
    mock_socket_instance = MagicMock()
    mock_socket_instance.getsockname.return_value = [None, 12345]

    mock_socket_client = MagicMock()
    mock_socket_client.recv.return_value = ("\r\n".join(
        ["GET /?token=MOCK_TOKEN HTTP/1.1",
         "User-Agent: snowflake-agent"])).encode("utf-8")
    mock_socket_instance.accept.return_value = (mock_socket_client, None)
    mock_socket = Mock(return_value=mock_socket_instance)

    auth = AuthByWebBrowser(rest,
                            APPLICATION,
                            webbrowser_pkg=mock_webbrowser,
                            socket_pkg=mock_socket)
    with patch("builtins.input", return_value=input_text):
        auth.authenticate(AUTHENTICATOR, SERVICE_NAME, ACCOUNT, USER, PASSWORD)
    captured = capsys.readouterr()
    assert captured.out == (
        "Initiating login request with your identity provider. A browser window "
        "should have opened for you to complete the login. If you can't see it, "
        "check existing browser windows, or your OS settings. Press CTRL+C to "
        "abort and try again...\nWe were unable to open a browser window for "
        "you, please open the following url manually then paste the URL you "
        f"are redirected to into the terminal.\nURL: {REF_SSO_URL}\n")
    if expected_error:
        assert rest._connection.errorhandler.called  # an error
        assert auth.assertion_content is None
    else:
        assert not rest._connection.errorhandler.called  # no error
        body = {"data": {}}
        auth.update_body(body)
        assert body["data"]["TOKEN"] == ref_token
        assert body["data"]["PROOF_KEY"] == REF_PROOF_KEY
        assert body["data"]["AUTHENTICATOR"] == EXTERNAL_BROWSER_AUTHENTICATOR