Beispiel #1
0
def _GetIAMAuthHandlers(authority_selector, authorization_token_file):
    """Get the request handlers for IAM authority selctors and auth tokens..

  Args:
    authority_selector: str, The authority selector string we want to use for
      the request or None.
    authorization_token_file: str, The file that contains the authorization
      token we want to use for the request or None.

  Returns:
    [transport Modifiers]: A list of request modifier functions to use to wrap
    an http request.
  """
    authorization_token = None
    if authorization_token_file:
        try:
            authorization_token = files.ReadFileContents(
                authorization_token_file)
        except files.Error as e:
            raise Error(e)

    handlers = []
    if authority_selector:
        handlers.append(
            transport.Handler(
                transport.SetHeader('x-goog-iam-authority-selector',
                                    authority_selector)))

    if authorization_token:
        handlers.append(
            transport.Handler(
                transport.SetHeader('x-goog-iam-authorization-token',
                                    authorization_token)))

    return handlers
Beispiel #2
0
    def testReportDuration(self):
        url = 'http://foo.com'
        request_headers = {b'header1': b'value1', b'header2': b'value2'}
        response_headers = {b'header3': b'value3', b'header4': b'value4'}

        self.orig_request.return_value = {
            'status': httplib.OK,
            'headers': response_headers,
            'content': 'response content',
        }

        time_mock = self.StartPatch('time.time', autospec=True)
        # Time is called twice by RPC duration reporting.
        time_mock.side_effect = [1.0, 3.0]

        metrics_mock = self.StartObjectPatch(metrics, 'RPCDuration')

        handlers = [
            transport.Handler(transport.RecordStartTime(),
                              transport.ReportDuration())
        ]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        self.http_client.request(url,
                                 'GET',
                                 headers=request_headers,
                                 body='Request Body')

        metrics_mock.assert_called_once_with(2.0)
Beispiel #3
0
 def QuotaWrappedRequest(self, http_client, quota_project):
     """Returns a request method which adds the quota project header."""
     handlers = [
         transport.Handler(
             transport.SetHeader('X-Goog-User-Project', quota_project))
     ]
     self.WrapRequest(http_client, handlers)
     return http_client.request
Beispiel #4
0
    def testSetHeader(self, current_headers, header, expected_headers):
        handlers = [transport.Handler(transport.SetHeader(header, 'B'))]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        self.http_client.request('uri', 'method', headers=current_headers)
        self.orig_request.assert_called_once_with('uri',
                                                  'method',
                                                  headers=expected_headers)
Beispiel #5
0
    def testLogHttpOauthRedaction(self):
        handlers = [
            transport.Handler(transport.LogRequest(True),
                              transport.LogResponse())
        ]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        def run(url, extra_headers):
            self.orig_request.return_value = {
                'status': httplib.OK,
                'headers': {
                    'header1': 'value1',
                    'header2': 'value2'
                },
                'content': 'response content',
            }
            self.http_client.request(url,
                                     'GET',
                                     body='request content',
                                     headers=extra_headers)
            self.orig_request.assert_called_once()
            self.assertEqual(self.orig_request.call_args[0], (url, 'GET'))
            self.assertEqual(self.orig_request.call_args[1].get('body'),
                             'request content')
            self.orig_request.reset_mock()

        # Test authorization header is redacted.
        run(
            'https://fake.googleapis.com/foo', {
                'Authorization': 'Bearer oauth2token',
                'x-goog-iam-authorization-token': 'iamtoken',
            })
        self.AssertErrNotContains('oauth2token')
        self.AssertErrNotContains('iamtoken')
        self.AssertErrContains('request content')
        self.AssertErrContains('response content')
        self.ClearErr()

        # Test body is redacted from both request and response.
        run('https://accounts.google.com/o/oauth2/token', {})
        self.AssertErrNotContains('request content')
        self.AssertErrNotContains('response content')
        self.ClearErr()

        # Test body is redacted from response. Body of request doesn't matter.
        run(
            'http://metadata.google.internal/computeMetadata/v1/instance/'
            'service-accounts/[email protected]/token',
            {})
        self.AssertErrNotContains('response content')
        self.ClearErr()

        run(
            'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'
            '[email protected]:generateAccessToken?alt='
            'json', {})
        self.AssertErrNotContains('response content')
        self.ClearErr()
Beispiel #6
0
    def testLogRequestResponse(self):
        url = 'http://foo.com'
        request_headers = {b'header1': b'value1', b'header2': b'value2'}
        response_headers = {b'header3': b'value3', b'header4': b'value4'}

        self.orig_request.return_value = {
            'status': httplib.OK,
            'headers': response_headers,
            'content': 'response content',
        }

        time_mock = self.StartPatch('time.time', autospec=True)
        # Time is called twice by logging.
        time_mock.side_effect = [1.0, 3.0]

        log_mock = self.StartObjectPatch(log.status, 'Print')

        handlers = [
            transport.Handler(transport.LogRequest(True),
                              transport.LogResponse())
        ]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        self.http_client.request(url,
                                 'GET',
                                 headers=request_headers,
                                 body='Request Body')
        self.orig_request.assert_called_once_with(url,
                                                  'GET',
                                                  headers=request_headers,
                                                  body='Request Body')
        expected_output = """\
=======================
==== request start ====
uri: http://foo.com
method: GET
== headers start ==
{0}
== headers end ==
== body start ==
Request Body
== body end ==
==== request end ====
---- response start ----
status: 200
-- headers start --
{1}
-- headers end --
-- body start --
response content
-- body end --
total round trip time (request+response): 2.000 secs
---- response end ----
----------------------""".format(self._FormatHeaderOutput(request_headers),
                                 self._FormatHeaderOutput(response_headers))

        log_mock.assert_has_calls(
            [mock.call(line) for line in expected_output.split('\n')])
Beispiel #7
0
    def testHandlers(self):
        mock_request = Request('uri', 'method', {'a': 'b'}, None)
        self.StartObjectPatch(Request,
                              'FromRequestArgs',
                              return_value=mock_request)
        mock_response = Response(httplib.OK, {}, None)
        self.StartObjectPatch(Response,
                              'FromResponse',
                              return_value=mock_response)

        request_handler = mock.Mock(return_value='data')
        response_handler = mock.Mock()
        handlers = [transport.Handler(request_handler, response_handler)]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        self.http_client.request('uri', 'method', headers={'a': 'A'})
        request_handler.assert_called_once_with(mock_request)
        response_handler.assert_called_once_with(mock_response, 'data')
Beispiel #8
0
    def testAddQueryParam(self):
        handlers = [transport.Handler(transport.AddQueryParam('a', 'A'))]
        RequestWrapper().WrapRequest(self.http_client, handlers)

        self.http_client.request('uri.com', 'method')
        self.orig_request.assert_called_once_with('uri.com?a=A', 'method')