Exemplo n.º 1
0
 def testRequestOverInsecureTransport(self):
     """
     Test the rejection of a request to a protected resource
     with a valid token that was made over an insecure protocol.
     """
     request = MockRequest('GET', 'protectedResource', isSecure=False)
     request.setRequestHeader(b'Authorization',
                              'Bearer ' + self.VALID_TOKEN)
     self.assertTrue(
         isAuthorized(request,
                      self.VALID_TOKEN_SCOPE,
                      allowInsecureRequestDebug=True),
         msg=
         'Expected isAuthorized to accept a request over an insecure protocol '
         'if "allowInsecureRequestDebug" is set to True.')
     self.assertFalse(
         isAuthorized(request, self.VALID_TOKEN_SCOPE),
         msg=
         'Expected isAuthorized to reject a request over an insecure protocol.'
     )
     self.assertEqual(
         400,
         request.responseCode,
         msg=
         'The HTTP response code should be {code}, if a protected resource receives a '
         'request over an insecure channel.'.format(code=400))
Exemplo n.º 2
0
 def testAccessClockResourceWithoutToken(self):
     """ Test that a request to the protected resource with an invalid token is rejected. """
     request = MockRequest('GET', 'clock')
     self._makeExampleRequest(request)
     self.assertEqual(401, request.responseCode, msg='Expected the protected clock resource '
                                                     'to reject a request without a token.')
     self.assertNotSubstring(b'<html><body>', request.getResponse(),
                             msg='Expected the protected clock resource '
                                 'not to send the protected content.')
Exemplo n.º 3
0
 def testWrongAccessToken(self):
     """ Test the rejection of a request to a protected resource with an invalid token. """
     request = MockRequest('GET', 'protectedResource')
     request.setRequestHeader(b'Authorization', b'Bearer an invalid token')
     self.assertFalse(
         isAuthorized(request, 'scope'),
         msg=
         'Expected isAuthorized to reject a request with an invalid token.')
     self.assertFailedProtectedResourceRequest(
         request, InvalidTokenRequestError(['scope']))
Exemplo n.º 4
0
 def testAuthorizationCodeGrantDeny(self):
     """ Test the authorization code grant flow when the user denies. """
     state = b'state'
     request = AbstractAuthResourceTest.createAuthRequest(
         arguments={
             'response_type': 'code',
             'client_id': self._VALID_CLIENT.id,
             'redirect_uri': self._VALID_CLIENT.redirectUris[0],
             'scope': ' '.join(self._VALID_SCOPE),
             'state': state
         })
     self._SERVER.makeSynchronousRequest(request)
     self.assertIn(
         request.responseCode, (None, 200),
         msg='Expected the auth resource to accept a valid request.')
     response = request.getResponse()
     self.assertSubstring(
         b'<!DOCTYPE html>',
         response,
         msg=
         'Expected the auth resource to send the content returned by onAuthenticate.'
     )
     dataKey = re.search(b"<input.*name=\"data_key\".*value=\"(?P<dataKey>.*)\">", response) \
         .group('dataKey')
     request = MockRequest('POST',
                           'oauth2',
                           arguments={
                               'confirm': 'no',
                               'data_key': dataKey
                           })
     self._SERVER.makeSynchronousRequest(request)
     self.assertEquals(
         request.responseCode,
         302,
         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 = AbstractAuthResourceTest.getParameterFromRedirectUrl(
         redirectUrl, False)
     self.assertIn('error',
                   parameter,
                   msg='Missing error parameter in response.')
     self.assertEquals(parameter['error'],
                       UserDeniesAuthorization().message,
                       msg='Result contained an unexpected error.')
     self.assertIn('state',
                   parameter,
                   msg='Missing state parameter in response.')
     self.assertEquals(parameter['state'],
                       state if isinstance(state, str) else state.decode(
                           'utf-8', errors='replace'),
                       msg='Result contained an unexpected state.')
Exemplo n.º 5
0
 def _testValidAccessRequest(self, token=_VALID_TOKEN):
     """
     Test that a request to the protected resource with the given token is accepted.
     :param token: The token to use in the request.
     """
     request = MockRequest('GET', 'clock')
     request.setRequestHeader(b'Authorization', 'Bearer ' + token)
     self._makeExampleRequest(request)
     self.assertIn(
         request.responseCode, (None, 200),
         msg='Expected the protected clock resource to accept a request with a valid token.')
     self.assertSubstring(
         b'<html><body>', request.getResponse(),
         msg='Expected the protected clock resource to send the protected content.')
Exemplo n.º 6
0
 def testInvalidScope(self):
     """
     Test the rejection of a request to a protected resource
     with a valid token that does not grant access to the necessary scopes.
     """
     request = MockRequest('GET', 'protectedResource')
     request.setRequestHeader(b'Authorization',
                              'Bearer ' + self.VALID_TOKEN)
     self.assertFalse(
         isAuthorized(request, 'someOtherScope'),
         msg='Expected isAuthorized to reject a request with token '
         'that does not allow access to the given scope.')
     self.assertFailedProtectedResourceRequest(
         request, InsufficientScopeRequestError(['someOtherScope']))
Exemplo n.º 7
0
 def testWithAccessTokenInHeader(self):
     """
     Test a request to a protected resource with a valid token in the Authorization header.
     See https://tools.ietf.org/html/rfc6750#section-2.1
     """
     request = MockRequest('GET', 'protectedResource')
     request.setRequestHeader(b'Authorization',
                              'Bearer ' + self.VALID_TOKEN)
     self.assertTrue(
         isAuthorized(request, self.VALID_TOKEN_SCOPE[0]),
         msg='Expected isAuthorized to accept a request with a valid token.'
     )
     self.assertFalse(
         request.finished,
         msg='isAuthorized should not finish the request if it\'s valid.')
Exemplo n.º 8
0
 def testGrantAccessCustomResponseType(self):
     """ Test that grantAccess rejects a call for a request with a custom response type. """
     responseType = 'myCustomResponseType'
     state = b'state\xFF\xFF'
     client = PasswordClient('customResponseTypeClientGrantAccess',
                             ['https://redirect.noexistent'],
                             [responseType], 'clientSecret')
     dataKey = 'customResponseTypeDataKey'
     self._PERSISTENT_STORAGE.put(
         dataKey, {
             'response_type': responseType,
             'client_id': client.id,
             'redirect_uri': client.redirectUris[0],
             'scope': 'All',
             'state': state
         })
     request = MockRequest('GET', 'some/path')
     self._CLIENT_STORAGE.addClient(client)
     self.assertRaises(ValueError, self._AUTH_RESOURCE.grantAccess, request,
                       dataKey)
     try:
         self.assertEqual(
             self._AUTH_RESOURCE.requestDataLifetime,
             self._PERSISTENT_STORAGE.getExpireTime(dataKey),
             msg='Expected the data to be stored with the expected lifetime.'
         )
         self._PERSISTENT_STORAGE.pop(dataKey)
     except KeyError:
         self.fail(
             'Expected the data to still be in the persistent storage.')
Exemplo n.º 9
0
        def _testGrantAccessAdditionalData(self, dataKey, responseType, msg):
            """
            Ensure that additional data given to grantAccess is stored with the code.

            :param dataKey: The  key to store the data.
            :param responseType: The response type of the authorization request.
            :param msg: The assertion message.
            """
            redirectUri = self._VALID_CLIENT.redirectUris[0]
            request = MockRequest('GET', 'some/path')
            additionalData = 'someData'
            data = {
                'response_type': responseType,
                'redirect_uri': redirectUri,
                'client_id': self._VALID_CLIENT.id,
                'scope': ['All'],
                'state': b'state\xFF\xFF'
            }
            self._PERSISTENT_STORAGE.put(dataKey, data)
            result = self._AUTH_RESOURCE.grantAccess(
                request, dataKey, additionalData=additionalData)
            self.assertValidCodeResponse(request,
                                         result,
                                         data,
                                         expectedAdditionalData=additionalData,
                                         msg=msg)
Exemplo n.º 10
0
 def testGrantAccessSubsetScope(self):
     """ Test that grandAccess accepts a call with a subset of the original scope. """
     dataKey = 'dataKeySubsetScope' + self._RESPONSE_TYPE
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = MockRequest('GET', 'some/path')
     data = {
         'response_type':
         self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
         'redirect_uri':
         redirectUri,
         'client_id':
         self._VALID_CLIENT.id,
         'scope': ['All', 'Other'],
         'state':
         b'state\xFF\xFF'
     }
     scope = ['Other']
     self._PERSISTENT_STORAGE.put(dataKey, data)
     result = self._AUTH_RESOURCE.grantAccess(request,
                                              dataKey,
                                              scope=scope)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         expectedScope=scope,
         msg=
         'Expected the auth resource to correctly handle a valid accepted '
         '{type} grant with a subset of the scope original '
         'requested.'.format(type=self._RESPONSE_TYPE))
Exemplo n.º 11
0
 def testGrantAccessInsecureConnectionAllowed(self):
     """
     Test that grandAccess accepts a call with a
     request over an insecure transport if it is allowed.
     """
     dataKey = 'insecureConnectionDataKey' + self._RESPONSE_TYPE
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = MockRequest('GET', 'some/path', isSecure=False)
     data = {
         'response_type':
         self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
         'redirect_uri':
         redirectUri,
         'client_id':
         self._VALID_CLIENT.id,
         'scope': ['All'],
         'state':
         b'state\xFF\xFF'
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     authResource = OAuth2Abstract.AuthResourceTest.TestOAuth2Resource(
         self._TOKEN_FACTORY,
         self._PERSISTENT_STORAGE,
         self._CLIENT_STORAGE,
         authTokenStorage=self._TOKEN_STORAGE,
         allowInsecureRequestDebug=True)
     result = authResource.grantAccess(request, dataKey)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         msg='Expected the auth resource to correctly handle a valid '
         'accepted {type} grant request over an insecure transport, '
         'if it is allowed.'.format(type=self._RESPONSE_TYPE))
Exemplo n.º 12
0
 def testGrantAccessInsecureConnection(self):
     """
     Test that grandAccess returns the expected error
     for a request over an insecure transport.
     """
     dataKey = 'insecureConnectionDataKey' + self._RESPONSE_TYPE
     request = MockRequest('GET', 'some/path', isSecure=False)
     state = b'state\xFF\xFF'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     self._PERSISTENT_STORAGE.put(
         dataKey, {
             'response_type':
             self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
             'redirect_uri':
             redirectUri,
             'client_id':
             self._VALID_CLIENT.id,
             'scope':
             'All',
             'state':
             state
         })
     result = self._AUTH_RESOURCE.grantAccess(request, dataKey)
     self.assertFailedRequest(
         request,
         result,
         InsecureConnectionError(state),
         redirectUri=redirectUri,
         msg='Expected the authorization resource to '
         'reject a request over an insecure transport.')
Exemplo n.º 13
0
    def test_signing_is_enforced(self):
        """
        Test that the supplied signature (in field merchantSig) is checked and
        notifications are ignored when the signature doesn't match.

        In an ideal world, our other tests would ignore the signature checking
        because it's annoying to have to alter the sig when altering the fake
        data. Maik gets valid signatures by adding a print(expected_hash) to
        PaymentRedirection.validate.
        """
        fake_signature = copy(AUTHORISED_PAYMENT_PARAMS_GET)
        fake_signature['merchantSig'] = '14M4N3V1LH4X0RZ'
        signature_none = copy(AUTHORISED_PAYMENT_PARAMS_GET)
        signature_none['merchantSig'] = None
        signature_empty = copy(AUTHORISED_PAYMENT_PARAMS_GET)
        signature_empty['merchantSig'] = ''

        for tampered_data in [fake_signature, signature_empty, signature_none]:
            request = MockRequest(tampered_data)
            try:
                Scaffold().handle_payment_feedback(request)
            except (InvalidTransactionException, MissingFieldException):
                pass
            else:
                raise AssertionError(
                    "Should've raised an exception, but didn't")

        # Make sure we haven't recorded any of those faulty transactions.
        # That way, nobody can fill up our database!
        assert not AdyenTransaction.objects.exists()
Exemplo n.º 14
0
 def testAccessTokenInBodyWrongMethod(self):
     """
     Test the rejection of a request to a protected resource with a valid token
     in the request body but a request that was not made with the POST method.
     """
     request = MockRequest('GET',
                           'protectedResource',
                           arguments={'access_token': self.VALID_TOKEN})
     request.setRequestHeader('Content-Type',
                              'application/x-www-form-urlencoded')
     self.assertFalse(
         isAuthorized(request, self.VALID_TOKEN_SCOPE),
         msg='Expected isAuthorized to reject a request with a valid token '
         'in the request body that was not send with the POST method.')
     self.assertFailedProtectedResourceRequest(
         request, MissingTokenError(self.VALID_TOKEN_SCOPE))
Exemplo n.º 15
0
 def testDenyAccess(self):
     """ Test that denyAccess redirects with the expected error. """
     dataKey = 'userDenies_' + self._RESPONSE_TYPE
     state = b'state\xFF\xFF'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     self._PERSISTENT_STORAGE.put(
         dataKey, {
             'response_type':
             self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
             'redirect_uri':
             redirectUri,
             'client_id':
             self._VALID_CLIENT.id,
             'scope':
             'All',
             'state':
             state
         })
     request = MockRequest('GET', 'some/path')
     result = self._AUTH_RESOURCE.denyAccess(request, dataKey)
     self.assertFailedRequest(
         request,
         result,
         UserDeniesAuthorization(state),
         redirectUri=redirectUri,
         msg='Expected denyAccess to redirect the resource owner to the '
         'redirection endpoint with an access denied error.')
Exemplo n.º 16
0
 def testAccessTokenInBodyWrongContentType(self):
     """
     Test the rejection of a request to a protected resource
     with a valid token but an invalid content type.
     """
     request = MockRequest('POST',
                           'protectedResource',
                           arguments={'access_token': self.VALID_TOKEN})
     request.setRequestHeader('Content-Type', 'application/other')
     self.assertFalse(
         isAuthorized(request, self.VALID_TOKEN_SCOPE),
         msg='Expected isAuthorized to reject a request '
         'with a valid token in the request body with a content type '
         'that is not "application/x-www-form-urlencoded".')
     self.assertFailedProtectedResourceRequest(
         request, MissingTokenError(self.VALID_TOKEN_SCOPE))
Exemplo n.º 17
0
 def testWithAccessTokenInBody(self):
     """
     Test a request to a protected resource with a valid token in the request body.
     See https://tools.ietf.org/html/rfc6750#section-2.2
     """
     request = MockRequest('POST',
                           'protectedResource',
                           arguments={'access_token': self.VALID_TOKEN})
     request.setRequestHeader('Content-Type',
                              'application/x-www-form-urlencoded')
     self.assertTrue(isAuthorized(request, self.VALID_TOKEN_SCOPE[0]),
                     msg='Expected isAuthorized to accept a request '
                     'with a valid token in the request body.')
     self.assertFalse(
         request.finished,
         msg='isAuthorized should not finish the request if it\'s valid.')
 def testGrantAccessAdditionalData(self):
     """ Ensure that additional data given to grantAccess is stored with the code. """
     dataKey = 'authorizationCodeGrantDataKeyAdditionalData'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = MockRequest('GET', 'some/path')
     additionalData = 'someData'
     data = {
         'response_type': GrantTypes.AuthorizationCode.value,
         'redirect_uri': redirectUri,
         'client_id': self._VALID_CLIENT.id,
         'scope': ['All'],
         'state': b'state\xFF\xFF'
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     result = self._AUTH_RESOURCE.grantAccess(request,
                                              dataKey,
                                              additionalData=additionalData)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         expectedAdditionalData=additionalData,
         msg=
         'Expected the auth resource to correctly handle a valid accepted code grant '
         'and store the code data with the given additional data.')
Exemplo n.º 19
0
 def testAccessTokenLifetime(self):
     """ Ensure that the token lifetime is controlled by the authTokenLifeTime parameter. """
     dataKey = 'implicitGrantDataKeySubsetLifetime'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     request = MockRequest('GET', 'some/path')
     lifetime = 10
     scope = ['All']
     data = {
         'response_type': GrantTypes.IMPLICIT.value,
         'redirect_uri': redirectUri,
         'client_id': self._VALID_CLIENT.id,
         'scope': scope,
         'state': b'state\xFF\xFF'
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     authResource = self.TestOAuth2Resource(
         self._TOKEN_FACTORY,
         self._PERSISTENT_STORAGE,
         self._CLIENT_STORAGE,
         authTokenLifeTime=lifetime,
         authTokenStorage=self._TOKEN_STORAGE)
     result = authResource.grantAccess(request, dataKey, scope=scope)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         expectedScope=scope,
         expectedAccessTokenLifetime=lifetime,
         msg=
         'Expected the auth resource to correctly handle a valid accepted {type} grant '
         'with a subset of the scope original requested.'.format(
             type=self._RESPONSE_TYPE))
 def testGrantAccessCodeLifetime(self):
     """ Ensure that the code lifetime is controlled by the codeDataLifetime parameter. """
     dataKey = 'authorizationCodeGrantDataKeyLifetime'
     redirectUri = self._VALID_CLIENT.redirectUris[0]
     lifeTime = 60
     request = MockRequest('GET', 'some/path')
     data = {
         'response_type': GrantTypes.AuthorizationCode.value,
         'redirect_uri': redirectUri,
         'client_id': self._VALID_CLIENT.id,
         'scope': ['All'],
         'state': b'state\xFF\xFF'
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     result = self._AUTH_RESOURCE.grantAccess(request,
                                              dataKey,
                                              codeLifeTime=lifeTime)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         expectedCodeDataLifetime=lifeTime,
         msg=
         'Expected the auth resource to correctly handle a valid accepted code grant '
         'and store the code data with the given lifetime.')
Exemplo n.º 21
0
 def testGrantAccessInsecureRedirectUriAllowed(self):
     """
     Test that grandAccess accepts a call with an insecure
     redirect uri if it is allowed.
     """
     dataKey = 'insecureRedirectUriDataKey' + self._RESPONSE_TYPE
     redirectUri = self._VALID_CLIENT.redirectUris[1]
     # noinspection HttpUrlsUsage
     self.assertTrue(redirectUri.startswith('http://'),
                     msg='The redirect uri is not insecure.')
     request = MockRequest('GET', 'some/path')
     data = {
         'response_type':
         self._RESPONSE_GRANT_TYPE_MAPPING[self._RESPONSE_TYPE],
         'redirect_uri':
         redirectUri,
         'client_id':
         self._VALID_CLIENT.id,
         'scope': ['All'],
         'state':
         b'state\xFF\xFF'
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     result = self._AUTH_RESOURCE.grantAccess(
         request, dataKey, allowInsecureRedirectUri=True)
     self.assertValidCodeResponse(
         request,
         result,
         data,
         msg=
         'Expected the auth resource to correctly handle a valid accepted '
         '{type} grant with an insecure redirect uri, '
         'if it is allowed.'.format(type=self._RESPONSE_TYPE))
Exemplo n.º 22
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.')
Exemplo n.º 23
0
 def testGrantAccessInvalidClientId(self):
     """ Test that grandAccess rejects a call with an invalid clientId. """
     dataKey = 'dataKeyInvalidClientId' + 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':
         'invalidClientId',
         'scope': ['All'],
         'state':
         state
     }
     self._PERSISTENT_STORAGE.put(dataKey, data)
     result = self._AUTH_RESOURCE.grantAccess(request, dataKey)
     self.assertFailedRequest(
         request,
         result,
         InvalidParameterError('client_id', state=state),
         redirectUri=redirectUri,
         msg='Expected grantAccess to reject an invalid client id.')
Exemplo n.º 24
0
    def test_handle_authorised_payment(self):
        request = MockRequest(AUTHORISED_PAYMENT_PARAMS_GET)
        success, status, details = Scaffold().handle_payment_feedback(request)

        assert success
        assert status == Scaffold.PAYMENT_STATUS_ACCEPTED
        assert details['amount'] == 13894
        assert details['ip_address'] == '127.0.0.1'
        assert details['method'] == 'adyen'
        assert details['psp_reference'] == '8814136447235922'
        assert details['status'] == 'AUTHORISED'

        # After calling `handle_payment_feedback` there is one authorised
        # transaction and no refused transaction in the database.
        assert AdyenTransaction.objects.filter(
            status='AUTHORISED').count() == 1
        assert AdyenTransaction.objects.filter(status='REFUSED').count() == 0

        # We delete the previously recorded AdyenTransaction.
        AdyenTransaction.objects.filter(status='AUTHORISED').delete()

        # We now test with POST instead of GET.
        request = MockRequest(AUTHORISED_PAYMENT_PARAMS_GET, method='POST')

        # This is going to fail because the mandatory fields are not the same
        # for GET and POST requests.
        with self.assertRaises(MissingFieldException):
            Scaffold().handle_payment_feedback(request)

        # So, let's try again with valid POST parameters.
        request = MockRequest(AUTHORISED_PAYMENT_PARAMS_POST, method='POST')
        success, status, details = Scaffold().handle_payment_feedback(request)

        assert success
        assert status == Scaffold.PAYMENT_STATUS_ACCEPTED
        assert details['amount'] == 21714
        assert details['ip_address'] == '127.0.0.1'
        assert details['method'] == 'adyen'
        assert details['psp_reference'] == '7914120802434172'
        assert details['status'] == 'AUTHORISED'

        # After calling `handle_payment_feedback` there is one authorised
        # transaction and no refused transaction in the database.
        assert AdyenTransaction.objects.filter(
            status='AUTHORISED').count() == 1
        assert AdyenTransaction.objects.filter(status='REFUSED').count() == 0
Exemplo n.º 25
0
 def testNoAccessToken(self):
     """ Test the rejection of a request to a protected resource without a token. """
     request = MockRequest('GET', 'protectedResource')
     self.assertFalse(
         isAuthorized(request, 'scope'),
         msg='Expected isAuthorized to reject a request without a token.')
     self.assertFailedProtectedResourceRequest(request,
                                               MissingTokenError(['scope']))
Exemplo n.º 26
0
 def testAuthorizationCodeGrant(self):
     """ Test the authorization code grant flow. """
     state = b'state'
     dataKey = self._doAuthorizationRequest(state)
     request = MockRequest('POST', 'oauth2', arguments={
         'confirm': 'yes',
         'data_key': dataKey
     })
     self._makeExampleRequest(request)
     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('code', parameter, msg='Missing code parameter in response.')
     self.assertIn('state', parameter, msg='Missing state parameter in response.')
     self.assertEqual(
         state if isinstance(state, str) else state.decode('utf-8', errors='replace'),
         parameter['state'], msg='Result contained an unexpected state.')
     code = parameter['code']
     request = Abstract.TokenResourceTest.generateValidTokenRequest(arguments={
         'grant_type': 'authorization_code',
         'code': code,
         'redirect_uri': self._VALID_CLIENT.redirectUris[0],
     }, url='oauth2/token', authentication=self._VALID_CLIENT)
     self._makeExampleRequest(request)
     self.assertEqual(200, request.responseCode,
                      msg='Expected the token resource to accept the request.')
     jsonResult = json.loads(request.getResponse().decode('utf-8'))
     self.assertIn('access_token', jsonResult, msg='Expected the result from the token resource '
                                                   'to contain an access_token parameter.')
     self.assertIn('refresh_token', jsonResult,
                   msg='Expected the result from the token resource '
                       'to contain a refresh_token parameter.')
     self.assertIn('scope', jsonResult,
                   msg='Expected the result from the token resource '
                       'to contain a scope parameter.')
     self.assertListEqual(jsonResult['scope'].split(), self._VALID_SCOPE,
                          msg='The token resource returned a different '
                              'scope than expected.')
     accessToken = jsonResult['access_token']
     self._testValidAccessRequest(token=accessToken)
     refreshToken = jsonResult['refresh_token']
     self._testTokenRefresh(refreshToken)
Exemplo n.º 27
0
 def testWithAccessTokenInQuery(self):
     """
     Test a request to a protected resource with a valid token in the request query.
     See https://tools.ietf.org/html/rfc6750#section-2.3
     """
     request = MockRequest(
         'GET', 'protectedResource?access_token=' + self.VALID_TOKEN)
     self.assertTrue(isAuthorized(request, self.VALID_TOKEN_SCOPE[0]),
                     msg='Expected isAuthorized to accept a request '
                     'with a valid token as a query parameter.')
     self.assertFalse(
         request.finished,
         msg='isAuthorized should not finish the request if it\'s valid.')
     self.assertIn(
         'private',
         request.getResponseHeader('Cache-Control'),
         msg=
         'The response to a request with the access token as a query parameter '
         'should contain a Cache-Control header with the "private" option.')
Exemplo n.º 28
0
 def testRequiresPostMethod(self):
     """ Test the rejection of any request that is not a POST request. """
     self.assertEquals(
         [b'POST'],
         self._TOKEN_RESOURCE.allowedMethods,
         msg='Expected the token resource to only accept POST requests.')
     methods = [
         name[7:] for name in dir(self._TOKEN_RESOURCE)
         if name.startswith('render_')
         and callable(getattr(self._TOKEN_RESOURCE, name))
     ]
     for method in methods:
         if method == 'POST':
             continue
         self.assertRaises(UnsupportedMethod, self._TOKEN_RESOURCE.render,
                           MockRequest(method, 'token'))
     try:
         self._TOKEN_RESOURCE.render(MockRequest('POST', 'token'))
     except UnsupportedMethod:
         self.fail('Expected the token resource to accept POST requests.')
Exemplo n.º 29
0
 def testInvalidContentType(self):
     """ Test the rejection requests whose content is not "x-www-form-urlencoded". """
     request = MockRequest('POST',
                           'token',
                           arguments={
                               'grant_type': 'refresh_token',
                               'refresh_token': self._VALID_REFRESH_TOKEN
                           })
     request.setRequestHeader('Content-Type',
                              'application/not-x-www-form-urlencoded')
     result = self._TOKEN_RESOURCE.render_POST(request)
     self.assertFailedTokenRequest(
         request,
         result,
         MalformedRequestError(
             'The Content-Type must be "application/x-www-form-urlencoded"'
         ),
         msg=
         'Expected the token resource to reject a request with an invalid content type.'
     )
Exemplo n.º 30
0
 def generateValidTokenRequest(url='token',
                               urlQuery='',
                               authentication=None,
                               **kwargs):
     """
     :param url: The request url.
     :param urlQuery: An optional query part of the request url.
     :param authentication: An optional client to use for header-authentication.
     :param kwargs: Optional arguments to the the request.
     :return: A valid request to the token resource.
     """
     if urlQuery:
         url = '?'.join((url, urlQuery))
     request = MockRequest('POST', url, **kwargs)
     request.setRequestHeader('Content-Type',
                              'application/x-www-form-urlencoded')
     if authentication is not None:
         AbstractTokenResourceTest._addAuthenticationToRequestHeader(
             request, authentication)
     return request