def test_checkPermission(self): from zope.security import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction, endInteraction from zope.security.interfaces import NoInteraction permission = 'zope.Test' obj = object() class PolicyStub(object): def checkPermission( s, p, o, ): self.assert_(p is permission) self.assert_(o is obj) self.assert_(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEquals(checkPermission(permission, obj), True) endInteraction() self.assertRaises(NoInteraction, checkPermission, permission, obj)
def test_checkPermission(self): from zope.security import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction, endInteraction from zope.security.interfaces import NoInteraction permission = 'zope.Test' obj = object() class PolicyStub(object): def checkPermission(s, p, o,): self.assert_(p is permission) self.assert_(o is obj) self.assert_(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEquals(checkPermission(permission, obj), True) endInteraction() self.assertRaises(NoInteraction, checkPermission, permission, obj)
def router(conf, session_key, zcml, dsn, name): allowed = ('de',) register_allowed_languages(allowed) config.ALLOWED_LANGUAGES = None load_zcml(zcml) setSecurityPolicy(GenericSecurityPolicy) # We register our SQLengine under a given name engine = create_engine(dsn, name) # We use a declarative base, if it exists we bind it and create engine.bind(Base) metadata = Base.metadata metadata.create_all(engine.engine, checkfirst=True) # Router root = URLMap() admin_app = Admin(session_key, engine, name) root['/admin'] = localize(admin_app) root['/'] = localize(User(session_key, engine, name)) root.__runner__ = admin_app.__runner__ return root
def create(cls, gc, **kws): kws['base'] = Base setSecurityPolicy(GenericSecurityPolicy) session_key = kws.get("session_key", "session") key = key_from_file(path.join(kws.pop('root'), 'jwt.key')) session_wrapper = JWTCookieSession(key, 60, environ_key=session_key) app = super(MySQL, cls).create(gc, **kws) return session_wrapper(app.__call__)
def test_securityPolicy(self): from zope.security.management import setSecurityPolicy from zope.security.management import getSecurityPolicy from zope.security.simplepolicies import PermissiveSecurityPolicy policy = PermissiveSecurityPolicy setSecurityPolicy(policy) self.assertTrue(getSecurityPolicy() is policy)
def test_securityPolicy(self): from zope.security.management import setSecurityPolicy from zope.security.management import getSecurityPolicy from zope.security.simplepolicies import PermissiveSecurityPolicy policy = PermissiveSecurityPolicy setSecurityPolicy(policy) self.assert_(getSecurityPolicy() is policy)
def routing(conf, files, **kwargs): languages = kwargs['langs'] allowed = languages.strip().replace(',', ' ').split() allowed = ('de',) register_allowed_languages(allowed) load_zcml(kwargs['zcml']) setSecurityPolicy(GenericSecurityPolicy) name = kwargs.get('name', 'school') # We register our SQLengine under a given name if not 'engine' in kwargs: dsn = kwargs['dsn'] engine = create_engine(dsn, name) else: engine = EngineServer(kwargs['engine'], name) # We use a declarative base, if it exists we bind it and create engine.bind(Base) metadata = Base.metadata metadata.create_all(engine.engine, checkfirst=True) # Extract possible layer layer = kwargs.get('layer') if layer is not None: layer_iface = eval_loader(layer) else: layer_iface = None title = kwargs.get('title', 'BG ETEM') # We create the session wrappper session_key = "session" key = key_from_file(path.join(kwargs['root'], 'jwt.key')) session_wrapper = Session(key, 60, environ_key=session_key) # Applications configuration smtp = kwargs.get('smtp', '10.33.115.55') setup = Configuration( title, session_key, engine, name, None, layer_iface, smtp) # Router root = URLMap() quizz = localize(anonymous.Application(setup)) root['/'] = localize(company.Application(setup)) root['/register'] = localize(company.Registration(setup)) root['/quizz'] = quizz root['/befragung'] = quizz root['/json'] = localize(remote.Application(setup)) return session_wrapper(root.__call__)
def test_addCell_no_invalidation(self): class NoInvalidation(object): attrs = () def __getattr__(self, name): self.attrs += (name,) return object.__getattr__(self, name) setSecurityPolicy(NoInvalidation) endInteraction() newInteraction() map = self._getSecurityMap() map.addCell(0, 0, 'aa') self.assertIn('invalidate_cache', getInteraction().attrs)
def testSetUp(cls): """Fixture replicating the process-mail.py environment. This zopeless script uses the regular security policy and connects as a specific DB user. """ cls._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy) switch_dbuser(config.processmail.dbuser)
def test_checkPermission_forbidden_policy(self): from zope.security import checkPermission from zope.security.checker import CheckerPublic from zope.security.management import setSecurityPolicy from zope.security.management import newInteraction obj = object() class ForbiddenPolicyStub(object): def checkPermission(s, p, o): return False setSecurityPolicy(ForbiddenPolicyStub) newInteraction() self.assertEqual(checkPermission("zope.Test", obj), False) self.assertEqual(checkPermission(None, obj), True) self.assertEqual(checkPermission(CheckerPublic, obj), True)
def permissive_security_policy(dbuser_name=None): """Context manager to run code with a permissive security policy. This is just enough to run code such as `BaseMailer` that normally expects to be called only from environments that use a permissive security policy, such as jobs or scripts. """ try: old_policy = setSecurityPolicy(LaunchpadPermissiveSecurityPolicy) if dbuser_name is not None: dbuser_context = dbuser(dbuser_name) else: dbuser_context = contextmanager([None].__iter__) with person_logged_in(ANONYMOUS), dbuser_context: yield finally: setSecurityPolicy(old_policy)
def test_checkPermission_forbidden_policy(self): from zope.security import checkPermission from zope.security.checker import CheckerPublic from zope.security.management import setSecurityPolicy from zope.security.management import newInteraction obj = object() class ForbiddenPolicyStub(object): def checkPermission(s, p, o): return False setSecurityPolicy(ForbiddenPolicyStub) newInteraction() self.assertEqual(checkPermission('zope.Test', obj), False) self.assertEqual(checkPermission(None, obj), True) self.assertEqual(checkPermission(CheckerPublic, obj), True)
def setUp(self): super(TestUpdateStatusEmailCommand, self).setUp( user='******') self._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy) self.merge_proposal = self.factory.makeBranchMergeProposal() # Default the user to be the target branch owner, so they are # authorised to update the status. self.context = CodeReviewEmailCommandExecutionContext( self.merge_proposal, self.merge_proposal.target_branch.owner) self.jrandom = self.factory.makePerson() switch_dbuser(config.processmail.dbuser)
def test_checkPermission_w_interaction(self): from zope.security.management import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction permission = "zope.Test" obj = object() class PolicyStub(object): def checkPermission(s, p, o): self.assertTrue(p is permission) self.assertTrue(o is obj) self.assertTrue(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEqual(checkPermission(permission, obj), True)
def zopelessLaunchpadSecuritySetUp(test): """Set up a LaunchpadZopelessLayer test to use LaunchpadSecurityPolicy. To be able to use switch_dbuser in a test, we need to run in the Zopeless environment. The Zopeless environment normally runs using the LaunchpadPermissiveSecurityPolicy. If we want the test to cover functionality used in the webapp, it needs to use the LaunchpadSecurityPolicy. """ setGlobs(test) test.old_security_policy = setSecurityPolicy(LaunchpadSecurityPolicy)
def wire_security(): management.setSecurityPolicy(SimulationSecurityPolicy) checker.defineChecker(sandbox.Sandbox, sandbox_checker) checker.defineChecker(sandbox.TimeService, time_service_checker) checker.defineChecker(sandbox.AgentDiscoveryService, agent_service_checker) checker.defineChecker(sandbox.HomeDiscoveryService, home_service_checker) def addAgent(self, agent): if not self._agents.has_key(agent.getId()) \ and sandbox.IAgent.providedBy(agent): self._agents[agent.getId()]=agent agentChecker = checker.selectChecker(self) wrapped_home = agentChecker.proxy(self) agent.setHome(wrapped_home) else: raise sandbox.SandboxError("couldn't add agent %s" %agent) sandbox.Sandbox.addAgent = addAgent def setupAgent(self, agent): management.newInteraction(AgentParticipation(agent)) sandbox.TimeGenerator.setupAgent = setupAgent def teardownAgent(self, agent): management.endInteraction() sandbox.TimeGenerator.teardownAgent = teardownAgent def GreenerPastures(agent): """ where do they want to go today """ import random _homes = sandbox._homes possible_homes = _homes.keys() possible_homes.remove(agent.getHome().getId()) new_home = _homes.get(random.choice(possible_homes)) return checker.selectChecker(new_home).proxy(new_home) sandbox.GreenerPastures = GreenerPastures
def wire_security(): management.setSecurityPolicy(SimulationSecurityPolicy) checker.defineChecker(sandbox.Sandbox, sandbox_checker) checker.defineChecker(sandbox.TimeService, time_service_checker) checker.defineChecker(sandbox.AgentDiscoveryService, agent_service_checker) checker.defineChecker(sandbox.HomeDiscoveryService, home_service_checker) def addAgent(self, agent): if not self._agents.has_key(agent.getId()) \ and sandbox.IAgent.providedBy(agent): self._agents[agent.getId()] = agent agentChecker = checker.selectChecker(self) wrapped_home = agentChecker.proxy(self) agent.setHome(wrapped_home) else: raise sandbox.SandboxError("couldn't add agent %s" % agent) sandbox.Sandbox.addAgent = addAgent def setupAgent(self, agent): management.newInteraction(AgentParticipation(agent)) sandbox.TimeGenerator.setupAgent = setupAgent def teardownAgent(self, agent): management.endInteraction() sandbox.TimeGenerator.teardownAgent = teardownAgent def GreenerPastures(agent): """ where do they want to go today """ import random _homes = sandbox._homes possible_homes = _homes.keys() possible_homes.remove(agent.getHome().getId()) new_home = _homes.get(random.choice(possible_homes)) return checker.selectChecker(new_home).proxy(new_home) sandbox.GreenerPastures = GreenerPastures
def test_ownership_concept(self): alice = User('alice') bob = User('bob') oldpolicy = setSecurityPolicy(zopepolicy.ZopeSecurityPolicy) def create_object(): obj = DummyObject() roleper = interfaces.IRolePermissionManager(obj) roleper.grantPermissionToRole('anything', 'owner') return obj def set_owner(obj, principal): prinrole = interfaces.IPrincipalRoleManager(obj) prinrole.assignRoleToPrincipal('owner', principal.id) aobj = create_object() bobj = create_object() bob_p = Participation() bob_p.principal = bob alice_p = Participation() alice_p.principal = alice set_owner(aobj, alice) set_owner(bobj, bob) with InteractionScope(alice_p) as alice_int: # alice is owner of aobj, but cannot access bobj assert not alice_int.checkPermission('anything', bobj) assert alice_int.checkPermission('anything', aobj) with InteractionScope(bob_p) as bob_int: # bob is owner of bobj, but cannot access aobj assert bob_int.checkPermission('anything', bobj) assert not bob_int.checkPermission('anything', aobj) setSecurityPolicy(oldpolicy)
def test_checkPermission_w_interaction(self): from zope.security.management import checkPermission from zope.security.management import setSecurityPolicy from zope.security.management import queryInteraction from zope.security.management import newInteraction permission = 'zope.Test' obj = object() class PolicyStub(object): def checkPermission( s, p, o, ): self.assertTrue(p is permission) self.assertTrue(o is obj) self.assertTrue(s is queryInteraction() or s is interaction) return s is interaction setSecurityPolicy(PolicyStub) newInteraction() interaction = queryInteraction() self.assertEqual(checkPermission(permission, obj), True)
def setUp(self): super(BasePublicationTests, self).setUp() from zope.security.management import endInteraction endInteraction() ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets, HTTPCharsets) self.policy = setSecurityPolicy( simplepolicies.PermissiveSecurityPolicy) self.storage = DemoStorage('test_storage') self.db = db = DB(self.storage) ztapi.provideUtility(IAuthentication, principalRegistry) connection = db.open() root = connection.root() app = getattr(root, ZopePublication.root_name, None) if app is None: from zope.app.folder import rootFolder app = rootFolder() root[ZopePublication.root_name] = app transaction.commit() connection.close() self.app = app from zope.traversing.namespace import view, resource, etc ztapi.provideNamespaceHandler('view', view) ztapi.provideNamespaceHandler('resource', resource) ztapi.provideNamespaceHandler('etc', etc) self.request = TestRequest('/f1/f2') self.user = Principal('test.principal') self.request.setPrincipal(self.user) from zope.interface import Interface self.presentation_type = Interface self.request._presentation_type = self.presentation_type self.object = object() self.publication = ZopePublication(self.db)
def setUp(self): from zope.security.management import endInteraction endInteraction() self.policy = setSecurityPolicy(simplepolicies.PermissiveSecurityPolicy) self.storage = DemoStorage("test_storage") self.db = db = DB(self.storage) component.provideUtility(principalRegistry, IAuthentication) connection = db.open() root = connection.root() app = getattr(root, ZopePublication.root_name, None) if app is None: from zope.site.folder import rootFolder app = rootFolder() root[ZopePublication.root_name] = app transaction.commit() connection.close() self.app = app from zope.traversing.namespace import view, resource, etc support.provideNamespaceHandler("view", view) support.provideNamespaceHandler("resource", resource) support.provideNamespaceHandler("etc", etc) self.request = TestRequest("/f1/f2") self.user = Principal("test.principal") self.request.setPrincipal(self.user) from zope.interface import Interface self.presentation_type = Interface self.request._presentation_type = self.presentation_type self.object = object() self.publication = ZopePublication(self.db)
def setUp(self): super(BasePublicationTests, self).setUp() from zope.security.management import endInteraction endInteraction() ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets, HTTPCharsets) self.policy = setSecurityPolicy( simplepolicies.PermissiveSecurityPolicy ) self.storage = DemoStorage('test_storage') self.db = db = DB(self.storage) connection = db.open() root = connection.root() app = getattr(root, ZopePublication.root_name, None) if app is None: from zope.app.folder import rootFolder app = rootFolder() root[ZopePublication.root_name] = app transaction.commit() connection.close() self.app = app from zope.app.traversing.namespace import view, resource, etc ztapi.provideNamespaceHandler('view', view) ztapi.provideNamespaceHandler('resource', resource) ztapi.provideNamespaceHandler('etc', etc) self.request = TestRequest('/f1/f2') self.user = Principal('test.principal') self.request.setPrincipal(self.user) from zope.interface import Interface self.presentation_type = Interface self.request._presentation_type = self.presentation_type self.object = object() self.publication = ZopePublication(self.db)
def setUp(test=None): setup.placelessSetUp() test.globs['__policy'] = setSecurityPolicy(SecurityPolicy) endInteraction() newInteraction()
def tearDown(test=None): setSecurityPolicy(test.globs['__policy']) restoreInteraction() setup.placelessTearDown()
def decoratedTearDown(self): endInteraction() setSecurityPolicy(self._oldpolicy)
def setUp(test): test._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy) switch_dbuser(config.processmail.dbuser)
def setUp(self): super(TestMaloneHandler, self).setUp() self._old_policy = getSecurityPolicy() setSecurityPolicy(LaunchpadSecurityPolicy)
def execute_zcml_for_scripts(use_web_security=False): """Execute the zcml rooted at launchpad/script.zcml If use_web_security is True, the same security policy as the web application uses will be used. Otherwise everything protected by a permission is allowed, and everything else denied. """ # When in testing mode, prevent some cases of erroneous layer usage. # But we don't want to import that module in production usage, thus # the conditional block. if 'lp.testing.layers' in sys.modules: from lp.testing.layers import (FunctionalLayer, BaseLayer, ZopelessLayer) assert not FunctionalLayer.isSetUp, \ 'Setting up Zopeless CA when Zopefull CA is already running' assert not BaseLayer.isSetUp or ZopelessLayer.isSetUp, """ execute_zcml_for_scripts should not be called from tests. Instead, your test should use the Zopeless layer. """ if config.isTestRunner(): scriptzcmlfilename = 'script-testing.zcml' else: scriptzcmlfilename = 'script.zcml' scriptzcmlfilename = os.path.abspath( os.path.join(config.root, 'zcml', scriptzcmlfilename)) from zope.configuration import xmlconfig # Hook up custom component architecture calls zope.site.hooks.setHooks() # Load server-independent site config context = ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context = xmlconfig.file(scriptzcmlfilename, execute=True, context=context) if use_web_security: setSecurityPolicy(LaunchpadSecurityPolicy) else: setSecurityPolicy(LaunchpadPermissiveSecurityPolicy) # Register atexit handler to kill off mail delivery daemon threads, and # thus avoid spew at exit. See: # http://mail.python.org/pipermail/python-list/2003-October/192044.html # http://mail.python.org/pipermail/python-dev/2003-September/038151.html # http://mail.python.org/pipermail/python-dev/2003-September/038153.html def kill_queue_processor_threads(): for thread in threading.enumerate(): if isinstance(thread, zope.sendmail.delivery.QueueProcessorThread): thread.stop() thread.join(30) if thread.isAlive(): raise RuntimeError( "QueueProcessorThread did not shut down") atexit.register(kill_queue_processor_threads) # This is a convenient hack to set up a zope interaction, before we get # the proper API for having a principal / user running in scripts. setupInteractionByEmail(ANONYMOUS)
def tearDown(self): setSecurityPolicy(self._old_policy) super(TestCodeHandler, self).tearDown()
def tearDown(self): setSecurityPolicy(self._old_policy) super(TestUpdateStatusEmailCommand, self).tearDown()
def setUp(self): super(TestCodeHandler, self).setUp(user='******') self.code_handler = CodeHandler() self._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy)
def tearDown(self): endInteraction() setSecurityPolicy(self.__oldpolicy) CleanUp.tearDown(self)
def decoratedSetUp(self): self.policy = RecordedSecurityPolicy self._oldpolicy = setSecurityPolicy(self.policy) newInteraction() self.interaction = getInteraction() self.obj = object()
def tearDown(self): setSecurityPolicy(self._old_policy) super(TestAddReviewerEmailCommand, self).tearDown()
def set_policy_security(settings, event): management.setSecurityPolicy(ZopeSecurityPolicy)
def testTearDown(cls): """Tear down the test fixture.""" setSecurityPolicy(cls._old_policy)
def zopelessLaunchpadSecurityTearDown(test): setSecurityPolicy(test.old_security_policy)
def setUp(self): CleanUp.setUp(self) self.__oldpolicy = setSecurityPolicy(SecurityPolicy) newInteraction()
def tearDown(self): super(TestMaloneHandler, self).tearDown() setSecurityPolicy(self._old_policy)
def tearDown(test): setSecurityPolicy(test._old_policy)
def execute_zcml_for_scripts(use_web_security=False): """Execute the zcml rooted at launchpad/script.zcml If use_web_security is True, the same security policy as the web application uses will be used. Otherwise everything protected by a permission is allowed, and everything else denied. """ # When in testing mode, prevent some cases of erroneous layer usage. # But we don't want to import that module in production usage, thus # the conditional block. if 'lp.testing.layers' in sys.modules: from lp.testing.layers import ( FunctionalLayer, BaseLayer, ZopelessLayer) assert not FunctionalLayer.isSetUp, \ 'Setting up Zopeless CA when Zopefull CA is already running' assert not BaseLayer.isSetUp or ZopelessLayer.isSetUp, """ execute_zcml_for_scripts should not be called from tests. Instead, your test should use the Zopeless layer. """ if config.isTestRunner(): scriptzcmlfilename = 'script-testing.zcml' else: scriptzcmlfilename = 'script.zcml' scriptzcmlfilename = os.path.abspath( os.path.join(config.root, 'zcml', scriptzcmlfilename)) from zope.configuration import xmlconfig # Hook up custom component architecture calls zope.site.hooks.setHooks() # Load server-independent site config context = ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context = xmlconfig.file( scriptzcmlfilename, execute=True, context=context) if use_web_security: setSecurityPolicy(LaunchpadSecurityPolicy) else: setSecurityPolicy(LaunchpadPermissiveSecurityPolicy) # Register atexit handler to kill off mail delivery daemon threads, and # thus avoid spew at exit. See: # http://mail.python.org/pipermail/python-list/2003-October/192044.html # http://mail.python.org/pipermail/python-dev/2003-September/038151.html # http://mail.python.org/pipermail/python-dev/2003-September/038153.html def kill_queue_processor_threads(): for thread in threading.enumerate(): if isinstance( thread, zope.sendmail.delivery.QueueProcessorThread): thread.stop() thread.join(30) if thread.isAlive(): raise RuntimeError( "QueueProcessorThread did not shut down") atexit.register(kill_queue_processor_threads) # This is a convenient hack to set up a zope interaction, before we get # the proper API for having a principal / user running in scripts. setupInteractionByEmail(ANONYMOUS)