Ejemplo n.º 1
0
    def testProtectedPageViews(self):
        component.provideUtility(Permission('p', 'P'), IPermission, 'p')

        request = TestRequest()
        self.assertEqual(
            component.queryMultiAdapter((ob, request), name='test'), None)

        xmlconfig(
            StringIO(template % u'''
            <include package="zope.security" file="meta.zcml" />

            <permission id="zope.TestPermission" title="Test permission" />

            <browser:pages
                class="zope.browserpage.tests.test_page.V1"
                for="zope.browserpage.tests.test_page.IC"
                permission="zope.TestPermission"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
            </browser:pages>
            '''))

        v = component.getMultiAdapter((ob, request), name='index.html')
        v = ProxyFactory(v)
        zope.security.management.getInteraction().add(request)
        self.assertRaises(Exception, v)
        v = component.getMultiAdapter((ob, request), name='action.html')
        v = ProxyFactory(v)
        self.assertRaises(Exception, v)
Ejemplo n.º 2
0
    def testFile(self):
        path = os.path.join(tests_path, 'testfiles', 'test.pt')

        self.assertEqual(component.queryAdapter(request, name='test'), None)

        xmlconfig(
            StringIO(template % '''
            <browser:resource
                name="index.html"
                file="%s"
                />
            ''' % path))

        r = component.getAdapter(request, name='index.html')
        self.assertTrue(isinstance(r, FileResource))
        r = ProxyFactory(r)
        self.assertEqual(r.__name__, "index.html")

        # Make sure we can access available attrs and not others
        for n in ('GET', 'HEAD', 'publishTraverse', 'request', '__call__'):
            getattr(r, n)

        self.assertRaises(Exception, getattr, r, '_testData')

        r = removeSecurityProxy(r)
        self.assertEqual(r._testData(), open(path, 'rb').read())
Ejemplo n.º 3
0
    def testFile(self):
        path = os.path.join(tests_path, 'testfiles', 'test.pt')

        self.assertEqual(zapi.queryAdapter(request, name='test'), None)

        xmlconfig(StringIO(template %
            '''
            <browser:resource
                name="index.html"
                file="%s"
                />
            ''' % path
            ))

        r = zapi.getAdapter(request, name='index.html')
        self.assertEquals(r.__class__, FileResource)
        r = ProxyFactory(r)
        self.assertEqual(r.__name__, "index.html")

        # Make sure we can access available attrs and not others
        for n in ('GET', 'HEAD', 'publishTraverse', 'request', '__call__'):
            getattr(r, n)
        self.assertEqual(r.__name__, "index.html")

        self.assertRaises(Exception, getattr, r, '_testData')

        r = removeSecurityProxy(r)
        self.assert_(r.__class__ is FileResource)
        self.assertEqual(r._testData(), open(path, 'rb').read())
Ejemplo n.º 4
0
    def test_both_wrapper_and_object_have_checkers_security_proxied(self):
        from zope.proxy import ProxyBase
        from zope.security.checker import CombinedChecker
        from zope.security.checker import NamesChecker
        from zope.security.checker import defineChecker
        from zope.security.proxy import ProxyFactory

        class Foo(object):
            a = 'a'

        fooChecker = NamesChecker(['a'])  # a is public
        defineChecker(Foo, fooChecker)
        foo = Foo()
        f_sec = ProxyFactory(foo)

        class Wrapper(ProxyBase):
            b = 'b'
            __Security_checker__ = self._makeOne()

        wrapperChecker = NamesChecker(['b'])  # b is public
        defineChecker(Wrapper, wrapperChecker)
        w_sec = Wrapper(f_sec)

        checker = w_sec.__Security_checker__
        self.assertTrue(isinstance(checker, CombinedChecker))
        checker.check(w_sec, 'a')  # no raise
        checker.check(w_sec, 'b')  # no raise
Ejemplo n.º 5
0
    def test__call__w_non_ILocation_multiple_args_extra_spacesuit(self):
        from zope.security.proxy import ProxyFactory
        from zope.security.proxy import removeSecurityProxy
        factory = self._makeFactory()
        ltaf = self._makeOne(factory)

        class _NotAdapter(object):
            pass

        class _Extra(object):
            pass

        adapter = _NotAdapter()
        extra = _Extra()
        proxy = ProxyFactory(extra)
        before = factory.__dict__.copy()
        returned = ltaf(adapter, proxy)
        self.assertFalse(returned is factory)
        unwrapped = removeSecurityProxy(returned)
        self.assertTrue('__parent__' not in unwrapped.__dict__)
        self.assertIs(unwrapped, factory)
        after = {
            k: v
            for k, v in unwrapped.__dict__.items()
            if k not in ('_called_with', )
        }
        self.assertEqual(factory._called_with, (adapter, extra))
        self.assertEqual(after, before)  # no added attrs
Ejemplo n.º 6
0
    def testInterfaceProtectedPage(self):
        xmlconfig(
            StringIO(template % u'''
            <browser:page name="test"
                class="zope.browserpage.tests.test_page.V1"
                attribute="index"
                for="zope.browserpage.tests.test_page.IC"
                permission="zope.Public"
                allowed_interface="zope.browserpage.tests.test_page.IV"
                />
            '''))

        v = component.getMultiAdapter((ob, self.request), name='test')
        v = ProxyFactory(v)
        self.assertEqual(v.index(), 'V1 here')
        self.assertRaises(Exception, getattr, v, 'action')
Ejemplo n.º 7
0
    def test__call__w_non_ILocation_w_spacesuit(self):
        from zope.security.proxy import ProxyFactory
        from zope.security.proxy import removeSecurityProxy
        factory = self._makeFactory()
        ltaf = self._makeOne(factory)

        class _NotAdapter(object):
            pass

        adapter = _NotAdapter()
        proxy = ProxyFactory(adapter)
        before = factory.__dict__.copy()
        returned = ltaf(proxy)
        self.assertFalse(returned is factory)
        ploc = removeSecurityProxy(returned)
        self.assertIs(ploc.__parent__, adapter)
        unwrapped = getProxiedObject(ploc)
        self.assertIs(unwrapped, factory)
        after = {
            k: v
            for k, v in unwrapped.__dict__.items()
            if k not in ('_called_with', )
        }
        self.assertEqual(factory._called_with, (adapter, ))
        self.assertEqual(after, before)  # no added attrs
Ejemplo n.º 8
0
    def testProxiedNewClassAsDictKey(self):
        class C(object):
            pass

        d = {C: C()}
        pC = ProxyFactory(C, self.c)
        self.assertEqual(d[pC], d[C])
Ejemplo n.º 9
0
def get_sitting_items(sitting, request, include_actions=False):
    items = []

    if (sitting.status in IWorkflow(sitting).get_state_ids(
            keys=["draft_agenda", "published_agenda"])):
        order = "planned_order"
    else:
        order = "real_order"

    schedulings = map(removeSecurityProxy,
                      sitting.items.batch(order_by=order, limit=None))
    for scheduling in schedulings:
        item = ProxyFactory(location_wrapped(scheduling.item, sitting))

        props = IDCDescriptiveProperties.providedBy(item) and item or \
                IDCDescriptiveProperties(item)

        discussions = tuple(scheduling.discussions.values())
        discussion = discussions and discussions[0] or None
        truncated_discussion = None
        if ((discussion is not None) and (discussion.body is not None)):
            #truncate discussion to first hundred characters
            t_discussion = discussion.body[0:100]
            try:
                #truncate discussion to first two lines
                index = t_discussion.index("<br>")
                index2 = t_discussion.index("<br>", index + 4)
                truncated_discussion = t_discussion[0:index2] + "..."
            except ValueError:
                truncated_discussion = t_discussion + "..."
        state_title = IWorkflow(item).get_state(item.status).title
        item = removeSecurityProxy(item)
        record = {
            "title": props.title,
            "description": props.description,
            "name": stringKey(scheduling),
            "status": item.status,
            "type": item.type.capitalize,
            "state_title": state_title,
            "heading": True if item.type == "heading" else False,
            #"category_id": scheduling.category_id,
            #"category": scheduling.category,
            "discussion": discussion,
            "truncated_discussion": truncated_discussion,
            "delete_url": "%s/delete" % url.absoluteURL(scheduling, request),
            "url": url.absoluteURL(item, request),
        }

        if include_actions:
            record["actions"] = get_scheduling_actions(scheduling, request)
            record["workflow"] = get_workflow_actions(item, request)

            discussion_actions = get_discussion_actions(discussion, request)
            if discussion_actions:
                assert len(discussion_actions) == 1
                record["discussion_action"] = discussion_actions[0]
            else:
                record["discussion_action"] = None
        items.append(record)
    return items
Ejemplo n.º 10
0
    def testDirectory(self):
        path = os.path.join(tests_path, 'testfiles', 'subdir')

        self.assertEqual(component.queryAdapter(request, name='dir'), None)

        xmlconfig(
            StringIO(template % '''
            <browser:resourceDirectory
                name="dir"
                directory="%s"
                />
            ''' % path))

        r = component.getAdapter(request, name='dir')
        self.assertTrue(isinstance(r, DirectoryResource))
        r = ProxyFactory(r)
        self.assertEqual(r.__name__, "dir")

        # Make sure we can access available attrs and not others
        for n in ('publishTraverse', 'browserDefault', 'request', '__call__',
                  'get', '__getitem__'):
            getattr(r, n)

        self.assertRaises(Exception, getattr, r, 'directory_factory')

        inexistent_dir = StringIO(template % '''
            <browser:resourceDirectory
                name="dir"
                directory="does-not-exist"
                />
            ''')

        self.assertRaises(ConfigurationError, xmlconfig, inexistent_dir)
Ejemplo n.º 11
0
    def test__call__w_ILocation_w_spacesuit_w_existing_parent(self):
        from zope.security.proxy import ProxyFactory
        from zope.security.proxy import removeSecurityProxy
        factory = self._makeFactory()
        factory.__name__ = None
        factory.__parent__ = parent = object()
        directlyProvides(factory, ILocation)
        ltaf = self._makeOne(factory)

        class _Adapter(object):
            pass

        adapter = _Adapter()
        proxy = ProxyFactory(adapter)
        before = {
            k: v
            for k, v in factory.__dict__.items()
            if k not in ('_called_with', '__parent__')
        }
        returned = ltaf(proxy)
        self.assertFalse(returned is factory)
        unwrapped = removeSecurityProxy(returned)
        self.assertIs(unwrapped.__parent__, parent)
        self.assertIs(unwrapped, factory)
        after = {
            k: v
            for k, v in unwrapped.__dict__.items()
            if k not in ('_called_with', '__parent__')
        }
        self.assertEqual(factory._called_with, (adapter, ))
        self.assertEqual(after, before)  # no added attrs
Ejemplo n.º 12
0
    def testFile(self):
        from zope.security.interfaces import ForbiddenAttribute
        path = os.path.join(tests_path, 'testfiles', 'test.pt')

        self.assertEqual(component.queryAdapter(request, name='test'), None)

        xmlconfig(
            StringIO(template % '''
            <browser:resource
                name="index.html"
                file="%s"
                />
            ''' % path))

        unwrapped_r = component.getAdapter(request, name='index.html')
        self.assertTrue(isinstance(unwrapped_r, FileResource))
        r = ProxyFactory(unwrapped_r)
        self.assertEqual(r.__name__, "index.html")

        # Make sure we can access available attrs and not others
        for n in ('GET', 'HEAD', 'publishTraverse', 'request', '__call__'):
            getattr(r, n)

        self.assertRaises(ForbiddenAttribute, getattr, r, '_testData')

        with open(path, 'rb') as f:
            self.assertEqual(unwrapped_r._testData(), f.read())
Ejemplo n.º 13
0
 def test__call__w_ILocation_w_spacesuit(self):
     from zope.interface import directlyProvides
     from zope.location import ILocation
     from zope.security.proxy import getObject
     from zope.security.proxy import ProxyFactory
     from zope.security.proxy import removeSecurityProxy
     factory = self._makeFactory()
     factory.__parent__ = factory.__name__ = None
     directlyProvides(factory, ILocation)
     ltaf = self._makeOne(factory)
     class _Adapter(object):
         pass
     adapter = _Adapter()
     proxy = ProxyFactory(adapter)
     before = dict([(k, v) for k, v in factory.__dict__.items()
                      if k not in ('_called_with', '__parent__')])
     returned = ltaf(proxy)
     self.assertFalse(returned is factory)
     ploc = removeSecurityProxy(returned)
     self.assertTrue(ploc.__parent__ is adapter)
     unwrapped = getObject(ploc)
     self.assertTrue(unwrapped is factory)
     after = dict([(k, v) for k, v in unwrapped.__dict__.items()
                      if k not in ('_called_with', '__parent__')])
     self.assertEqual(factory._called_with, (adapter,))
     self.assertTrue(factory.__parent__ is adapter)
     self.assertEqual(after, before) # no added attrs
Ejemplo n.º 14
0
    def testInterfaceProtectedPage(self):
        xmlconfig(StringIO(template %
            '''
            <browser:page name="test"
                class="zope.app.component.tests.views.V1"
                attribute="index"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                allowed_interface="zope.app.component.tests.views.IV"
                />
            '''
            ))

        v = zapi.getMultiAdapter((ob, request), name='test')
        v = ProxyFactory(v)
        self.assertEqual(v.index(), 'V1 here')
        self.assertRaises(Exception, getattr, v, 'action')
Ejemplo n.º 15
0
    def testAttributeProtectedPage(self):
        xmlconfig(
            StringIO(template % u'''
            <browser:page name="test"
                class="zope.browserpage.tests.test_page.V2"
                for="zope.browserpage.tests.test_page.IC"
                attribute="action"
                permission="zope.Public"
                allowed_attributes="action2"
                />
            '''))

        v = component.getMultiAdapter((ob, self.request), name='test')
        v = ProxyFactory(v)
        self.assertEqual(v.action(), 'done')
        self.assertEqual(v.action2(), 'done')
        self.assertRaises(Exception, getattr, v, 'index')
Ejemplo n.º 16
0
    def render(self, request, *args, **keywords):
        instance = self.__parent__

        debug_flags = request.debug
        request = ProxyFactory(request)
        instance = ProxyFactory(instance)
        if args:
            args = ProxyFactory(args)
        kw = ProxyFactory(keywords)

        namespace = self.pt_getContext(instance,
                                       request,
                                       args=args,
                                       options=kw)

        return self.pt_render(namespace,
                              showtal=debug_flags.showTAL,
                              sourceAnnotations=debug_flags.sourceAnnotations)
Ejemplo n.º 17
0
    def testAttributeProtectedPage(self):
        xmlconfig(StringIO(template %
            '''
            <browser:page name="test"
                class="zope.app.publisher.browser.tests.test_directives.V2"
                for="zope.app.component.tests.views.IC"
                attribute="action"
                permission="zope.Public"
                allowed_attributes="action2"
                />
            '''
            ))

        v = zapi.getMultiAdapter((ob, request), name='test')
        v = ProxyFactory(v)
        self.assertEqual(v.action(), 'done')
        self.assertEqual(v.action2(), 'done')
        self.assertRaises(Exception, getattr, v, 'index')
Ejemplo n.º 18
0
    def testAttributeProtectedView(self):
        xmlconfig(
            StringIO(template % u'''
            <browser:view name="test"
                class="zope.browserpage.tests.test_page.V2"
                for="zope.browserpage.tests.test_page.IC"
                permission="zope.Public"
                allowed_attributes="action2"
                >
              <browser:page name="index.html" attribute="action" />
           </browser:view>
            '''))

        v = component.getMultiAdapter((ob, self.request), name='test')
        v = ProxyFactory(v)
        page = v.publishTraverse(self.request, 'index.html')
        self.assertEqual(page(), 'done')
        self.assertEqual(v.action2(), 'done')
        self.assertRaises(Exception, getattr, page, 'index')
 def test_read_to_all(self):
     """`BugSubscriptionFilter`s can be read by anyone."""
     bug_subscription_filter = BugSubscriptionFilter()
     bug_subscription_filter.structural_subscription = self.subscription
     bug_subscription_filter = ProxyFactory(bug_subscription_filter)
     with person_logged_in(self.subscriber):
         bug_subscription_filter.find_all_tags
     with person_logged_in(self.factory.makePerson()):
         bug_subscription_filter.find_all_tags
     with anonymous_logged_in():
         bug_subscription_filter.find_all_tags
Ejemplo n.º 20
0
def get_sitting_items(sitting, request, include_actions=False):
    items = []

    if sitting.status in [
            sitting_wf_state[u'draft-agenda'].id,
            sitting_wf_state[u'published-agenda'].id
    ]:
        order = "planned_order"
    else:
        order = "real_order"

    schedulings = map(removeSecurityProxy,
                      sitting.items.batch(order_by=order, limit=None))

    for scheduling in schedulings:
        item = ProxyFactory(location_wrapped(scheduling.item, sitting))

        props = IDCDescriptiveProperties.providedBy(item) and item or \
                IDCDescriptiveProperties(item)

        discussions = tuple(scheduling.discussions.values())
        discussion = discussions and discussions[0] or None

        info = IWorkflowInfo(item, None)
        state_title = info.workflow().workflow.states[item.status].title

        record = {
            'title': props.title,
            'description': props.description,
            'name': stringKey(scheduling),
            'status': item.status,
            'type': item.type.capitalize,
            't': item.type,
            'state_title': state_title,
            #'category_id': scheduling.category_id,
            #'category': scheduling.category,
            'discussion': discussion,
            'delete_url':
            "%s/delete" % ui_url.absoluteURL(scheduling, request),
            'url': ui_url.absoluteURL(item, request)
        }

        if include_actions:
            record['actions'] = get_scheduling_actions(scheduling, request)
            record['workflow'] = get_workflow_actions(item, request)

            discussion_actions = get_discussion_actions(discussion, request)
            if discussion_actions:
                assert len(discussion_actions) == 1
                record['discussion_action'] = discussion_actions[0]
            else:
                record['discussion_action'] = None
        items.append(record)
    return items
Ejemplo n.º 21
0
 def test_security_should_allow_access_to_id_prefix(self):
     import zeit.cms.testing
     import zope.security.management
     from zope.security.proxy import ProxyFactory
     factory = zeit.content.video.testing.video_factory(self)
     next(factory)
     video = next(factory)  # in repository
     zope.security.management.endInteraction()
     with zeit.cms.testing.interaction('zope.mgr'):
         proxied = ProxyFactory(video)
         self.assertEqual('vid', proxied.id_prefix)
Ejemplo n.º 22
0
    def testAttributeProtectedView(self):
        xmlconfig(StringIO(template %
            '''
            <browser:view name="test"
                class="zope.browserpage.tests.test_page.V2"
                for="zope.component.testfiles.views.IC"
                permission="zope.Public"
                allowed_attributes="action2"
                >
              <browser:page name="index.html" attribute="action" />
           </browser:view>
            '''
            ))

        v = component.getMultiAdapter((ob, request), name='test')
        v = ProxyFactory(v)
        page = v.publishTraverse(request, 'index.html')
        self.assertEqual(page(), 'done')
        self.assertEqual(v.action2(), 'done')
        self.assertRaises(Exception, getattr, page, 'index')
Ejemplo n.º 23
0
    def testRepr(self):
        self.assertEqual(repr(self.p), repr(self.x))

        x = Something()
        c = Checker()
        c.ok = 0
        p = ProxyFactory(x, c)
        s = repr(p)
        self.failUnless(
            s.startswith("<security proxied %s.%s instance at" %
                         (x.__class__.__module__, x.__class__.__name__)), s)
Ejemplo n.º 24
0
    def testProtectedtemplate(self):

        path = os.path.join(tests_path, 'testfiles', 'test.pt')

        request = TestRequest()
        self.assertEqual(
            component.queryMultiAdapter((ob, request), name='test'),
            None)

        xmlconfig(StringIO(template %
            '''
            <include package="zope.security" file="meta.zcml" />

            <permission id="zope.TestPermission" title="Test permission" />

            <browser:page
                name="xxx.html"
                template="%s"
                permission="zope.TestPermission"
                for="zope.component.testfiles.views.IC" />
            ''' % path
            ))

        xmlconfig(StringIO(template %
            '''
            <browser:page
                name="index.html"
                template="%s"
                permission="zope.Public"
                for="zope.component.testfiles.views.IC" />
            ''' % path
            ))

        v = component.getMultiAdapter((ob, request), name='xxx.html')
        v = ProxyFactory(v)
        zope.security.management.getInteraction().add(request)
        self.assertRaises(Exception, v)

        v = component.getMultiAdapter((ob, request), name='index.html')
        v = ProxyFactory(v)
        self.assertEqual(v().strip(), '<html><body><p>test</p></body></html>')
Ejemplo n.º 25
0
def _Engine(engine=None):
    if engine is None:
        engine = ZopeEngine()
    engine = _create_base_engine(engine, ZopePathExpr)
    engine.registerType('python', ZopePythonExpr)

    # Using a proxy around sys.modules allows page templates to use
    # modules for which security declarations have been made, but
    # disallows execution of any import-time code for modules, which
    # should not be allowed to happen during rendering.
    engine.registerBaseName('modules', ProxyFactory(sys.modules))

    return engine
Ejemplo n.º 26
0
 def __call__(self):
     # Set up the utility with an appropriate proxy.
     # Note that this does not take into account other security
     # directives on this content made later on during the execution
     # of the zcml.
     checker = Checker(self.permission_collector.get_permissions,
                       self.permission_collector.set_permissions)
     component = ProxyFactory(self.component, checker=checker)
     utility(self._context,
             self.provides,
             component=component,
             name=self.name)
     return ()
    def find(self, *args, **kwargs):
        """See `IResultSet`.

        :return: The decorated version of the returned result set.
        """
        naked_result_set = removeSecurityProxy(self.result_set)
        if naked_result_set is not self.result_set:
            naked_new_result_set = naked_result_set.find(*args, **kwargs)
            new_result_set = ProxyFactory(naked_new_result_set)
        else:
            new_result_set = self.result_set.find(*args, **kwargs)
        return DecoratedResultSet(new_result_set, self.result_decorator,
                                  self.pre_iter_hook, self.slice_info,
                                  self.return_both)
Ejemplo n.º 28
0
    def getSliceFromMemo(self, size, memo):
        """Return a result set for the given memo values.

        Note that at least two other implementations are possible:
        Instead of OR-combining the expressions returned by
        whereExpressions(), these expressions could be used for
        separate SELECTs which are then merged with UNION ALL.

        We could also issue separate Storm queries for each
        expression and combine the results here.

        Which variant is more efficient is yet unknown; it may
        differ between different queries.
        """
        sort_expressions = self.getOrderBy()
        where = self.whereExpressions(sort_expressions, memo)
        where = reduce(Or, where)
        # From storm.zope.interfaces.IResultSet.__doc__:
        #     - C{find()}, C{group_by()} and C{having()} are really
        #       used to configure result sets, so are mostly intended
        #       for use on the model side.
        naked_result = removeSecurityProxy(self.resultset).find(where)
        result = ProxyFactory(naked_result)
        return result.config(limit=size)
Ejemplo n.º 29
0
 def test_unops(self):
     # We want the starting value of the expressions to be a proxy,
     # but we don't want to create new proxies as a result of
     # evaluation, so we have to extend the list of types that
     # aren't proxied.
     self.c.unproxied_types = str, int, long, float
     for expr in self.unops:
         x = 1
         y = eval(expr)
         # Make sure 'x' is a proxy always:
         x = ProxyFactory(1, self.c)
         z = eval(expr)
         self.assertEqual(removeSecurityProxy(z), y,
                          "x=%r; expr=%r" % (x, expr))
         self.shouldFail(lambda x: eval(expr), x)
Ejemplo n.º 30
0
    def getSliceFromMemo(self, size, memo):
        """Return a result set for the given memo values.

        Note that at least two other implementations are possible:
        Instead of OR-combining the expressions returned by
        whereExpressions(), these expressions could be used for
        separate SELECTs which are then merged with UNION ALL.

        We could also issue separate Storm queries for each
        expression and combine the results here.

        Which variant is more efficient is yet unknown; it may
        differ between different queries.
        """
        sort_expressions = self.getOrderBy()
        where = self.whereExpressions(sort_expressions, memo)
        where = reduce(Or, where)
        # From storm.zope.interfaces.IResultSet.__doc__:
        #     - C{find()}, C{group_by()} and C{having()} are really
        #       used to configure result sets, so are mostly intended
        #       for use on the model side.
        naked_result = removeSecurityProxy(self.resultset).find(where)
        result = ProxyFactory(naked_result)
        return result.config(limit=size)
 def test_write_to_subscribers(self):
     """`BugSubscriptionFilter`s can only be modifed by subscribers."""
     bug_subscription_filter = BugSubscriptionFilter()
     bug_subscription_filter.structural_subscription = self.subscription
     bug_subscription_filter = ProxyFactory(bug_subscription_filter)
     # The subscriber can edit the filter.
     with person_logged_in(self.subscriber):
         bug_subscription_filter.find_all_tags = True
     # Any other person is denied rights to edit the filter.
     with person_logged_in(self.factory.makePerson()):
         self.assertRaises(Unauthorized, setattr, bug_subscription_filter,
                           "find_all_tags", True)
     # Anonymous users are also denied.
     with anonymous_logged_in():
         self.assertRaises(Unauthorized, setattr, bug_subscription_filter,
                           "find_all_tags", True)
 def test_delete_by_subscribers(self):
     """`BugSubscriptionFilter`s can only be deleted by subscribers."""
     bug_subscription_filter = BugSubscriptionFilter()
     bug_subscription_filter.structural_subscription = self.subscription
     bug_subscription_filter = ProxyFactory(bug_subscription_filter)
     # Anonymous users are denied rights to delete the filter.
     with anonymous_logged_in():
         self.assertRaises(Unauthorized, getattr, bug_subscription_filter,
                           "delete")
     # Any other person is also denied.
     with person_logged_in(self.factory.makePerson()):
         self.assertRaises(Unauthorized, getattr, bug_subscription_filter,
                           "delete")
     # The subscriber can delete the filter.
     with person_logged_in(self.subscriber):
         bug_subscription_filter.delete()
 def test_write_to_any_user_when_no_subscription(self):
     """
     `BugSubscriptionFilter`s can be modifed by any logged-in user when
     there is no related subscription.
     """
     bug_subscription_filter = BugSubscriptionFilter()
     bug_subscription_filter = ProxyFactory(bug_subscription_filter)
     # The subscriber can edit the filter.
     with person_logged_in(self.subscriber):
         bug_subscription_filter.find_all_tags = True
     # Any other person can edit the filter.
     with person_logged_in(self.factory.makePerson()):
         bug_subscription_filter.find_all_tags = True
     # Anonymous users are denied rights to edit the filter.
     with anonymous_logged_in():
         self.assertRaises(Unauthorized, setattr, bug_subscription_filter,
                           "find_all_tags", True)
Ejemplo n.º 34
0
    def testFactory(self):
        self.assertEqual(component.queryAdapter(request, name='index.html'),
                         None)

        xmlconfig(
            StringIO(template % '''
            <browser:resource
                name="index.html"
                factory="
                  zope.browserresource.tests.test_directives.MyResource"
                />
            '''))

        r = component.getAdapter(request, name='index.html')
        self.assertEquals(r.__class__, MyResource)
        r = ProxyFactory(r)
        self.assertEqual(r.__name__, "index.html")
Ejemplo n.º 35
0
    def publishTraverse(self, request, name):
        # this is the primary condition; traverse to ``name`` by
        # looking up methods on this class
        try:
            method = getattr(self.context, "get_%s" % name)
        except AttributeError:
            # fall back to default traversal (view lookup)
            def method():
                return super(SchedulingContextTraverser,
                             self).publishTraverse(request, name)

        obj = method()
        assert ILocation.providedBy(obj), obj
        log.debug("SchedulingContextTraverser.publishTraverse: " \
            "self=%s context=%s name=%s obj=%s" % (self, self.context, name, obj))
        return ProxyFactory(
            LocationProxy(removeSecurityProxy(obj),
                          container=self.context,
                          name=name))
Ejemplo n.º 36
0
 def testAttributeProtectedView(self):
     xmlconfig.file("xmlrpc.zcml", xmlrpc.tests)
     v = component.getMultiAdapter((ob, request), name='test3')
     v = ProxyFactory(v)
     self.assertEqual(v.action(), 'done')
     self.assertRaises(Exception, getattr, v, 'index')
Ejemplo n.º 37
0
 def testInterfaceProtectedView(self):
     xmlconfig.file("xmlrpc.zcml", xmlrpc.tests)
     v = component.getMultiAdapter((ob, request), name='test2')
     v = ProxyFactory(v)
     self.assertEqual(v.index(), 'V1 here')
     self.assertRaises(Exception, getattr, v, 'action')
Ejemplo n.º 38
0
class ProxyTests(unittest.TestCase):

    def setUp(self):
        self.x = Something()
        self.c = Checker()
        self.p = ProxyFactory(self.x, self.c)

    def shouldFail(self, *args):
        self.c.ok = 0
        self.assertRaises(RuntimeError, *args)
        self.c.ok = 1

    def testDerivation(self):
        self.assert_(isinstance(self.p, proxy))

    def testStr(self):
        self.assertEqual(str(self.p), str(self.x))

        x = Something()
        c = Checker()
        c.ok = 0
        p = ProxyFactory(x, c)
        s = str(p)
        self.failUnless(s.startswith(
            "<security proxied %s.%s instance at"
            % (x.__class__.__module__, x.__class__.__name__)),
                        s)


    def testRepr(self):
        self.assertEqual(repr(self.p), repr(self.x))

        x = Something()
        c = Checker()
        c.ok = 0
        p = ProxyFactory(x, c)
        s = repr(p)
        self.failUnless(s.startswith(
            "<security proxied %s.%s instance at"
            % (x.__class__.__module__, x.__class__.__name__)),
                        s)

    def testGetAttrOK(self):
        self.assertEqual(removeSecurityProxy(self.p.foo), [1,2,3])

    def testGetAttrFail(self):
        self.assertRaises(RuntimeError, lambda: self.p.bar)

    def testSetAttrOK(self):
        self.p.foo = 42
        self.assertEqual(self.p.foo, 42)

    def testSetAttrFail(self):
        def doit(): self.p.bar = 42
        self.assertRaises(RuntimeError, doit)

    def testGetItemOK(self):
        self.assertEqual(self.p[0], 1)

    def testGetItemFail(self):
        self.shouldFail(lambda: self.p[10])

    def testSetItemOK(self):
        self.p[0] = 42
        self.assertEqual(self.p[0], 42)

    def testSetItemFail(self):
        def doit(): del self.p[0]
        self.shouldFail(doit)

    def testDelItemOK(self):
        self.p[0] = 42
        self.assertEqual(self.p[0], 42)
        del self.p[0]
        self.shouldFail(lambda: self.p[0])

    def testDelItemFail(self):
        def doit(): self.p[10] = 42
        self.shouldFail(doit)

    def testCallOK(self):
        self.assertEqual(self.p(None), 42)

    def testCallFail(self):
        self.shouldFail(self.p, None)

    def testRichCompareOK(self):
        self.failUnless(self.p == self.x)

    def testRichCompareFail(self):
        self.shouldFail(lambda: self.p == self.x)

    def testIterOK(self):
        self.assertEqual(removeSecurityProxy(iter(self.p)), self.x)

    def testIterFail(self):
        self.shouldFail(iter, self.p)

    def testNextOK(self):
        self.assertEqual(self.p.next(), 42)

    def testNextFail(self):
        self.shouldFail(self.p.next)

    def testCompareOK(self):
        self.assertEqual(cmp(self.p, self.x), 0)

    def testCompareFail(self):
        self.shouldFail(cmp, self.p, self.x)

    def testHashOK(self):
        self.assertEqual(hash(self.p), hash(self.x))

    def testHashFail(self):
        self.shouldFail(hash, self.p)

    def testNonzeroOK(self):
        self.assertEqual(not self.p, 0)

    def testNonzeroFail(self):
        self.shouldFail(lambda: not self.p)

    def testLenOK(self):
        self.assertEqual(len(self.p), 42)

    def testLenFail(self):
        self.shouldFail(len, self.p)

    def testSliceOK(self):
        self.assertEqual(removeSecurityProxy(self.p[:]), [42])

    def testSliceFail(self):
        self.shouldFail(lambda: self.p[:])

    def testSetSliceOK(self):
        self.p[:] = [42]

    def testSetSliceFail(self):
        def doit(): self.p[:] = [42]
        self.shouldFail(doit)

    def testContainsOK(self):
        self.failUnless(42 in self.p)

    def testContainsFail(self):
        self.shouldFail(lambda: 42 in self.p)

    def testGetObject(self):
        self.assertEqual(self.x, removeSecurityProxy(self.p))

    def testGetChecker(self):
        self.assertEqual(self.c, getChecker(self.p))

    def testProxiedClassicClassAsDictKey(self):
        class C(object):
            pass
        d = {C: C()}
        pC = ProxyFactory(C, self.c)
        self.assertEqual(d[pC], d[C])

    def testProxiedNewClassAsDictKey(self):
        class C(object):
            pass
        d = {C: C()}
        pC = ProxyFactory(C, self.c)
        self.assertEqual(d[pC], d[C])

    unops = [
        "-x", "+x", "abs(x)", "~x",
        "int(x)", "long(x)", "float(x)",
        ]

    def test_unops(self):
        # We want the starting value of the expressions to be a proxy,
        # but we don't want to create new proxies as a result of
        # evaluation, so we have to extend the list of types that
        # aren't proxied.
        self.c.unproxied_types = str, int, long, float
        for expr in self.unops:
            x = 1
            y = eval(expr)
            # Make sure 'x' is a proxy always:
            x = ProxyFactory(1, self.c)
            z = eval(expr)
            self.assertEqual(removeSecurityProxy(z), y,
                             "x=%r; expr=%r" % (x, expr))
            self.shouldFail(lambda x: eval(expr), x)

    def test_odd_unops(self):
        # unops that don't return a proxy
        P = self.c.proxy
        for func in hex, oct, lambda x: not x:
            self.assertEqual(func(P(100)), func(100))
            self.shouldFail(func, P(100))

    binops = [
        "x+y", "x-y", "x*y", "x/y", "divmod(x, y)", "x**y", "x//y",
        "x<<y", "x>>y", "x&y", "x|y", "x^y",
        ]

    def test_binops(self):
        P = self.c.proxy
        for expr in self.binops:
            first = 1
            for x in [1, P(1)]:
                for y in [2, P(2)]:
                    if first:
                        z = eval(expr)
                        first = 0
                    else:
                        self.assertEqual(removeSecurityProxy(eval(expr)), z,
                                         "x=%r; y=%r; expr=%r" % (x, y, expr))
                        self.shouldFail(lambda x, y: eval(expr), x, y)

    def test_inplace(self):
        # TODO: should test all inplace operators...
        P = self.c.proxy

        pa = P(1)
        pa += 2
        self.assertEqual(removeSecurityProxy(pa), 3)

        a = [1, 2, 3]
        pa = qa = P(a)
        pa += [4, 5, 6]
        self.failUnless(pa is qa)
        self.assertEqual(a, [1, 2, 3, 4, 5, 6])

        def doit():
            pa = P(1)
            pa += 2
        self.shouldFail(doit)

        pa = P(2)
        pa **= 2
        self.assertEqual(removeSecurityProxy(pa), 4)

        def doit():
            pa = P(2)
            pa **= 2
        self.shouldFail(doit)

    def test_coerce(self):
        P = self.c.proxy

        # Before 2.3, coerce() of two proxies returns them unchanged
        import sys
        fixed_coerce = sys.version_info >= (2, 3, 0)

        x = P(1)
        y = P(2)
        a, b = coerce(x, y)
        self.failUnless(a is x and b is y)

        x = P(1)
        y = P(2.1)
        a, b = coerce(x, y)
        self.failUnless(removeSecurityProxy(a) == 1.0 and b is y)
        if fixed_coerce:
            self.failUnless(type(removeSecurityProxy(a)) is float and b is y)

        x = P(1.1)
        y = P(2)
        a, b = coerce(x, y)
        self.failUnless(a is x and removeSecurityProxy(b) == 2.0)
        if fixed_coerce:
            self.failUnless(a is x and type(removeSecurityProxy(b)) is float)

        x = P(1)
        y = 2
        a, b = coerce(x, y)
        self.failUnless(a is x and b is y)

        x = P(1)
        y = 2.1
        a, b = coerce(x, y)
        self.failUnless(type(removeSecurityProxy(a)) is float and b is y)

        x = P(1.1)
        y = 2
        a, b = coerce(x, y)
        self.failUnless(a is x and type(removeSecurityProxy(b)) is float)

        x = 1
        y = P(2)
        a, b = coerce(x, y)
        self.failUnless(a is x and b is y)

        x = 1.1
        y = P(2)
        a, b = coerce(x, y)
        self.failUnless(a is x and type(removeSecurityProxy(b)) is float)

        x = 1
        y = P(2.1)
        a, b = coerce(x, y)
        self.failUnless(type(removeSecurityProxy(a)) is float and b is y)
Ejemplo n.º 39
0
 def setUp(self):
     self.x = Something()
     self.c = Checker()
     self.p = ProxyFactory(self.x, self.c)