class IDSiteCallbackTest(IDSiteBuildURITest):

    def setUp(self):
        super(IDSiteCallbackTest, self).setUp()
        self.store = MagicMock()
        self.store.get_resource.return_value = {'href': 'acchref', 'sp_http_status': 200}
        self.store._cache_get.return_value = False # ignore nonce

        self.client.data_store = self.store

        self.app = Application(
                client=self.client,
                properties={'href': 'apphref', 'accounts': {'href': 'acchref'}})

        self.acc = MagicMock(href='acchref')
        now = datetime.datetime.utcnow()

        try:
            irt = uuid4().get_hex()
        except AttributeError:
            irt = uuid4().hex

        fake_jwt_data = {
                'exp': now + datetime.timedelta(seconds=3600),
                'aud': self.app._client.auth.id,
                'irt': irt,
                'iss': 'Stormpath',
                'sub': self.acc.href,
                'isNewSub': False,
                'state': None,
        }

        self.fake_jwt = to_unicode(jwt.encode(
            fake_jwt_data,
            self.app._client.auth.secret,
            'HS256'), 'UTF-8')

    def test_id_site_callback_handler(self):
        fake_jwt_response = 'http://localhost/?jwtResponse=%s' % self.fake_jwt
        ret = self.app.handle_id_site_callback(fake_jwt_response)
        self.assertIsNotNone(ret)
        self.assertEqual(ret.account.href, self.acc.href)
        self.assertIsNone(ret.state)

    def test_id_site_callback_handler_jwt_already_used(self):
        self.store._cache_get.return_value = True # Fake Nonce already used

        fake_jwt_response = 'http://localhost/?jwtResponse=%s' % self.fake_jwt
        self.assertRaises(ValueError, self.app.handle_id_site_callback, fake_jwt_response)

    def test_id_site_callback_handler_invalid_jwt(self):
        fake_jwt_response = 'http://localhost/?jwtResponse=%s' % 'INVALID_JWT'
        ret = self.app.handle_id_site_callback(fake_jwt_response)
        self.assertIsNone(ret)

    def test_id_site_callback_handler_invalid_url_response(self):
        fake_jwt_response = 'invalid_url_response'
        ret = self.app.handle_id_site_callback(fake_jwt_response)
        self.assertIsNone(ret)
Example #2
0
    def setUp(self):
        super(IDSiteCallbackTest, self).setUp()
        self.store = MagicMock()
        self.store.get_resource.return_value = {
            'href':
            'acchref',
            'sp_http_status':
            200,
            'applications':
            ApplicationList(client=self.client,
                            properties={
                                'href': 'apps',
                                'items': [{
                                    'href': 'apphref'
                                }],
                                'offset': 0,
                                'limit': 25
                            })
        }
        self.store._cache_get.return_value = False  # ignore nonce

        self.client.data_store = self.store

        self.app = Application(client=self.client,
                               properties={
                                   'href': 'apphref',
                                   'accounts': {
                                       'href': 'acchref'
                                   }
                               })

        self.acc = MagicMock(href='acchref')
        now = datetime.datetime.utcnow()

        try:
            irt = uuid4().get_hex()
        except AttributeError:
            irt = uuid4().hex

        fake_jwt_data = {
            'exp': now + datetime.timedelta(seconds=3600),
            'aud': self.app._client.auth.id,
            'irt': irt,
            'iss': 'Stormpath',
            'sub': self.acc.href,
            'isNewSub': False,
            'state': None,
        }

        self.fake_jwt = to_unicode(
            jwt.encode(fake_jwt_data, self.app._client.auth.secret, 'HS256'),
            'UTF-8')
    def test_cache_opts_with_different_cache_stores(self):
        cache_opts = {
            'regions': {
                'customData': {
                    'store': NullCacheStore,
                }
            }
        }

        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        scheme=self.AUTH_SCHEME,
                        cache_options=cache_opts)

        app_name = self.get_random_name()
        app = client.applications.create({
            'name': app_name,
            'description': 'test app',
            'custom_data': {
                'a': 1
            }
        })
        href = app.href

        # this will cache application
        self.assertEqual(Application(client, href=href).name, app_name)

        # pretend that app name is changed elsewhere
        properties = app._get_properties()
        properties['name'] = 'changed %s' % app_name
        client.data_store.executor.post(app.href, properties)

        # we get stale, cached app name
        self.assertEqual(Application(client, href=href).name, app_name)

        # unless we refresh
        app.refresh()
        self.assertEqual(
            Application(client, href=href).name, properties['name'])

        # this will not cache custom data
        self.assertEqual(Application(client, href=href).custom_data['a'], 1)

        # pretend that app's custom data is changed elsewhere
        properties = app.custom_data._get_properties()
        properties['a'] = 2
        client.data_store.executor.post(app.custom_data.href, properties)

        # we get fresh custom data
        self.assertEqual(Application(client, href=href).custom_data['a'], 2)

        app.delete()
Example #4
0
    def test_building_saml_redirect_uri(self):
        try:
            from urlparse import urlparse
        except ImportError:
            from urllib.parse import urlparse

        app = Application(client=self.client, properties={'href': 'apphref'})

        ret = app.build_saml_idp_redirect_url('http://localhost/',
                                              'apphref/saml/sso/idpRedirect')
        try:
            jwt_response = urlparse(ret).query.split('=')[1]
        except:
            self.fail("Failed to parse ID site redirect uri")

        try:
            decoded_data = jwt.decode(jwt_response,
                                      verify=False,
                                      algorithms=['HS256'])
        except jwt.DecodeError:
            self.fail("Invaid JWT generated.")

        self.assertIsNotNone(decoded_data.get('iat'))
        self.assertIsNotNone(decoded_data.get('jti'))
        self.assertIsNotNone(decoded_data.get('iss'))
        self.assertIsNotNone(decoded_data.get('sub'))
        self.assertIsNotNone(decoded_data.get('cb_uri'))
        self.assertEqual(decoded_data.get('cb_uri'), 'http://localhost/')
        self.assertIsNone(decoded_data.get('path'))
        self.assertIsNone(decoded_data.get('state'))

        ret = app.build_saml_idp_redirect_url('http://testserver/',
                                              'apphref/saml/sso/idpRedirect',
                                              path='/#/register',
                                              state='test')
        try:
            jwt_response = urlparse(ret).query.split('=')[1]
        except:
            self.fail("Failed to parse SAML redirect uri")

        try:
            decoded_data = jwt.decode(jwt_response,
                                      verify=False,
                                      algorithms=['HS256'])
        except jwt.DecodeError:
            self.fail("Invaid JWT generated.")

        self.assertEqual(decoded_data.get('path'), '/#/register')
        self.assertEqual(decoded_data.get('state'), 'test')
    def test_building_saml_redirect_uri(self):
        try:
            from urlparse import urlparse
        except ImportError:
            from urllib.parse import urlparse

        app = Application(client=self.client, properties={'href': 'apphref'})

        ret = app.build_saml_idp_redirect_url(
            'http://localhost/', 'apphref/saml/sso/idpRedirect')
        try:
            jwt_response = urlparse(ret).query.split('=')[1]
        except:
            self.fail("Failed to parse ID site redirect uri")

        try:
            decoded_data = jwt.decode(
                jwt_response, verify=False, algorithms=['HS256'])
        except jwt.DecodeError:
            self.fail("Invaid JWT generated.")

        self.assertIsNotNone(decoded_data.get('iat'))
        self.assertIsNotNone(decoded_data.get('jti'))
        self.assertIsNotNone(decoded_data.get('iss'))
        self.assertIsNotNone(decoded_data.get('sub'))
        self.assertIsNotNone(decoded_data.get('cb_uri'))
        self.assertEqual(decoded_data.get('cb_uri'), 'http://localhost/')
        self.assertIsNone(decoded_data.get('path'))
        self.assertIsNone(decoded_data.get('state'))

        ret = app.build_saml_idp_redirect_url(
                'http://testserver/',
                'apphref/saml/sso/idpRedirect',
                path='/#/register',
                state='test')
        try:
            jwt_response = urlparse(ret).query.split('=')[1]
        except:
            self.fail("Failed to parse SAML redirect uri")

        try:
            decoded_data = jwt.decode(
                jwt_response, verify=False, algorithms=['HS256'])
        except jwt.DecodeError:
            self.fail("Invaid JWT generated.")

        self.assertEqual(decoded_data.get('path'), '/#/register')
        self.assertEqual(decoded_data.get('state'), 'test')
    def setUp(self):
        super(IDSiteCallbackTest, self).setUp()
        self.store = MagicMock()
        self.store.get_resource.return_value = {'href': 'acchref', 'sp_http_status': 200}
        self.store._cache_get.return_value = False # ignore nonce

        self.client.data_store = self.store

        self.app = Application(
                client=self.client,
                properties={'href': 'apphref', 'accounts': {'href': 'acchref'}})

        self.acc = MagicMock(href='acchref')
        now = datetime.datetime.utcnow()

        try:
            irt = uuid4().get_hex()
        except AttributeError:
            irt = uuid4().hex

        fake_jwt_data = {
                'exp': now + datetime.timedelta(seconds=3600),
                'aud': self.app._client.auth.id,
                'irt': irt,
                'iss': 'Stormpath',
                'sub': self.acc.href,
                'isNewSub': False,
                'state': None,
        }

        self.fake_jwt = to_unicode(jwt.encode(
            fake_jwt_data,
            self.app._client.auth.secret,
            'HS256'), 'UTF-8')
Example #7
0
    def test_resend(self):
        ds = MagicMock()
        ds.create_resource.return_value = {}
        client = MagicMock(data_store=ds, BASE_URL='http://example.com/')

        acc = Account(client=client,
                      properties={
                          'href': 'test/app',
                          'email': '*****@*****.**'
                      })
        vel = VerificationEmailList(client=client, href='test/emails')
        app = Application(client=client,
                          properties={
                              'href': 'test/app',
                              'verification_emails': vel
                          })
        dir = Directory(client=client, href='test/directory')

        app.verification_emails.resend(acc, dir)

        ds.create_resource.assert_called_once_with(
            'http://example.com/test/emails', {
                'login': '******',
                'account_store': 'test/directory'
            })
class SamlCallbackTest(SamlBuildURITest):

    def setUp(self):
        super(SamlCallbackTest, self).setUp()
        self.store = MagicMock()
        self.store.get_resource.return_value = {
            'href': 'acchref',
            'sp_http_status': 200,
            'applications': ApplicationList(
                client=self.client,
                properties={
                    'href': 'apps',
                    'items': [{'href': 'apphref'}],
                    'offset': 0,
                    'limit': 25
                })
        }
        self.store._cache_get.return_value = False # ignore nonce

        self.client.data_store = self.store

        self.app = Application(
                client=self.client,
                properties={'href': 'apphref', 'accounts': {'href': 'acchref'}})

        self.acc = MagicMock(href='acchref')
        now = datetime.datetime.utcnow()

        try:
            irt = uuid4().get_hex()
        except AttributeError:
            irt = uuid4().hex

        fake_jwt_data = {
                'exp': now + datetime.timedelta(seconds=3600),
                'aud': self.app._client.auth.id,
                'irt': irt,
                'iss': 'Stormpath',
                'sub': self.acc.href,
                'isNewSub': False,
                'state': None,
        }

        self.fake_jwt = to_unicode(jwt.encode(
            fake_jwt_data,
            self.app._client.auth.secret,
            'HS256'), 'UTF-8')

    def test_saml_callback_handler(self):
        fake_jwt_response = 'http://localhost/?jwtResponse=%s' % self.fake_jwt

        with patch.object(Application, 'has_account') as mock_has_account:
            mock_has_account.return_value = True
            ret = self.app.handle_stormpath_callback(fake_jwt_response)

        self.assertIsNotNone(ret)
        self.assertIsInstance(ret, StormpathCallbackResult)
        self.assertEqual(ret.account.href, self.acc.href)
        self.assertIsNone(ret.state)
    def test_app_get_provider_acc_does_create_w_provider_data(self):
        ds = MagicMock()
        ds.get_resource.return_value = {}
        client = MagicMock(data_store=ds, BASE_URL='http://example.com')

        app = Application(client=client, properties={
            'href': 'test/app',
            'accounts': {'href': '/test/app/accounts'}
        })

        app.get_provider_account('myprovider', access_token='foo')

        ds.create_resource.assert_called_once_with(
            'http://example.com/test/app/accounts', {
                'providerData': {
                    'providerId': 'myprovider',
                    'accessToken': 'foo'
                }
            }, params={})
    def test_app_get_provider_acc_does_create_w_provider_data(self):
        ds = MagicMock()
        ds.get_resource.return_value = {}
        client = MagicMock(data_store=ds, BASE_URL='http://example.com')

        app = Application(client=client, properties={
            'href': 'test/app',
            'accounts': {'href': '/test/app/accounts'}
        })

        app.get_provider_account('myprovider', access_token='foo')

        ds.create_resource.assert_called_once_with(
            'http://example.com/test/app/accounts', {
                'providerData': {
                    'providerId': 'myprovider',
                    'accessToken': 'foo'
                }
            }, params={})
    def test_building_id_site_redirect_uri(self):

        app = Application(client=self.client, properties={'href': 'apphref'})
        ret = app.build_id_site_redirect_url('http://localhost/')
        decoded_data = self.decode_jwt(ret)
        self.assertIsNotNone(decoded_data.get('iat'))
        self.assertIsNotNone(decoded_data.get('jti'))
        self.assertIsNotNone(decoded_data.get('iss'))
        self.assertIsNotNone(decoded_data.get('sub'))
        self.assertIsNotNone(decoded_data.get('cb_uri'))
        self.assertEqual(decoded_data.get('cb_uri'), 'http://localhost/')
        self.assertIsNone(decoded_data.get('path'))
        self.assertIsNone(decoded_data.get('state'))
        self.assertNotEqual(decoded_data.get('sof'), True)
        self.assertIsNone(decoded_data.get('onk'))
        self.assertIsNone(decoded_data.get('sp_token'))

        ret = app.build_id_site_redirect_url(
                'http://testserver/',
                path='/#/register',
                state='test')
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data.get('path'), '/#/register')
        self.assertEqual(decoded_data.get('state'), 'test')

        sp_token = '{"test":"test"}'
        ret = app.build_id_site_redirect_url(
            'http://localhost/', show_organization_field=True, sp_token=sp_token)
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data["sof"], True)
        self.assertEqual(decoded_data["sp_token"], sp_token)
        self.assertIsNone(decoded_data.get('onk'))

        ret = app.build_id_site_redirect_url(
            'http://localhost/', organization_name_key="testorg")
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data["onk"], "testorg")
        self.assertNotEqual(decoded_data.get('sof'), True)
    def test_building_id_site_redirect_uri(self):
        app = Application(client=self.client, properties={'href': 'apphref'})
        ret = app.build_id_site_redirect_url('http://localhost/')
        decoded_data = self.decode_jwt(ret)
        self.assertIsNotNone(decoded_data.get('iat'))
        self.assertIsNotNone(decoded_data.get('jti'))
        self.assertIsNotNone(decoded_data.get('iss'))
        self.assertIsNotNone(decoded_data.get('sub'))
        self.assertIsNotNone(decoded_data.get('cb_uri'))
        self.assertEqual(decoded_data.get('cb_uri'), 'http://localhost/')
        self.assertIsNone(decoded_data.get('path'))
        self.assertIsNone(decoded_data.get('state'))
        self.assertNotEqual(decoded_data.get('sof'), True)
        self.assertIsNone(decoded_data.get('onk'))
        self.assertIsNone(decoded_data.get('sp_token'))

        ret = app.build_id_site_redirect_url('http://testserver/',
                                             path='/#/register',
                                             state='test')
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data.get('path'), '/#/register')
        self.assertEqual(decoded_data.get('state'), 'test')

        sp_token = '{"test":"test"}'
        ret = app.build_id_site_redirect_url('http://localhost/',
                                             show_organization_field=True,
                                             sp_token=sp_token)
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data["sof"], True)
        self.assertEqual(decoded_data["sp_token"], sp_token)
        self.assertIsNone(decoded_data.get('onk'))

        ret = app.build_id_site_redirect_url('http://localhost/',
                                             organization_name_key="testorg")
        decoded_data = self.decode_jwt(ret)
        self.assertEqual(decoded_data["onk"], "testorg")
        self.assertNotEqual(decoded_data.get('sof'), True)
Example #13
0
 def test_save_wont_save_new_resources(self):
     r = Application(MagicMock(), properties={})
     self.assertRaises(ValueError, r.save)
Example #14
0
 def test_deleting_new_resource(self):
     r = Application(MagicMock(), properties={})
     self.assertIsNone(r.delete())
Example #15
0
 def test_resource_status_is_disabled_if_not_specified(self):
     r = Application(MagicMock(), properties={})
     self.assertEqual(r.STATUS_DISABLED, r.get_status())
Example #16
0
 def test_getting_resource_status(self):
     r = Application(MagicMock(),
                     properties={'status': Application.STATUS_ENABLED})
     self.assertEqual(r.STATUS_ENABLED, r.get_status())
Example #17
0
 def test_checking_if_status_enabled(self):
     r = Application(MagicMock(),
                     properties={'status': Application.STATUS_ENABLED})
     self.assertTrue(r.is_enabled())
 def test_iter_method_on_dict_mixin(self):
     r = Application(MagicMock(), properties={'name': 'some app'})
     self.assertEqual(['name'], list(r.__iter__()))
Example #19
0
 def test_getting_items_from_dict_mixing(self):
     r = Application(MagicMock(), properties={'name': 'some app'})
     self.assertEqual([('name', 'some app')], r.items())
 def test_checking_if_status_disabled(self):
     r = Application(
             MagicMock(),
             properties={})
     self.assertTrue(r.is_disabled())
 def test_checking_if_status_enabled(self):
     r = Application(
             MagicMock(),
             properties={'status': Application.STATUS_ENABLED})
     self.assertTrue(r.is_enabled())
 def test_getting_resource_status(self):
     r = Application(
             MagicMock(),
             properties={'status': Application.STATUS_ENABLED})
     self.assertEqual(r.STATUS_ENABLED, r.get_status())
 def test_resource_status_is_disabled_if_not_specified(self):
     r = Application(
             MagicMock(),
             properties={})
     self.assertEqual(r.STATUS_DISABLED, r.get_status())
 def test_deleting_new_resource(self):
     r = Application(
             MagicMock(),
             properties={})
     self.assertIsNone(r.delete())
Example #25
0
 def test_checking_if_status_disabled(self):
     r = Application(MagicMock(), properties={})
     self.assertTrue(r.is_disabled())
 def test_building_id_site_redirect_uri_with_usd(self):
     app = Application(client=self.client, properties={'href': 'apphref'})
     ret = app.build_id_site_redirect_url('http://localhost/',
                                          use_subdomain=True)
     decoded_data = self.decode_jwt(ret)
     self.assertEqual(decoded_data.get('usd'), True)
 def test_getting_items_from_dict_mixing(self):
     r = Application(MagicMock(), properties={'name': 'some app'})
     self.assertEqual([('name', 'some app')], r.items())
 def test_building_id_site_redirect_uri_with_usd(self):
     app = Application(client=self.client, properties={'href': 'apphref'})
     ret = app.build_id_site_redirect_url('http://localhost/', use_subdomain=True)
     decoded_data = self.decode_jwt(ret)
     self.assertEqual(decoded_data.get('usd'), True)
Example #29
0
 def test_iter_method_on_dict_mixin(self):
     r = Application(MagicMock(), properties={'name': 'some app'})
     self.assertEqual(['name'], list(r.__iter__()))