def testTokenRefreshDeniedByCAAError(self):
     refresh_mock = self.StartObjectPatch(client.OAuth2Credentials,
                                          '_do_refresh_request')
     refresh_mock.side_effect = client.AccessTokenRefreshError(
         'access_deniedAccount restricted')
     http_client = http.Http()
     with self.assertRaisesRegex(
             store.TokenRefreshDeniedByCAAError,
             'Access was blocked due to an organization policy'):
         http_client.request('http://foo.com')
def test_track_list_logic_exception_propagation(service_mock):
    package_name = "com.package.name"
    gp_service_mock = Mock()
    gp_service_mock.create_edit.side_effect = [
        client.AccessTokenRefreshError("Exception")
    ]
    service_mock.return_value = gp_service_mock
    with pytest.raises(client.AccessTokenRefreshError):
        tracks_logic.list_tracks(package_name)
        gp_service_mock.create_edit.assert_called_once_with(package_name)
        gp_service_mock.list_tracks.assert_not_called()
 def testBatchTokenRefreshDeniedByCAAError(self):
     refresh_mock = self.StartObjectPatch(client.OAuth2Credentials,
                                          '_do_refresh_request')
     refresh_mock.side_effect = client.AccessTokenRefreshError(
         'access_deniedAccount restricted')
     http_client = http.Http()
     batch_http_request = batch.BatchHttpRequest(
         'https://www.googleapis.com/batch/compute')
     with self.assertRaisesRegex(
             store.TokenRefreshDeniedByCAAError,
             'Access was blocked due to an organization policy'):
         batch_http_request.Execute(http_client)
Exemple #4
0
    def _refresh(self, http):
        """Refreshes the access token.

        Since the underlying App Engine app_identity implementation does its
        own caching we can skip all the storage hoops and just to a refresh
        using the API.

        Args:
            http: unused HTTP object

        Raises:
            AccessTokenRefreshError: When the refresh fails.
        """
        try:
            scopes = self.scope.split()
            (token, _) = app_identity.get_access_token(
                scopes, service_account_id=self.service_account_id)
        except app_identity.Error as e:
            raise client.AccessTokenRefreshError(str(e))
        self.access_token = token
Exemple #5
0
    def _refresh(self, http_request):
        """Refreshes the access_token.

        Since the underlying App Engine app_identity implementation does its
        own caching we can skip all the storage hoops and just to a refresh
        using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make the
                          refresh request.

        Raises:
            AccessTokenRefreshError: When the refresh fails.
        """
        try:
            scopes = self.scope.split()
            (token, _) = app_identity.get_access_token(
                scopes, service_account_id=self.service_account_id)
        except app_identity.Error as e:
            raise client.AccessTokenRefreshError(str(e))
        self.access_token = token
Exemple #6
0
    def test_required(self, new_http):
        new_http.return_value = http_mock.HttpMock(data=DEFAULT_RESP)
        # An initial request to an oauth_required decorated path should be a
        # redirect to start the OAuth dance.
        self.assertEqual(self.decorator.flow, None)
        self.assertEqual(self.decorator.credentials, None)
        response = self.app.get('http://localhost/foo_path')
        self.assertTrue(response.status.startswith('302'))
        q = urllib.parse.parse_qs(response.headers['Location'].split('?',
                                                                     1)[1])
        self.assertEqual('http://localhost/oauth2callback',
                         q['redirect_uri'][0])
        self.assertEqual('foo_client_id', q['client_id'][0])
        self.assertEqual('foo_scope bar_scope', q['scope'][0])
        self.assertEqual('http://localhost/foo_path',
                         q['state'][0].rsplit(':', 1)[0])
        self.assertEqual('code', q['response_type'][0])
        self.assertEqual(False, self.decorator.has_credentials())

        with mock.patch.object(appengine,
                               '_parse_state_value',
                               return_value='foo_path',
                               autospec=True) as parse_state_value:
            # Now simulate the callback to /oauth2callback.
            response = self.app.get('/oauth2callback', {
                'code': 'foo_access_code',
                'state': 'foo_path:xsrfkey123',
            })
            parts = response.headers['Location'].split('?', 1)
            self.assertEqual('http://localhost/foo_path', parts[0])
            self.assertEqual(None, self.decorator.credentials)
            if self.decorator._token_response_param:
                response_query = urllib.parse.parse_qs(parts[1])
                response = response_query[
                    self.decorator._token_response_param][0]
                self.assertEqual(json.loads(DEFAULT_RESP),
                                 json.loads(urllib.parse.unquote(response)))
            self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
            self.assertEqual(self.decorator.credentials,
                             self.decorator._tls.credentials)

            parse_state_value.assert_called_once_with('foo_path:xsrfkey123',
                                                      self.current_user)

        # Now requesting the decorated path should work.
        response = self.app.get('/foo_path')
        self.assertEqual('200 OK', response.status)
        self.assertEqual(True, self.had_credentials)
        self.assertEqual('foo_refresh_token',
                         self.found_credentials.refresh_token)
        self.assertEqual('foo_access_token',
                         self.found_credentials.access_token)
        self.assertEqual(None, self.decorator.credentials)

        # Raising an exception still clears the Credentials.
        self.should_raise = Exception('')
        with self.assertRaises(Exception):
            self.app.get('/foo_path')
        self.should_raise = False
        self.assertEqual(None, self.decorator.credentials)

        # Access token refresh error should start the dance again
        self.should_raise = client.AccessTokenRefreshError()
        response = self.app.get('/foo_path')
        self.should_raise = False
        self.assertTrue(response.status.startswith('302'))
        query_params = urllib.parse.parse_qs(
            response.headers['Location'].split('?', 1)[1])
        self.assertEqual('http://localhost/oauth2callback',
                         query_params['redirect_uri'][0])

        # Invalidate the stored Credentials.
        self.found_credentials.invalid = True
        self.found_credentials.store.put(self.found_credentials)

        # Invalid Credentials should start the OAuth dance again.
        response = self.app.get('/foo_path')
        self.assertTrue(response.status.startswith('302'))
        query_params = urllib.parse.parse_qs(
            response.headers['Location'].split('?', 1)[1])
        self.assertEqual('http://localhost/oauth2callback',
                         query_params['redirect_uri'][0])

        # Check the mocks were called.
        new_http.assert_called_once_with()
 def _Poll(self):
     raise client.AccessTokenRefreshError()