Пример #1
0
    def test_auth_system_success(self, mock_mgr_map, mock_request):
        """Test that we can authenticate using the auth system."""
        class FakePlugin(BaseFakePlugin):
            def authenticate(self, cls):
                cls.request("POST",
                            "http://auth/tokens",
                            json={"fake": "me"},
                            allow_redirects=True)

        mock_mgr_map.side_effect = (
            lambda func: func(MockEntrypoint("fake", FakePlugin)))

        mock_request.side_effect = mock_http_request()

        auth.discover_auth_systems()
        plugin = auth.load_plugin("fake")
        cs = client.HTTPClient(auth_plugin=plugin)
        cs.authenticate()

        headers = requested_headers(cs)

        mock_request.assert_called_with("POST",
                                        "http://auth/tokens",
                                        headers=headers,
                                        data='{"fake": "me"}',
                                        allow_redirects=True,
                                        **TEST_REQUEST_BASE)
Пример #2
0
    def test_client_request_expired_token(self):
        side_effect_rv = [False, True]

        def side_effect(*args, **kwargs):
            if side_effect_rv.pop():
                raise exceptions.Unauthorized()
            return

        def new_creds(*args, **kwargs):
            return 'new_token', 'new_endpoint'

        with mock.patch('%s.FakeAuthPlugin.token_and_endpoint' % __name__,
                        mock.MagicMock()) as mocked_token_and_endpoint:
            mocked_token_and_endpoint.side_effect = new_creds

            http_client = client.HTTPClient(FakeAuthPlugin())
            http_client.cached_token = 'old_token'
            http_client.request = mock.MagicMock(side_effect=side_effect)

            http_client.client_request(TestClient(http_client),
                                       "GET",
                                       "/resource",
                                       json={"1": "2"})
            http_client.request.assert_called_with(
                'GET',
                'new_endpoint/resource',
                headers={'X-Auth-Token': 'new_token'},
                json={'1': '2'})
            self.assertEqual('new_token', http_client.cached_token)
Пример #3
0
    def test_client_with_no_token_and_no_endpoint(self):
        with mock.patch('%s.FakeAuthPlugin.token_and_endpoint' % __name__,
                        mock.MagicMock()) as mocked_token_and_endpoint:
            mocked_token_and_endpoint.return_value = (None, None)

            http_client = client.HTTPClient(FakeAuthPlugin())
            self.assertRaises(exceptions.AuthorizationFailure,
                              http_client.client_request,
                              TestClient(http_client),
                              "GET",
                              "/resource",
                              json={"1": "2"})
Пример #4
0
 def test_client_with_response_400_status_code(self):
     http_client = client.HTTPClient(FakeAuthPlugin())
     mock_request = mock.Mock()
     mock_request.return_value = requests.Response()
     mock_request.return_value.status_code = 400
     with mock.patch("requests.Session.request", mock_request):
         self.assertRaises(exceptions.BadRequest,
                           http_client.client_request,
                           TestClient(http_client),
                           "GET",
                           "/resource",
                           json={"bad": "request"})
Пример #5
0
 def test_client_raising_unauthorized_with_equal_token_and_endpoint(self):
     with mock.patch('%s.FakeAuthPlugin.token_and_endpoint' % __name__,
                     mock.MagicMock()) as mocked_token_and_endpoint:
         mocked_token_and_endpoint.return_value = ('token-0', '/endpoint-0')
         http_client = client.HTTPClient(FakeAuthPlugin())
         http_client.request = mock.MagicMock(
             side_effect=exceptions.Unauthorized())
         self.assertRaises(exceptions.Unauthorized,
                           http_client.client_request,
                           TestClient(http_client),
                           "GET",
                           "/resource",
                           json={"1": "2"})
Пример #6
0
 def test_client_with_timeout(self):
     http_client = client.HTTPClient(None, timeout=2)
     self.assertEqual(http_client.timeout, 2)
     mock_request = mock.Mock()
     mock_request.return_value = requests.Response()
     mock_request.return_value.status_code = 200
     with mock.patch("requests.Session.request", mock_request):
         http_client.request("GET", "/", json={"1": "2"})
         requests.Session.request.assert_called_with("GET",
                                                     "/",
                                                     timeout=2,
                                                     headers=mock.ANY,
                                                     verify=mock.ANY,
                                                     data=mock.ANY)
Пример #7
0
    def test_client_request_reissue(self):
        reject_token = None

        def fake_request(method, url, **kwargs):
            if kwargs["headers"]["X-Auth-Token"] == reject_token:
                raise exceptions.Unauthorized(method=method, url=url)
            return "%s %s" % (method, url)

        http_client = client.HTTPClient(FakeAuthPlugin())
        test_client = TestClient(http_client)
        http_client.request = fake_request

        self.assertEqual(
            http_client.client_request(test_client, "GET", "/resource"),
            "GET /endpoint-0/resource")
        reject_token = "token-0"
        self.assertEqual(
            http_client.client_request(test_client, "GET", "/resource"),
            "GET /endpoint-1/resource")
Пример #8
0
    def test_log_req(self):
        self.logger = self.useFixture(
            fixtures.FakeLogger(format="%(message)s",
                                level=logging.DEBUG,
                                nuke_handlers=True))
        cs = client.HTTPClient(FakeAuthPlugin())
        cs.debug = True
        cs._http_log_req('GET', '/foo', {'headers': {}})
        BOGUS_HEADERS_1 = {'headers': {'X-Auth-Token': 'totally_bogus'}}
        cs._http_log_req('GET', '/foo', BOGUS_HEADERS_1)
        BOGUS_HEADERS_2 = {
            'headers': {
                'X-Subject-Token': 'totally_bogus_subject_token'
            }
        }
        cs._http_log_req('GET', '/foo/bar', BOGUS_HEADERS_2)
        BOGUS_HEADERS_3 = {
            'headers': {
                'X-Foo': 'bar',
                'X-Auth-Token': 'totally_bogus',
                'X-Subject-Token': 'totally_bogus_subject_token'
            }
        }
        cs._http_log_req('GET', '/foo', BOGUS_HEADERS_3)

        output = self.logger.output.split('\n')

        self.assertIn("REQ: curl -g -i -X 'GET' '/foo'", output)
        self.assertIn(
            "REQ: curl -g -i -X 'GET' '/foo' -H 'X-Auth-Token: "
            "{SHA1}b42162b6ffdbd7c3c37b7c95b7ba9f51dda0236d'", output)
        self.assertIn(
            "REQ: curl -g -i -X 'GET' '/foo/bar'"
            " -H 'X-Subject-Token: "
            "{SHA1}1999873bee4b1aed81b7abb168044a8cbbbccbd6'", output)
        self.assertIn(
            "REQ: curl -g -i -X 'GET' '/foo' "
            "-H 'X-Subject-Token: "
            "{SHA1}1999873bee4b1aed81b7abb168044a8cbbbccbd6' "
            "-H 'X-Foo: bar' "
            "-H 'X-Auth-Token: "
            "{SHA1}b42162b6ffdbd7c3c37b7c95b7ba9f51dda0236d'", output)
Пример #9
0
 def test_client_request(self):
     http_client = client.HTTPClient(FakeAuthPlugin())
     mock_request = mock.Mock()
     mock_request.return_value = requests.Response()
     mock_request.return_value.status_code = 200
     with mock.patch("requests.Session.request", mock_request):
         http_client.client_request(TestClient(http_client),
                                    "GET",
                                    "/resource",
                                    json={"1": "2"})
         requests.Session.request.assert_called_with(
             "GET",
             "/endpoint-0/resource",
             headers={
                 "User-Agent": http_client.user_agent,
                 "Content-Type": "application/json",
                 "X-Auth-Token": "token-0"
             },
             data='{"1": "2"}',
             verify=True)
Пример #10
0
    def test_client_raising_unauthorized_with_just_authenticated(self):
        side_effect_rv = [True, False, True]

        def side_effect(*args, **kwargs):
            if side_effect_rv.pop():
                raise exceptions.EndpointException()
            return ("token-%s" % len(side_effect_rv),
                    "/endpoint-%s" % len(side_effect_rv))

        with mock.patch('%s.FakeAuthPlugin.token_and_endpoint' % __name__,
                        mock.MagicMock()) as mocked_token_and_endpoint:
            mocked_token_and_endpoint.side_effect = side_effect

            http_client = client.HTTPClient(FakeAuthPlugin())
            http_client.request = mock.MagicMock(
                side_effect=exceptions.Unauthorized())
            self.assertRaises(exceptions.Unauthorized,
                              http_client.client_request,
                              TestClient(http_client),
                              "GET",
                              "/resource",
                              json={"1": "2"})