def testInvalidScope(self):
     """ Test the rejection of a valid request with an invalid scope. """
     invalidScope = 'invalidScope'
     request = self.generateValidTokenRequest(arguments={
         'grant_type': 'refresh_token',
         'refresh_token': self._VALID_REFRESH_TOKEN,
         'scope': invalidScope
     }, authentication=self._VALID_CLIENT)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(request, result, InvalidScopeError(invalidScope),
                                   msg='Expected the token resource to reject a refresh_token '
                                       'request with an invalid scope.')
     invalidScope = self._VALID_SCOPE[0]
     request = self.generateValidTokenRequest(arguments={
         'grant_type': 'refresh_token',
         'refresh_token': self._VALID_REFRESH_TOKEN,
         'scope': invalidScope
     }, authentication=self._VALID_CLIENT)
     self._TOKEN_FACTORY.expectTokenRequest(
         None, self._TOKEN_RESOURCE.authTokenLifeTime, self._VALID_CLIENT,
         [invalidScope], validScope=False)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self._TOKEN_FACTORY.assertAllTokensRequested()
     self.assertFailedTokenRequest(
         request, result, InvalidScopeError(invalidScope),
         msg='Expected the token resource to reject a refresh_token request with '
             'a scope that is rejected by the token factory.')
 def onAuthenticate(self, request, client, responseType, scope,
                    redirectUri, state, dataKey):
     if self.raiseErrorInOnAuthenticate:
         self.raiseErrorInOnAuthenticate = False
         raise RuntimeError(self.ERROR_MESSAGE)
     if self.UNKNOWN_SCOPE in scope:
         raise InvalidScopeError(scope, state=state)
     if self.UNKNOWN_SCOPE_RETURN in scope:
         return InvalidScopeError(scope, state=state)
     if self.UNKNOWN_SCOPE_RAISING_OAUTH2_ERROR in scope:
         raise InvalidTokenError(self.ERROR_MESSAGE)
     if self.TEMPORARY_UNAVAILABLE_SCOPE in scope:
         raise TemporarilyUnavailableError(state=state)
     return request, client, responseType, scope, redirectUri, state, dataKey
Exemple #3
0
 def testGrantAccessInvalidScope(self):
     """
     Test that grandAccess rejects a call with a scope that is not in the original scope.
     """
     dataKey = 'dataKeyInvalidScope' + self._RESPONSE_TYPE
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = MockRequest('GET', 'some/path')
     state = b'state\xFF\xFF'
     data = {
         'response_type':
         self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
         'redirect_uri':
         redirectUri,
         'client_id':
         self._VALID_CLIENT.id,
         'scope': ['All'],
         'state':
         state
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     scope = ['Other']
     result = self._AUTH_RESOURCE.grantAccess(request,
                                              dataKey,
                                              scope=scope)
     self.assertFailedRequest(
         request,
         result,
         InvalidScopeError(scope, state),
         redirectUri=redirectUri,
         msg='Expected grantAccess to reject an invalid scope.')
 def testInvalidScope(self):
     """ Test the rejection of a request with an invalid scope parameters. """
     username = b'someUserName'
     password = b'somePassword'
     request = self.generateValidTokenRequest(
         arguments={
             'grant_type': 'password',
             'username': username,
             'password': password,
             'scope': ' '.join(self._VALID_SCOPE),
         },
         authentication=self._VALID_CLIENT)
     self._TOKEN_FACTORY.expectTokenRequest(
         'token',
         self._TOKEN_RESOURCE.authTokenLifeTime,
         self._VALID_CLIENT,
         self._VALID_SCOPE,
         validScope=False)
     self._PASSWORD_MANAGER.expectAuthenticateRequest(username, password)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertTrue(
         self._PASSWORD_MANAGER.allPasswordsChecked(),
         msg=
         'Expected the token resource to check if the given user name and '
         'password combination is valid before creating an auth token.')
     self._TOKEN_FACTORY.assertAllTokensRequested()
     self.assertFailedTokenRequest(
         request,
         result,
         InvalidScopeError(self._VALID_SCOPE),
         msg='Expected the resource token to reject a '
         'password request with invalid scope parameters.')
Exemple #5
0
 def onAuthenticate(self, request, client, responseType, scope, redirectUri, state, dataKey):
     if self.raiseErrorInOnAuthenticate:
         self.raiseErrorInOnAuthenticate = False
         raise RuntimeError('Expected the auth resource to catch this error')
     if self.UNKNOWN_SCOPE in scope:
         return InvalidScopeError(scope, state=state)
     return request, client, responseType, scope, redirectUri, state, dataKey
 def testMalformedScope(self):
     """ Test the rejection of a valid request with a malformed scope. """
     malformedScope = b'malformedScope\xFF\xFF'
     request = self.generateValidTokenRequest(arguments={
         'grant_type': 'refresh_token',
         'refresh_token': self._VALID_REFRESH_TOKEN,
         'scope': malformedScope
     }, authentication=self._VALID_CLIENT)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(
         request, result, InvalidScopeError(ensureByteString(malformedScope)),
         msg='Expected the token resource to reject a '
             'refresh_token request with an malformed scope.')
Exemple #7
0
 def testAuthorizedClientWithMalformedScope(self):
     """ Test the rejection of a request with a malformed scope parameters. """
     malformedScope = b'malformedScope\xFF\xFF'
     request = self.generateValidTokenRequest(
         arguments={
             'grant_type': 'client_credentials',
             'scope': malformedScope,
         },
         authentication=self._VALID_CLIENT)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(
         request,
         result,
         InvalidScopeError(malformedScope),
         msg='Expected the resource token to reject a '
         'client_credentials request with a malformed scope parameters.')
Exemple #8
0
 def testWithMalformedScope(self):
     """ Test the rejection of a request with a malformed scope. """
     state = b'state\xFF\xFF'
     scope = b'malformedScope\xFF\xFF'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = self.createAuthRequest(arguments={
         'response_type': self._RESPONSE_TYPE,
         'client_id': self._VALID_CLIENT.id,
         'redirect_uri': redirectUri,
         'scope': scope,
         'state': state
     })
     result = self._AUTH_RESOURCE.render_GET(request)
     self.assertFailedRequest(
         request, result, InvalidScopeError(scope, state=state), redirectUri=redirectUri,
         msg='Expected the auth resource to reject a request with a malformed scope.')
Exemple #9
0
 def testInvalidScope(self):
     """ Test the rejection of a valid request with an invalid scope. """
     invalidScope = 'invalidScope'
     request = self.generateValidTokenRequest(
         arguments={
             'grant_type': 'refresh_token',
             'refresh_token': self._VALID_REFRESH_TOKEN,
             'scope': invalidScope
         },
         authentication=self._VALID_CLIENT)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(
         request,
         result,
         InvalidScopeError(invalidScope),
         msg='Expected the token resource to reject a refresh_token '
         'request with an invalid scope.')
Exemple #10
0
 def testSendsErrorInOnAuthenticate(self):
     """ Test tat any AuthorizationErrors returned by onAuthenticate are handled. """
     state = b'state\xFF\xFF'
     scope = self._AUTH_RESOURCE.UNKNOWN_SCOPE
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = self.createAuthRequest(arguments={
         'response_type': 'code',
         'client_id': self._VALID_CLIENT.id,
         'redirect_uri': redirectUri,
         'scope': scope,
         'state': state
     })
     result = self._AUTH_RESOURCE.render_GET(request)
     self.assertFailedRequest(
         request, result, InvalidScopeError(scope, state=state), redirectUri=redirectUri,
         msg='Expected the auth resource to send the error '
             'returned from the onAuthenticate method.')
 def testMalformedScope(self):
     """ Test the rejection of a request with a malformed scope. """
     malformedScope = b'malformedScope\xFF\xFF'
     request = self.generateValidTokenRequest(
         arguments={
             'grant_type': 'password',
             'scope': malformedScope,
             'username': b'someUser',
             'password': b'somePassword',
         },
         authentication=self._VALID_CLIENT)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(
         request,
         result,
         InvalidScopeError(malformedScope),
         msg=
         'Expected the resource token to reject a password request with a malformed scope.'
     )
Exemple #12
0
 def testAuthorizationInvalidScope(self):
     """ Test that a authorization request with an invalid scope is rejected. """
     scope = self._VALID_SCOPE + ['INVALID']
     state = b'state'
     request = OAuth2Abstract.AuthResourceTest.createAuthRequest(arguments={
         'response_type': 'code',
         'client_id': self._VALID_CLIENT.id,
         'redirect_uri': self._VALID_CLIENT.redirectUris[0],
         'scope': ' '.join(scope),
         'state': state
     })
     self._makeExampleRequest(request)
     expectedError = InvalidScopeError(scope, state)
     self.assertEqual(302, request.responseCode,
                      msg='Expected the auth resource to redirect the request.')
     redirectUrl = request.getResponseHeader(b'location')
     self.assertIsNotNone(redirectUrl, msg='Expected the auth resource to redirect the request.')
     parameter = OAuth2Abstract.AuthResourceTest.getParameterFromRedirectUrl(redirectUrl, False)
     self.assertIn('error', parameter, msg='Missing error parameter in response.')
     self.assertEqual(expectedError.name, parameter['error'],
                      msg='Result contained a different error than expected.')
     self.assertIn('error_description', parameter,
                   msg='Missing error_description parameter in response.')
     if not isinstance(expectedError.description, (bytes, str)):
         self.assertEqual(
             expectedError.description.encode('utf-8'), parameter['error_description'],
             msg='Result contained a different error description than expected.')
     else:
         self.assertEqual(
             expectedError.description, parameter['error_description'],
             msg='Result contained a different error description than expected.')
     if expectedError.errorUri is not None:
         self.assertIn('error_uri', parameter,
                       msg='Missing error_uri parameter in response.')
         self.assertEqual(expectedError.errorUri, parameter['error_uri'],
                          msg='Result contained an unexpected error_uri.')
     self.assertIn('state', parameter, msg='Missing state parameter in response.')
     self.assertEqual(
         expectedError.state if isinstance(expectedError.state, str)
         else expectedError.state.decode('utf-8', errors='replace'), parameter['state'],
         msg='Result contained an unexpected state.')
 def testSendsErrorReturnedByOnAuthenticate(self):
     """
     Test that any AuthorizationErrors returned by onAuthenticate
     are handled with a deprecation warning.
     """
     state = b'state\xFF\xFF'
     scope = self._AUTH_RESOURCE.UNKNOWN_SCOPE_RETURN
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = self.createAuthRequest(
         arguments={
             'response_type': 'code',
             'client_id': self._VALID_CLIENT.id,
             'redirect_uri': redirectUri,
             'scope': scope,
             'state': state
         })
     with warnings.catch_warnings(record=True) as caughtWarnings:
         warnings.simplefilter('always')
         result = self._AUTH_RESOURCE.render_GET(request)
         self.assertEqual(
             1,
             len(caughtWarnings),
             msg='Expected the OAuth2 resource to generate a warning, if '
             'onAuthenticate returns an OAuth2Error instead of raising it')
         self.assertTrue(
             issubclass(caughtWarnings[0].category, DeprecationWarning),
             msg=
             'Expected the token resource to generate a DeprecationWarning')
         self.assertIn(
             'Returning an error from onAuthenticate is deprecated',
             str(caughtWarnings[0].message),
             msg=
             'Expected the token resource to generate a DeprecationWarning explaining that '
             'returning an error from onAuthenticate is deprecated.')
     self.assertFailedRequest(
         request,
         result,
         InvalidScopeError(scope, state=state),
         redirectUri=redirectUri,
         msg='Expected the auth resource to send the error '
         'returned from the onAuthenticate method.')
Exemple #14
0
    def onAuthenticate(self, request, client, responseType, scope, redirectUri,
                       state, dataKey):
        for scopeItem in scope:
            if scopeItem not in self._VALID_SCOPES:
                raise InvalidScopeError(scope, state)
        return """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Authorization</title>
</head>
<body>
<form action="/oauth2" method="post">
<p>Allow {client} access to {scope}?</p>
<input type="hidden" name="data_key" value="{dataKey}">
<input type="submit" name="confirm" value="yes">
<input type="submit" name="confirm" value="no">
</form>
</body>
</html>""".format(client=client.id, scope=', '.join(scope),
                  dataKey=dataKey).encode('utf-8')
Exemple #15
0
 def testAuthorizedClientInvalidScope(self):
     """ Test the rejection of a request with an invalid scope parameters. """
     request = self.generateValidTokenRequest(
         arguments={
             'grant_type': 'client_credentials',
             'scope': ' '.join(self._VALID_SCOPE),
         },
         authentication=self._VALID_CLIENT)
     self._TOKEN_FACTORY.expectTokenRequest(
         'token',
         self._TOKEN_RESOURCE.authTokenLifeTime,
         self._VALID_CLIENT,
         self._VALID_SCOPE,
         validScope=False)
     result = self._TOKEN_RESOURCE.render_POST(request)
     self._TOKEN_FACTORY.assertAllTokensRequested()
     self.assertFailedTokenRequest(
         request,
         result,
         InvalidScopeError(self._VALID_SCOPE),
         msg='Expected the resource token to reject a '
         'client_credentials request with invalid scope parameters.')