Beispiel #1
0
 def test_refresh_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         requests.get.return_value = MockResponse(
             '%s/v2/info' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(api_version='2.1',
                      authorization_endpoint=TARGET_ENDPOINT)))
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(TARGET_ENDPOINT, token_format='opaque')
         client.init_with_token('refresh-token')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type='refresh_token',
                       scope='',
                       refresh_token='refresh-token',
                       token_format='opaque'),
             headers=dict(Accept='application/json',
                          Authorization='Basic Y2Y6'),
             proxies=dict(http='', https=''),
             verify=True)
Beispiel #2
0
 def _mock_info_calls(requests,
                      with_doppler: bool = True,
                      with_log_streams: bool = True):
     requests.get.side_effect = [
         MockResponse(
             "%s/v2/info" % AbstractTestCase.TARGET_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(
                     authorization_endpoint=AbstractTestCase.
                     AUTHORIZATION_ENDPOINT,
                     token_endpoint=AbstractTestCase.TOKEN_ENDPOINT,
                 )),
         ),
         MockResponse(
             "%s/" % AbstractTestCase.TARGET_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(
                     links={
                         "self":
                         dict(href=AbstractTestCase.TARGET_ENDPOINT),
                         "cloud_controller_v2":
                         dict(
                             href="%s/v2" %
                             AbstractTestCase.TARGET_ENDPOINT,
                             meta=dict(
                                 version=AbstractTestCase.API_V2_VERSION),
                         ),
                         "cloud_controller_v3":
                         dict(
                             href="%s/v3" %
                             AbstractTestCase.TARGET_ENDPOINT,
                             meta=dict(
                                 version=AbstractTestCase.API_V3_VERSION),
                         ),
                         "logging":
                         dict(href=AbstractTestCase.DOPPLER_ENDPOINT
                              ) if with_doppler else None,
                         "log_stream":
                         dict(href=AbstractTestCase.LOG_STREAM_ENDPOINT
                              ) if with_log_streams else None,
                         "app_ssh":
                         dict(href="ssh.nd-cfapi.itn.ftgroup:80"),
                         "uaa":
                         dict(href="https://uaa.nd-cfapi.itn.ftgroup"),
                         "network_policy_v0":
                         dict(
                             href=
                             "https://api.nd-cfapi.itn.ftgroup/networking/v0/external"
                         ),
                         "network_policy_v1":
                         dict(
                             href=
                             "https://api.nd-cfapi.itn.ftgroup/networking/v1/external"
                         ),
                     })),
         ),
     ]
 def _mock_info_calls(requests,
                      with_doppler: bool = True,
                      with_log_streams: bool = True):
     requests.get.side_effect = [
         MockResponse(
             '%s/v2/info' % AbstractTestCase.TARGET_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(authorization_endpoint=AbstractTestCase.
                      AUTHORIZATION_ENDPOINT,
                      token_endpoint=AbstractTestCase.TOKEN_ENDPOINT))),
         MockResponse(
             '%s/' % AbstractTestCase.TARGET_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(
                     links={
                         'self':
                         dict(href=AbstractTestCase.TARGET_ENDPOINT),
                         'cloud_controller_v2':
                         dict(href='%s/v2' %
                              AbstractTestCase.TARGET_ENDPOINT,
                              meta=dict(
                                  version=AbstractTestCase.API_V2_VERSION)),
                         'cloud_controller_v3':
                         dict(href='%s/v3' %
                              AbstractTestCase.TARGET_ENDPOINT,
                              meta=dict(
                                  version=AbstractTestCase.API_V3_VERSION)),
                         'logging':
                         dict(href=AbstractTestCase.DOPPLER_ENDPOINT
                              ) if with_doppler else None,
                         'log_stream':
                         dict(href=AbstractTestCase.LOG_STREAM_ENDPOINT
                              ) if with_log_streams else None,
                         'app_ssh':
                         dict(href='ssh.nd-cfapi.itn.ftgroup:80'),
                         'uaa':
                         dict(href='https://uaa.nd-cfapi.itn.ftgroup'),
                         'network_policy_v0':
                         dict(
                             href=
                             'https://api.nd-cfapi.itn.ftgroup/networking/v0/external'
                         ),
                         'network_policy_v1':
                         dict(
                             href=
                             'https://api.nd-cfapi.itn.ftgroup/networking/v1/external'
                         )
                     })))
     ]
Beispiel #4
0
 def mock_response(uri: str, status_code: HTTPStatus, headers: Optional[dict], *path_parts: str):
     if len(path_parts) > 0:
         file_name = path_parts[len(path_parts) - 1]
         extension_idx = file_name.rfind(".")
         binary_file = extension_idx >= 0 and file_name[extension_idx:] == ".bin"
         with (open(AbstractTestCase.get_fixtures_path(*path_parts), "rb" if binary_file else "r")) as f:
             return MockResponse(
                 url="%s%s" % (AbstractTestCase.TARGET_ENDPOINT, uri),
                 status_code=status_code.value,
                 text=f.read(),
                 headers=headers,
             )
     else:
         return MockResponse("%s%s" % (AbstractTestCase.TARGET_ENDPOINT, uri), status_code.value, "", headers)
Beispiel #5
0
 def test_grant_password_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(self.TARGET_ENDPOINT,
                                     token_format='opaque')
         client.init_with_user_credentials('somebody', 'p@s$w0rd')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(requests.post.return_value.url,
                                          data=dict(grant_type='password',
                                                    username='******',
                                                    scope='',
                                                    password='******',
                                                    token_format='opaque'),
                                          headers=dict(
                                              Accept='application/json',
                                              Authorization='Basic Y2Y6'),
                                          proxies=dict(http='', https=''),
                                          verify=True)
Beispiel #6
0
 def test_grant_password_request_with_login_hint(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests", new=requests), patch(
         "cloudfoundry_client.client.requests", new=requests
     ):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             "%s/oauth/token" % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(dict(access_token="access-token", refresh_token="refresh-token")),
         )
         client = CloudFoundryClient(
             self.TARGET_ENDPOINT, login_hint=quote(json.dumps(dict(origin="uaa"), separators=(",", ":")))
         )
         client.init_with_user_credentials("somebody", "p@s$w0rd")
         self.assertEqual("Bearer access-token", session.headers.get("Authorization"))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(
                 grant_type="password",
                 username="******",
                 scope="",
                 password="******",
                 login_hint="%7B%22origin%22%3A%22uaa%22%7D",
             ),
             headers=dict(Accept="application/json", Authorization="Basic Y2Y6"),
             proxies=dict(http="", https=""),
             verify=True,
         )
 def test_check_response_200(self):
     response = MockResponse("http://some-cf-url",
                             200,
                             text=json.dumps(
                                 dict(entity="entityTest",
                                      metadata="metadataTest")))
     self.assertIsNotNone(CloudFoundryClient._check_response(response))
 def test_refresh_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests",
                new=requests), patch("cloudfoundry_client.client.requests",
                                     new=requests):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             "%s/oauth/token" % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(access_token="access-token",
                      refresh_token="refresh-token")),
         )
         client = CloudFoundryClient(self.TARGET_ENDPOINT,
                                     token_format="opaque")
         client.init_with_token("refresh-token")
         self.assertEqual("Bearer access-token",
                          session.headers.get("Authorization"))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type="refresh_token",
                       scope="",
                       refresh_token="refresh-token",
                       token_format="opaque"),
             headers=dict(Accept="application/json",
                          Authorization="Basic Y2Y6"),
             proxies=dict(http="", https=""),
             verify=True,
         )
 def test_check_response_500_json(self):
     response = MockResponse("http://some-cf-url",
                             500,
                             text=json.dumps(
                                 dict(entity="entityTest",
                                      metadata="metadataTest")))
     with self.assertRaisesRegex(InvalidStatusCode, "metadataTest"):
         CloudFoundryClient._check_response(response)
 def test_invalid_token_v2(self):
     response = MockResponse("http://some-cf-url",
                             401,
                             text=json.dumps(
                                 dict(code=1000,
                                      error_code="CF-InvalidAuthToken")))
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
Beispiel #11
0
 def test_check_response_500_with_vcap(self):
     response = MockResponse(
         "http://some-cf-url",
         500,
         text=json.dumps(dict(entity="entityTest", metadata="metadataTest")),
         headers={"x-vcap-request-id": "testVcap"},
     )
     with self.assertRaisesRegex(InvalidStatusCode, "testVcap"):
         CloudFoundryClient._check_response(response)
 def mock_response(uri: str, status_code: HTTPStatus,
                   headers: Optional[dict], *path_parts: str):
     if len(path_parts) > 0:
         file_name = path_parts[len(path_parts) - 1]
         extension_idx = file_name.rfind('.')
         binary_file = extension_idx >= 0 and file_name[
             extension_idx:] == '.bin'
         with (open(AbstractTestCase.get_fixtures_path(*path_parts),
                    'rb' if binary_file else 'r')) as f:
             return MockResponse(url='%s%s' %
                                 (AbstractTestCase.TARGET_ENDPOINT, uri),
                                 status_code=status_code.value,
                                 text=f.read(),
                                 headers=headers)
     else:
         return MockResponse(
             '%s%s' % (AbstractTestCase.TARGET_ENDPOINT, uri),
             status_code.value, '')
Beispiel #13
0
 def test_log_request_empty_headers(self):
     response = MockResponse("http://some-cf-url", 200, text=json.dumps(dict(entity="entityTest", metadata="metadataTest")))
     with self.assertLogs(level="DEBUG") as cm:
         CloudFoundryClient._log_request("GET", "testURL", response)
     self.assertEqual(
         cm.output,
         [
             "DEBUG:cloudfoundry_client.client:GET: url=testURL - status_code=200 - vcap-request-id=N/A - response="
             '{"entity": "entityTest", "metadata": "metadataTest"}'
         ],
     )
Beispiel #14
0
 def test_invalid_token_v3(self):
     response = MockResponse(
         'http://some-cf-url',
         401,
         text=json.dumps(
             dict(errors=[
                 dict(code=666, title='Some-Error', detail='Error detail'),
                 dict(code=1000,
                      title='CF-InvalidAuthToken',
                      detail='Invalid token')
             ])))
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
 def test_invalid_token_v3(self):
     response = MockResponse(
         "http://some-cf-url",
         401,
         text=json.dumps(
             dict(errors=[
                 dict(code=666, title="Some-Error", detail="Error detail"),
                 dict(code=1000,
                      title="CF-InvalidAuthToken",
                      detail="Invalid token"),
             ])),
     )
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
Beispiel #16
0
 def test_grant_password_request_with_login_hint(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         requests.get.return_value = MockResponse(
             '%s/v2/info' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(api_version='2.1',
                      authorization_endpoint=TARGET_ENDPOINT)))
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(TARGET_ENDPOINT,
                                     login_hint=quote(
                                         json.dumps(dict(origin='uaa'),
                                                    separators=(',', ':'))))
         client.init_with_user_credentials('somebody', 'p@s$w0rd')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type='password',
                       username='******',
                       scope='',
                       password='******',
                       login_hint='%7B%22origin%22%3A%22uaa%22%7D'),
             headers=dict(Accept='application/json',
                          Authorization='Basic Y2Y6'),
             proxies=dict(http='', https=''),
             verify=True)
Beispiel #17
0
 def test_check_response_500_text(self):
     response = MockResponse("http://some-cf-url", 500, text="This is test text")
     with self.assertRaisesRegex(InvalidStatusCode, "This is test text"):
         CloudFoundryClient._check_response(response)