def test_invalid_id_token(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
        wireResponse = response['wireResponse']

        response_options = {'noIdToken': True}
        response = util.create_response(response_options)

        # break the id token
        idToken = wireResponse['id_token']
        idToken = idToken.replace('.', ' ')
        wireResponse['id_token'] = idToken
        authorityUrl = response['authority']
        upRequest = self.setup_expected_username_password_request_response(
            200, wireResponse, authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action
        token_response = context.acquire_token_with_username_password(
            response['resource'], cp['username'], cp['password'],
            cp['clientId'])

        #assert
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'],
                                         token_response),
            'Response did not match expected: ' + json.dumps(token_response))
    def test_happy_path_with_resource_adfs(self):
        # arrange
        # set up token refresh result
        wire_response = util.create_response({
            'refreshedRefresh': True,
            'mrrt': False
        })['wireResponse']
        new_resource = 'https://graph.local.azurestack.external/'
        tokenRequest = util.setup_expected_refresh_token_request_response(
            200, wire_response, cp['authority'], new_resource)

        # set up an existing token to be used for refreshing
        existing_token = util.create_response({
            'refreshedRefresh': True,
            'mrrt': True
        })['decodedResponse']
        existing_token['_clientId'] = existing_token.get(
            '_clientId') or cp['clientId']
        existing_token['isMRRT'] = existing_token.get('isMRRT') or True
        existing_token['_authority'] = existing_token.get(
            '_authority') or cp['authorizeUrl']
        token_cache = TokenCache(json.dumps([existing_token]))

        # act
        user_id = existing_token['userId']
        context = adal.AuthenticationContext(cp['authorityTenant'],
                                             cache=token_cache)
        token_response = context.acquire_token(new_resource, user_id,
                                               cp['clientId'])

        # assert
        tokens = [value for key, value in token_cache.read_items()]
        self.assertEqual(2, len(tokens))
        self.assertEqual({cp['resource'], new_resource},
                         set([x['resource'] for x in tokens]))
    def test_happy_path_with_resource_adfs(self):
        # arrange
        # set up token refresh result
        wire_response = util.create_response({ 
            'refreshedRefresh' : True,
            'mrrt': False
        })['wireResponse']
        new_resource = 'https://graph.local.azurestack.external/'
        tokenRequest = util.setup_expected_refresh_token_request_response(200, wire_response, cp['authority'], new_resource)

        # set up an existing token to be used for refreshing 
        existing_token = util.create_response({ 
            'refreshedRefresh': True,
            'mrrt': True
        })['decodedResponse']
        existing_token['_clientId'] = existing_token.get('_clientId') or cp['clientId']
        existing_token['isMRRT'] = existing_token.get('isMRRT') or True
        existing_token['_authority'] = existing_token.get('_authority') or cp['authorizeUrl']
        token_cache = TokenCache(json.dumps([existing_token]))

        # act
        user_id = existing_token['userId']
        context = adal.AuthenticationContext(cp['authorityTenant'], cache=token_cache)
        token_response = context.acquire_token(new_resource, user_id, cp['clientId'])

        # assert
        tokens = [value for key, value in token_cache.read_items()]
        self.assertEqual(2, len(tokens))
        self.assertEqual({cp['resource'], new_resource}, set([x['resource'] for x in tokens]))
    def test_federated_happy_path_and_correlation_id(self):
        correlationId = '12300002-0000-0000-c000-000000000000'
        util.set_correlation_id(correlationId)

        util.setup_expected_user_realm_response_common(True)
        util.setup_expected_mex_wstrust_request_common()

        response = util.create_response()
        assertion = self.setup_expected_oauth_assertion_request(response)

        logFunctionCalled = False
        def testCorrelationIdLog(level, message):
            logFunctionCalled = True
            self.assertIsNotNone(message)


        logOptions = {
            'level' : 3,
            'log' : testCorrelationIdLog
        }
        oldOptions = log.get_logging_options()
        log.set_logging_options(logOptions)

        authorityUrl = response['authority'] + '/' + cp['tenant']

        token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])
        self.assertTrue(util.isMatchTokenResponse(response['cachedResponse'], token_response), 'Response did not match expected: ' + JSON.stringify(token_response))
        log.set_logging_options(oldOptions)
        util.set_correlation_id()

        self.assertTrue(util.isMatchTokenResponse(response['cachedResponse'], token_response), 'The response did not match what was expected')
        self.assertTrue(logFunctionCalled, 'Logging was turned on but no messages were recieved.')
Esempio n. 5
0
    def test_federated_happy_path_and_correlation_id(self):
        util.setup_expected_user_realm_response_common(True)
        util.setup_expected_mex_wstrust_request_common()

        response = util.create_response()
        assertion = self.setup_expected_oauth_assertion_request(response)

        buffer = StringIO()
        handler = logging.StreamHandler(buffer)
        util.turn_on_logging(level='DEBUG', handler=handler)

        authorityUrl = response['authority']

        context = adal.AuthenticationContext(authorityUrl)
        correlation_id = '12300002-0000-0000-c000-000000000000'
        context.correlation_id = correlation_id

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response), 
                        'Response did not match expected: ' + json.dumps(token_response))
        
        #assert
        log_content = buffer.getvalue()
        self.assertTrue(correlation_id in log_content, 'Logging was turned on but no messages were recieved.')
    def test_federated_happy_path_and_correlation_id(self):
        util.setup_expected_user_realm_response_common(True)
        util.setup_expected_mex_wstrust_request_common()

        response = util.create_response()
        assertion = self.setup_expected_oauth_assertion_request(response)

        buffer = StringIO()
        handler = logging.StreamHandler(buffer)
        util.turn_on_logging(level='DEBUG', handler=handler)

        authorityUrl = response['authority']

        context = adal.AuthenticationContext(authorityUrl)
        correlation_id = '12300002-0000-0000-c000-000000000000'
        context.correlation_id = correlation_id

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response), 
                        'Response did not match expected: ' + json.dumps(token_response))
        
        #assert
        log_content = buffer.getvalue()
        self.assertTrue(correlation_id in log_content, 'Logging was turned on but no messages were recieved.')

        self.assertNotIn(cp['clientId'], log_content, "Should not log ClientID")
        self.assertNotIn(
            cp['username'].split('@')[0], log_content, "Should not contain PII")
Esempio n. 7
0
    def test_happy_path(self):
        response = util.create_response()
        self.setup_expected_auth_code_token_request_response(
            200, response['wireResponse'])

        context = adal.AuthenticationContext(cp['authUrl'])

        # action
        token_response = context.acquire_token_with_authorization_code(
            self.authorization_code, self.redirect_uri, response['resource'],
            cp['clientId'], cp['clientSecret'])

        # assert

        # the caching layer adds a few extra fields, let us pop them out for easier verification
        for k in ['_clientId', '_authority', 'resource']:
            token_response.pop(k, None)
        self.assertTrue(
            util.is_match_token_response(response['decodedResponse'],
                                         token_response),
            'The response did not match what was expected')

        # verify a request on the wire was made
        req = httpretty.last_request()
        util.match_standard_request_headers(req)

        # verify the same token entry was cached
        cached_items = list(context.cache.read_items())
        self.assertTrue(len(cached_items) == 1)
        _, cached_entry = cached_items[0]
        self.assertEqual(cached_entry, token_response)
    def test_federated_wstrust_unknown_token_type(self):
        context = self.create_authentication_context_stub(
            cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', None,
                                                cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(
            None, 'urn:oasis:names:tc:SAML:100.0:assertion', True)

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(
            cp['authority'], response['decodedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context,
                                    response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex,
                                                 wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(
                cp['username'], cp['password'])
            self.fail(receivedException, 'Did not receive expected error')
        except Exception as exp:
            #assert
            self.assertEqual(
                'Unsuccessful RSTR.\n\terror code: None\n\tfaultMessage: None',
                exp.args[0])
    def test_federated_failed_wstrust(self):
        context = self.create_authentication_context_stub(
            cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', None,
                                                cp['adfsWsTrust'])
        mock_err_msg = 'Network not available'
        wstrustRequest = self.create_wstrust_request_stub(
            Exception(mock_err_msg), 'urn:oasis:names:tc:SAML:1.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(
            cp['authority'], response['cachedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context,
                                    response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex,
                                                 wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(
                cp['username'], cp['password'])
            self.fail('Did not receive expected error')
        except Exception as exp:
            #assert
            self.assertEqual(mock_err_msg, exp.args[0])
    def test_federated_unknown_token_type(self):
        context = self.create_authentication_context_stub(
            cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated',
                                                cp['adfsMex'],
                                                cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(
            None, 'urn:oasis:names:tc:SAML:100.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(
            cp['authority'], response['decodedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context,
                                    response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex,
                                                 wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(
                cp['username'], cp['password'])
            self.assertTrue(receivedException,
                            'Did not receive expected error')
        except Exception as err:
            #assert
            self.assertTrue(
                'token type' in err.args[0],
                "Error message did not contain 'token type'. message:{}".
                format(err.args[0]))
    def test_federated_saml2(self):
        context = self.create_authentication_context_stub(
            cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated',
                                                cp['adfsMex'],
                                                cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(
            None, 'urn:oasis:names:tc:SAML:2.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(
            cp['authority'], response['cachedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context,
                                    response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex,
                                                 wstrustRequest, oauthClient)

        #action
        token_response = tokenRequest.get_token_with_username_password(
            cp['username'], cp['password'])

        #assert
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'],
                                         token_response),
            'The response did not match what was expected')
    def test_managed_happy_path(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        authorityUrl = response['authority'] + '/' + cp['tenant']
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])
        self.assertTrue(util.isMatchTokenResponse(response['cachedResponse'], token_response), 'Response did not match expected: ' + JSON.stringify(token_response))
    def test_happy_path(self):
        response = util.create_response()

        self.setup_expected_auth_code_token_request_response(200, response['wireResponse'])

        token_response = adal._acquire_token_with_authorization_code(cp['authUrl'], cp['clientId'], cp['clientSecret'], self.authorization_code, self.redirect_uri, response['resource'])

        self.assertTrue(util.is_match_token_response(response['decodedResponse'], token_response), 'The response did not match what was expected')

        req = httpretty.last_request()
        util.match_standard_request_headers(req)
    def test_no_access_token(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        del response['wireResponse']['access_token']

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority'] + '/' + cp['tenant']
        # Did not receive expected error about missing token_type
        with self.assertRaises(Exception):
            token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])
    def test_bad_int_in_response(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        response['wireResponse']['expires_in'] = 'foo'

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority'] + '/' + cp['tenant']

        # Did not receive expected error about bad int parameter
        with self.assertRaises(Exception):
            token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])
    def test_happy_path(self):
        response_options = { 'noRefresh' : True, 'tokenEndpoint': True }
        response = util.create_response(response_options)
        token_request = util.setup_expected_client_cred_token_request_response(200, response['wireResponse'])

        context = adal.AuthenticationContext(cp['authUrl'])
        token_response = context.acquire_token_with_client_credentials(
             response['resource'], cp['clientId'], cp['clientSecret'])
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )
    def test_happy_path(self):
        response_options = {"noRefresh": True}
        response = util.create_response(response_options)
        token_request = util.setup_expected_client_cred_token_request_response(200, response["wireResponse"])

        token_response = adal.acquire_token_with_client_credentials(
            cp["authUrl"], cp["clientId"], cp["clientSecret"], response["resource"]
        )
        self.assertTrue(
            util.is_match_token_response(response["cachedResponse"], token_response),
            "The response does not match what was expected.: " + str(token_response),
        )
    def test_invalid_id_token(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
        wireResponse = response['wireResponse']

        response_options = { 'noIdToken' : True }
        response = util.create_response(response_options)

        # break the id token
        idToken = wireResponse['id_token']
        idToken = idToken.replace('.', ' ')
        wireResponse['id_token'] = idToken
        authorityUrl = response['authority']
        upRequest = self.setup_expected_username_password_request_response(200, wireResponse, authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])

        #assert
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response), 'Response did not match expected: ' + json.dumps(token_response))
    def test_cert_happy_path(self):
        ''' TODO: Test Failing as of 2015/06/03 and needs to be completed. '''
        self.fail("Not Yet Impelemented.  Add Helper Functions and setup method")
        saveProto = updateSelfSignedJwtStubs()

        responseOptions = { noRefresh : true }
        response = util.create_response(responseOptions)
        tokenRequest = util.setupExpectedClientAssertionTokenRequestResponse(200, response.wireResponse, cp['authorityTenant'])
        context = adal.AuthenticationContext(cp['authorityTenant'])

        context.acquire_token_with_client_certificate(response.resource, cp['clientId'], cp['cert'], cp['certHash'])

        resetSelfSignedJwtStubs(saveProto)
        self.assertTrue(util.is_match_token_response(response.cachedResponse, token_response), 'The response did not match what was expected')
    def test_happy_path_adfs_authority(self):
        adfsAuthority = 'https://contoso.com/adfs'
        responseOptions = { 'authority' : adfsAuthority,  'mrrt' : True }
        response = util.create_response(responseOptions)
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], adfsAuthority, True)

        context = adal.AuthenticationContext(adfsAuthority, False)

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])

        #assert
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response),
               'Response did not match expected: ' + json.dumps(token_response))
Esempio n. 21
0
    def test_happy_path_adfs_authority(self):
        adfsAuthority = 'https://contoso.com/adfs'
        responseOptions = { 'authority' : adfsAuthority,  'mrrt' : True }
        response = util.create_response(responseOptions)
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], adfsAuthority, True)

        context = adal.AuthenticationContext(adfsAuthority, False)

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])

        #assert
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response),
               'Response did not match expected: ' + json.dumps(token_response))
    def test_happy_path(self):
        response_options = {'noRefresh': True, 'tokenEndpoint': True}
        response = util.create_response(response_options)
        token_request = util.setup_expected_client_cred_token_request_response(
            200, response['wireResponse'])

        context = adal.AuthenticationContext(cp['authUrl'])
        token_response = context.acquire_token_with_client_credentials(
            response['resource'], cp['clientId'], cp['clientSecret'])
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'],
                                         token_response),
            'The response does not match what was expected.: ' +
            str(token_response))
    def test_managed_happy_path(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        authorityUrl = response['authority']
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'],
                                                                      cp['password'], cp['clientId'])

        #assert
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response),
                        'Response did not match expected: ' + json.dumps(token_response))
Esempio n. 24
0
    def test_no_access_token(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
        del response['wireResponse']['access_token']

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority']
        context = adal.AuthenticationContext(authorityUrl)

        #action
        try:
            token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
            self.fail('Did not receive expected error about missing token_type')
        except Exception as exp:
            #assert
            self.assertEqual('wire_response is missing access_token', exp.args[0])
    def test_no_access_token(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
        del response['wireResponse']['access_token']

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority']
        context = adal.AuthenticationContext(authorityUrl)

        #action
        try:
            token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
            self.fail('Did not receive expected error about missing token_type')
        except Exception as exp:
            #assert
            self.assertEqual('wire_response is missing access_token', exp.args[0])
Esempio n. 26
0
    def test_managed_happy_path(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        authorityUrl = response['authority']
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action
        token_response = context.acquire_token_with_username_password(response['resource'], cp['username'],
                                                                      cp['password'], cp['clientId'])

        #assert
        self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response),
                        'Response did not match expected: ' + json.dumps(token_response))
Esempio n. 27
0
    def test_happy_path(self):
        response = util.create_response()

        self.setup_expected_auth_code_token_request_response(
            200, response['wireResponse'])

        token_response = adal._acquire_token_with_authorization_code(
            cp['authUrl'], cp['clientId'], cp['clientSecret'],
            self.authorization_code, self.redirect_uri, response['resource'])

        self.assertTrue(
            util.is_match_token_response(response['decodedResponse'],
                                         token_response),
            'The response did not match what was expected')

        req = httpretty.last_request()
        util.match_standard_request_headers(req)
Esempio n. 28
0
    def performStaticInstanceDiscovery(self, authorityHost, callback):
        hardCodedAuthority = 'https://' + authorityHost + '/' + cp['tenant']

        responseOptions = {
            'authority' : hardCodedAuthority
        }
        response = util.create_response(responseOptions)
        wireResponse = response['wireResponse']
        tokenRequest = util.setup_expected_client_cred_token_request_response(200, wireResponse, hardCodedAuthority)

        token_response = adal.acquire_token_with_client_credentials(
            hardCodedAuthority, cp['clientId'], cp['clientSecret'], response['resource'])

        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )
    def test_federated_user_realm_returns_no_mex_endpoint_wstrust2005(self):
         context = self.create_authentication_context_stub(cp['authorityTenant'])
         mex = self.create_mex_stub(cp['adfsWsTrust2005'])
         userRealm = self.create_user_realm_stub('wstrust', 'federated', None, cp['adfsWsTrust2005'])
         wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:1.0:assertion')

         response = util.create_response()
         oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

         tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
         self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient);

         #action
         token_response = tokenRequest.get_token_with_username_password(cp['username'], cp['password'])

         #assert
         self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response), 'The response did not match what was expected')
    def test_happy_path_with_resource_client_secret(self):
        response_options = { 'refreshedRefresh' : True }
        response = util.create_response(response_options)
        wire_response = response['wireResponse']
        tokenRequest = util.setup_expected_refresh_token_request_response(200, wire_response, response['authority'], response['resource'], cp['clientSecret'])

        context = adal.AuthenticationContext(cp['authorityTenant'])
        def side_effect (tokenfunc):
            return response['decodedResponse']

        context._acquire_token = mock.MagicMock(side_effect=side_effect)

        token_response = context.acquire_token_with_refresh_token(cp['refreshToken'], cp['clientId'], cp['clientSecret'], cp['resource'])
        self.assertTrue(
            util.is_match_token_response(response['decodedResponse'], token_response),
            'The response did not match what was expected: ' + str(token_response)
        )
    def performStaticInstanceDiscovery(self, authorityHost):
        hardCodedAuthority = "https://" + authorityHost + "/" + cp["tenant"]

        responseOptions = {"authority": hardCodedAuthority}
        response = util.create_response(responseOptions)
        wireResponse = response["wireResponse"]
        tokenRequest = util.setup_expected_client_cred_token_request_response(200, wireResponse, hardCodedAuthority)

        context = adal.AuthenticationContext(hardCodedAuthority)
        token_response = context.acquire_token_with_client_credentials(
            response["resource"], cp["clientId"], cp["clientSecret"]
        )

        self.assertTrue(
            util.is_match_token_response(response["cachedResponse"], token_response),
            "The response does not match what was expected.: " + str(token_response),
        )
Esempio n. 32
0
    def test_bad_int_in_response(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        response['wireResponse']['expires_in'] = 'foo'

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority']
        context = adal.AuthenticationContext(authorityUrl)

        #action
        try:
            token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
            self.fail('Did not see expected warning message about bad expires_in field')
        except Exception as exp:
            #assert
            self.assertEqual("invalid literal for int() with base 10: 'foo'", exp.args[0])
    def test_bad_int_in_response(self):
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        response['wireResponse']['expires_in'] = 'foo'

        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], response['authority'])
        authorityUrl = response['authority']
        context = adal.AuthenticationContext(authorityUrl)

        #action
        try:
            token_response = context.acquire_token_with_username_password(response['resource'], cp['username'], cp['password'], cp['clientId'])
            self.fail('Did not see expected warning message about bad expires_in field')
        except Exception as exp:
            #assert
            self.assertEqual("invalid literal for int() with base 10: 'foo'", exp.args[0])
    def test_federated_wstrust_unknown_token_type(self):
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', None, cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:100.0:assertion', True)

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

        #util.turnOnLogging()
        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        def callback(err, token_response):
            self.assertTrue(err, 'Did not receive expected error')

        tokenRequest._get_token_with_username_password('username', 'password', callback)
    def test_federated_failed_mex(self):
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'], Exception('mex failed'))
        userRealm = self.create_user_realm_stub('wstrust', 'federated', cp['adfsMex'], cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:1.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        def callback(err, token_response):
            if not err:
                self.assertTrue(util.is_match_token_response(response['cachedResponse'], token_response), 'The response did not match what was expected')

        tokenRequest._get_token_with_username_password('username', 'password', callback)
    def test_bad_id_token_base64_in_response(self):
        foundWarning = False
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()

        def findIdTokenWarning(level, message):
            if 'decoded' in message:
                foundWarning = True
        util.turn_on_logging() #, findIdTokenWarning)
        #util.turnOnLogging(None, findIdTokenWarning)

        response['wireResponse']['id_token'] = 'aaaaaaa./+===.aaaaaa'
        authorityUrl = response['authority'] + '/' + cp['tenant']
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])

        self.assertTrue(foundWarning, 'Did not see expected warning message about bad id_token base64.')
    def test_invalid_id_token(self):
        ''' TODO: Test Failing as of 2015/06/03 and needs to be completed. '''
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
        wireResponse = response['wireResponse']

        response_options = { 'noIdToken' : True }
        #response = util.create_response(response_options)

        # break the id token
        #idToken = wireResponse['id_token']
        #idToken = idToken.replace('.', ' ')
        #wireResponse['id_token'] = idToken
        authorityUrl = response['authority'] + '/' + cp['tenant']
        upRequest = self.setup_expected_username_password_request_response(200, wireResponse, authorityUrl)

        token_response = adal.acquire_token_with_username_password(authorityUrl, cp['username'], cp['password'], cp['clientId'], response['resource'])
        self.assertTrue(util.isMatchTokenResponse(response['cachedResponse'], token_response), 'Response did not match expected: ' + JSON.stringify(token_response))
Esempio n. 38
0
    def test_bad_id_token_base64_in_response(self):
        foundWarning = False
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
      
        log_content = StringIO()
        handler = logging.StreamHandler(log_content)
        util.turn_on_logging(level='WARNING', handler=handler)

        response['wireResponse']['id_token'] = 'aaaaaaa./+===.aaaaaa'
        expected_warn = 'The returned id_token could not be decoded: aaaaaaa./+===.aaaaaa'
        authorityUrl = response['authority'] 
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action and verify
        self.assertRaises(UnicodeDecodeError, context.acquire_token_with_username_password, response['resource'], cp['username'], cp['password'], cp['clientId'])
    def test_bad_id_token_base64_in_response(self):
        foundWarning = False
        util.setup_expected_user_realm_response_common(False)
        response = util.create_response()
      
        log_content = StringIO()
        handler = logging.StreamHandler(log_content)
        util.turn_on_logging(level='WARNING', handler=handler)

        response['wireResponse']['id_token'] = 'aaaaaaa./+===.aaaaaa'
        expected_warn = 'The returned id_token could not be decoded: aaaaaaa./+===.aaaaaa'
        authorityUrl = response['authority'] 
        upRequest = self.setup_expected_username_password_request_response(200, response['wireResponse'], authorityUrl)

        context = adal.AuthenticationContext(authorityUrl)

        #action and verify
        self.assertRaises(UnicodeDecodeError, context.acquire_token_with_username_password, response['resource'], cp['username'], cp['password'], cp['clientId'])
    def test_federated_unknown_token_type(self):
        ''' TODO: Test Failing as of 2015/06/03 and needs to be completed. '''
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', cp['adfsMex'], cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:100.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

        #util.turnOnLogging()
        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        def callback(err, token_response):
            self.assertTrue(err, 'Did not receive expected err.')
            self.assertTrue('tokenType' in  err.args[0], "Error message did not contain 'token type'. message:{}".format(err.args[0]))

        tokenRequest._get_token_with_username_password('username', 'password', callback)
    def test_federated_wstrust_unknown_token_type(self):
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', None, cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:100.0:assertion', True)

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(cp['username'], cp['password'])
            self.fail(receivedException, 'Did not receive expected error')
        except Exception as exp:
            #assert
            self.assertEqual('Unsuccessful RSTR.\n\terror code: None\n\tfaultMessage: None', exp.args[0])
    def test_federated_unknown_token_type(self):
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', cp['adfsMex'], cp['adfsWsTrust'])
        wstrustRequest = self.create_wstrust_request_stub(None, 'urn:oasis:names:tc:SAML:100.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['decodedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(cp['username'], cp['password'])
            self.assertTrue(receivedException, 'Did not receive expected error')
        except Exception as err:
            #assert
            self.assertTrue('token type' in err.args[0], "Error message did not contain 'token type'. message:{}".format(err.args[0]))
Esempio n. 43
0
    def test_success_dynamic_instance_discovery(self):
        instanceDiscoveryRequest = util.setup_expected_instance_discovery_request(
            200,
            cp['authorityHosts']['global'],
            {'tenant_discovery_endpoint' : 'http://foobar'},
            self.nonHardCodedAuthorizeEndpoint
        )

        responseOptions = { 'authority' : self.nonHardCodedAuthority}
        response = util.create_response(responseOptions)
        wireResponse = response['wireResponse']

        util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)

        token_response = adal.acquire_token_with_client_credentials(
            self.nonHardCodedAuthority, cp['clientId'], cp['clientSecret'], response['resource'])
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )
    def test_federated_failed_wstrust(self):
        context = self.create_authentication_context_stub(cp['authorityTenant'])
        mex = self.create_mex_stub(cp['adfsWsTrust'])
        userRealm = self.create_user_realm_stub('wstrust', 'federated', None, cp['adfsWsTrust'])
        mock_err_msg = 'Network not available'
        wstrustRequest = self.create_wstrust_request_stub(Exception(mock_err_msg), 'urn:oasis:names:tc:SAML:1.0:assertion')

        response = util.create_response()
        oauthClient = self.create_oauth2_client_stub(cp['authority'], response['cachedResponse'], None)

        tokenRequest = TokenRequest(cp['callContext'], context, response['clientId'], response['resource'])
        self.stub_out_token_request_dependencies(tokenRequest, userRealm, mex, wstrustRequest, oauthClient)

        #action
        try:
            tokenRequest.get_token_with_username_password(cp['username'], cp['password'])
            self.fail('Did not receive expected error')
        except Exception as exp:
            #assert
            self.assertEqual(mock_err_msg, exp.args[0])
Esempio n. 45
0
    def test_cert_happy_path(self):
        ''' TODO: Test Failing as of 2015/06/03 and needs to be completed. '''
        self.fail(
            "Not Yet Impelemented.  Add Helper Functions and setup method")
        saveProto = updateSelfSignedJwtStubs()

        responseOptions = {noRefresh: true}
        response = util.create_response(responseOptions)
        tokenRequest = util.setupExpectedClientAssertionTokenRequestResponse(
            200, response.wireResponse, cp['authorityTenant'])

        adal._acquire_token_with_client_certificate(cp['authorityTenant'],
                                                    cp['clientId'], cp['cert'],
                                                    cp['certHash'],
                                                    response.resource)

        resetSelfSignedJwtStubs(saveProto)
        self.assertTrue(
            util.is_match_token_response(response.cachedResponse,
                                         token_response),
            'The response did not match what was expected')
    def test_success_dynamic_instance_discovery(self):
        instanceDiscoveryRequest = util.setup_expected_instance_discovery_request(
            200,
            cp["authorityHosts"]["global"],
            {"tenant_discovery_endpoint": "http://foobar"},
            self.nonHardCodedAuthorizeEndpoint,
        )

        responseOptions = {"authority": self.nonHardCodedAuthority}
        response = util.create_response(responseOptions)
        wireResponse = response["wireResponse"]

        util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)

        context = adal.AuthenticationContext(self.nonHardCodedAuthority)
        token_response = context.acquire_token_with_client_credentials(
            response["resource"], cp["clientId"], cp["clientSecret"]
        )
        self.assertTrue(
            util.is_match_token_response(response["cachedResponse"], token_response),
            "The response does not match what was expected.: " + str(token_response),
        )
    def test_happy_path_with_resource_client_secret(self):
        response_options = {'refreshedRefresh': True}
        response = util.create_response(response_options)
        wire_response = response['wireResponse']
        tokenRequest = util.setup_expected_refresh_token_request_response(
            200, wire_response, response['authority'], response['resource'],
            cp['clientSecret'])

        context = adal.AuthenticationContext(cp['authorityTenant'])

        def side_effect(tokenfunc):
            return response['decodedResponse']

        context._acquire_token = mock.MagicMock(side_effect=side_effect)

        token_response = context.acquire_token_with_refresh_token(
            cp['refreshToken'], cp['clientId'], cp['clientSecret'],
            cp['resource'])
        self.assertTrue(
            util.is_match_token_response(response['decodedResponse'],
                                         token_response),
            'The response did not match what was expected: ' +
            str(token_response))
 def setUp(self):
     self.response_options = {'refreshedRefresh': True}
     self.response = util.create_response(self.response_options)
     self.wire_response = self.response['wireResponse']