Commit 6c2435cf authored by Jérome Perrin's avatar Jérome Perrin

Support properties' read permission in the GUI and in getProperty

Because unlike `getFoo()`,  `getProperty('foo')` does not checks the permission defined on the accessor, when a form contain a `my_foo` field, the property would be displayed to the user who can view the form, even if the user does not actually have the permission to get this property. This because getter for default value of fields uses getProperty ( [here](https://lab.nexedi.com/nexedi/erp5/blob/58d4ab8efef748f522b3eaaecba3dc1133c99e72/product/ERP5Form/Form.py#L275) ).

These changes modify behavior of `getProperty`, so that it enforces read permission security of properties and raise when user does not have permission to access properties.

Some notes about implementation:
 * `getProperty` now becomes a bit slower, but it was incorrect before, so I guess it's inevitable.
 * some efforts have been made to keep the impact on performance minimal. This uses the same approach of  in `edit` of computing the set of restricted properties and using `guarded_getattr` only on these properties and using `getattr` on non-restricted properties. The computation of this set was moved  to dynamic class generation time and as a result, `edit` becomes a bit faster.
 * the `expectedFailure` part of `test_PropertySheetSecurityOnAccessors` was moved to another test, but I'm not even sure we want to support this (read-protecting properties with default write permission) as, to me, such configuration does not make much sense. 
 * new performance tests were added. I don't know what to use as min/max values so I just used something that should pass.
 * implementation for `getProperty('*_list')` was changed a lot, I have no idea why this was getting the method on the class and passing self as first argument. Now it we just get method on the instance, like we do for single properties.

/reviewed-on !181
parents 55351d08 16aa6134
...@@ -5,5 +5,6 @@ ...@@ -5,5 +5,6 @@
<portal_type id="Foo"> <portal_type id="Foo">
<item>Amount</item> <item>Amount</item>
<item>DublinCore</item> <item>DublinCore</item>
<item>Foo</item>
</portal_type> </portal_type>
</property_sheet_list> </property_sheet_list>
\ No newline at end of file
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Property Sheet" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_count</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAI=</string> </persistent>
</value>
</item>
<item>
<key> <string>_mt_index</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAM=</string> </persistent>
</value>
</item>
<item>
<key> <string>_tree</string> </key>
<value>
<persistent> <string encoding="base64">AAAAAAAAAAQ=</string> </persistent>
</value>
</item>
<item>
<key> <string>description</string> </key>
<value>
<none/>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>Foo</string> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Property Sheet</string> </value>
</item>
</dictionary>
</pickle>
</record>
<record id="2" aka="AAAAAAAAAAI=">
<pickle>
<global name="Length" module="BTrees.Length"/>
</pickle>
<pickle> <int>0</int> </pickle>
</record>
<record id="3" aka="AAAAAAAAAAM=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
<record id="4" aka="AAAAAAAAAAQ=">
<pickle>
<global name="OOBTree" module="BTrees.OOBTree"/>
</pickle>
<pickle>
<none/>
</pickle>
</record>
</ZopeData>
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="Standard Property" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>categories</string> </key>
<value>
<tuple>
<string>elementary_type/string</string>
</tuple>
</value>
</item>
<item>
<key> <string>description</string> </key>
<value> <string>A protected property for UI test. This is a property that only managers should be able to see and modify</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>protected_property_property</string> </value>
</item>
<item>
<key> <string>portal_type</string> </key>
<value> <string>Standard Property</string> </value>
</item>
<item>
<key> <string>read_permission</string> </key>
<value> <string>Manage portal</string> </value>
</item>
<item>
<key> <string>write_permission</string> </key>
<value> <string>Manage portal</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="ERP5 Form" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
</klass>
<tuple/>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary/>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_objects</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>action</string> </key>
<value> <string>Base_edit</string> </value>
</item>
<item>
<key> <string>description</string> </key>
<value> <string>View with some restricted properties</string> </value>
</item>
<item>
<key> <string>edit_order</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>enctype</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>group_list</string> </key>
<value>
<list>
<string>left</string>
<string>right</string>
<string>center</string>
<string>bottom</string>
<string>hidden</string>
</list>
</value>
</item>
<item>
<key> <string>groups</string> </key>
<value>
<dictionary>
<item>
<key> <string>bottom</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>center</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>hidden</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>left</string> </key>
<value>
<list>
<string>my_protected_property</string>
<string>my_foo_category_title</string>
</list>
</value>
</item>
<item>
<key> <string>right</string> </key>
<value>
<list/>
</value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>Foo_viewSecurity</string> </value>
</item>
<item>
<key> <string>method</string> </key>
<value> <string>POST</string> </value>
</item>
<item>
<key> <string>name</string> </key>
<value> <string>Foo_view</string> </value>
</item>
<item>
<key> <string>pt</string> </key>
<value> <string>form_view</string> </value>
</item>
<item>
<key> <string>row_length</string> </key>
<value> <int>4</int> </value>
</item>
<item>
<key> <string>stored_encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Foo Security</string> </value>
</item>
<item>
<key> <string>unicode_mode</string> </key>
<value> <int>0</int> </value>
</item>
<item>
<key> <string>update_action</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>update_action_title</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
Bar | Reference Bar | Reference
Foo | Amount Foo | Amount
Foo | DublinCore Foo | DublinCore
Foo | Foo
\ No newline at end of file
...@@ -45,7 +45,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup): ...@@ -45,7 +45,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup):
parent_delivery = self._getParentDelivery(movement) parent_delivery = self._getParentDelivery(movement)
if parent_delivery is not None: if parent_delivery is not None:
for prop in self.getTestedPropertyList(): for prop in self.getTestedPropertyList():
property_dict['_%s' % prop] = self._getProperty(parent_delivery, prop) property_dict['_%s' % prop] = self._getPropertyFromDocument(parent_delivery, prop)
return property_dict return property_dict
def test(self, document, property_dict, property_list=None, **kw): def test(self, document, property_dict, property_list=None, **kw):
...@@ -64,7 +64,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup): ...@@ -64,7 +64,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup):
return False, {} return False, {}
document = self._getParentDelivery(movement) document = self._getParentDelivery(movement)
for prop in target_property_list: for prop in target_property_list:
if property_dict['_%s' % prop] != self._getProperty(document, prop): if property_dict['_%s' % prop] != self._getPropertyFromDocument(document, prop):
return False, {} return False, {}
return True, {} return True, {}
...@@ -78,7 +78,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup): ...@@ -78,7 +78,7 @@ class ParentDeliveryPropertyMovementGroup(PropertyMovementGroup):
delivery = movement.getDeliveryValue() delivery = movement.getDeliveryValue()
return delivery return delivery
def _getProperty(self, document, property_id): def _getPropertyFromDocument(self, document, property_id):
if document is None: if document is None:
return None return None
# XXX here we don't use Base.getProperty() but try to call accessor # XXX here we don't use Base.getProperty() but try to call accessor
......
...@@ -565,6 +565,12 @@ class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin): ...@@ -565,6 +565,12 @@ class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin):
return self._v_version_priority_name_list return self._v_version_priority_name_list
# Make sure ERP5Site follow same API as Products.ERP5Type.Base
# _getProperty is missing, but since there are no protected properties
# on an ERP5 Site, we can just use getProperty instead.
_getProperty = CMFSite.getProperty
security.declareProtected(Permissions.AccessContentsInformation, 'getUid') security.declareProtected(Permissions.AccessContentsInformation, 'getUid')
def getUid(self): def getUid(self):
""" """
......
...@@ -33,6 +33,7 @@ import unittest ...@@ -33,6 +33,7 @@ import unittest
import httplib import httplib
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from Acquisition import aq_base
from DateTime import DateTime from DateTime import DateTime
from _mysql_exceptions import ProgrammingError from _mysql_exceptions import ProgrammingError
from OFS.ObjectManager import ObjectManager from OFS.ObjectManager import ObjectManager
...@@ -44,6 +45,8 @@ from Testing import ZopeTestCase ...@@ -44,6 +45,8 @@ from Testing import ZopeTestCase
from zLOG import LOG from zLOG import LOG
class IndexableDocument(ObjectManager): class IndexableDocument(ObjectManager):
# This tests uses a simple ObjectManager, but ERP5Catalog only
# support classes inherting from ERP5Type.Base.
# this property is required for dummy providesIMovement # this property is required for dummy providesIMovement
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
...@@ -66,6 +69,11 @@ class IndexableDocument(ObjectManager): ...@@ -66,6 +69,11 @@ class IndexableDocument(ObjectManager):
return lambda: 0 return lambda: 0
raise AttributeError, name raise AttributeError, name
def getProperty(self, prop, default=None):
return getattr(aq_base(self), prop, default)
_getProperty = getProperty
def getPath(self): def getPath(self):
return self._path return self._path
......
...@@ -28,21 +28,14 @@ ...@@ -28,21 +28,14 @@
############################################################################## ##############################################################################
import unittest
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from zLOG import LOG
from Products.ERP5Type.tests.Sequence import SequenceList from Products.ERP5Type.tests.Sequence import SequenceList
from Testing import ZopeTestCase
from DateTime import DateTime
class TestGUISecurity(ERP5TypeTestCase): class TestGUISecurity(ERP5TypeTestCase):
""" """
""" """
quiet = 0
run_all_test = 1
def getBusinessTemplateList(self): def getBusinessTemplateList(self):
return ('erp5_ui_test', 'erp5_base') return ('erp5_ui_test', 'erp5_base')
...@@ -50,15 +43,6 @@ class TestGUISecurity(ERP5TypeTestCase): ...@@ -50,15 +43,6 @@ class TestGUISecurity(ERP5TypeTestCase):
def getTitle(self): def getTitle(self):
return "Security Issues in GUI" return "Security Issues in GUI"
def afterSetUp(self):
self.login()
def login(self):
uf = self.getPortal().acl_users
uf._doAddUser('seb', '', ['Manager'], [])
user = uf.getUserById('seb').__of__(uf)
newSecurityManager(None, user)
def loginAs(self, id='user'): def loginAs(self, id='user'):
uf = self.getPortal().acl_users uf = self.getPortal().acl_users
user = uf.getUser(id).__of__(uf) user = uf.getUser(id).__of__(uf)
...@@ -66,35 +50,51 @@ class TestGUISecurity(ERP5TypeTestCase): ...@@ -66,35 +50,51 @@ class TestGUISecurity(ERP5TypeTestCase):
def stepCreateObjects(self, sequence = None, sequence_list = None, **kw): def stepCreateObjects(self, sequence = None, sequence_list = None, **kw):
# Make sure that the status is clean. # Make sure that the status is clean.
portal = self.getPortal() self.portal.ListBoxZuite_reset()
portal.ListBoxZuite_reset() message = self.portal.foo_module.FooModule_createObjects()
message = portal.foo_module.FooModule_createObjects()
self.assertTrue('Created Successfully' in message) self.assertTrue('Created Successfully' in message)
if not hasattr(portal.person_module, 'user'): if not hasattr(self.portal.person_module, 'user'):
user = portal.person_module.newContent(portal_type='Person', id='user', reference='user') user = self.portal.person_module.newContent(portal_type='Person', id='user', reference='user')
user.newContent(portal_type='ERP5 Login', reference='user').validate() user.newContent(portal_type='ERP5 Login', reference='user').validate()
asg = user.newContent(portal_type='Assignment') user.newContent(portal_type='Assignment').open()
asg.setStartDate(DateTime() - 100)
asg.setStopDate(DateTime() + 100)
asg.open()
self.commit()
def stepCreateTestFoo(self, sequence = None, sequence_list = None, **kw): def stepCreateTestFoo(self, sequence = None, sequence_list = None, **kw):
foo_module = self.getPortal().foo_module foo_module = self.portal.foo_module
foo_module.newContent(portal_type='Foo', id='foo', foo_category='a') foo_module.newContent(portal_type='Foo', id='foo', foo_category='a', protected_property='Protected Property')
# allow Member to view foo_module in a hard coded way as it is not required to setup complex # allow Member to view foo_module in a hard coded way as it is not required to setup complex
# security for this test (by default only 5A roles + Manager can view default modules) # security for this test (by default only 5A roles + Manager can view default modules)
args = (('Manager', 'Member', 'Assignor', 'Assignee', 'Auditor', 'Associate' ), 0) for permission in ('Access contents information', 'View'):
foo_module.manage_permission('Access contents information', *args) foo_module.manage_permission(
foo_module.manage_permission('View', *args) permission,
self.commit() ('Manager', 'Member', 'Assignor', 'Assignee', 'Auditor', 'Associate' ),
0)
def stepAccessFoo(self, sequence = None, sequence_list = None, **kw): def stepAccessFooDoesNotRaise(self, sequence = None, sequence_list = None, **kw):
""" """
Try to view the Foo_view form, make sure Unauthorized is not raised. Try to view the Foo_view form, make sure Unauthorized is not raised.
""" """
self.loginAs() self.loginAs()
self.getPortal().foo_module.foo.Foo_view() self.portal.foo_module.foo.Foo_view()
self.login()
def stepAccessFooDisplaysCategoryName(self, sequence = None, sequence_list = None, **kw):
"""
Try to view the Foo_view form, make sure our category name is displayed
"""
self.loginAs()
self.assertIn(
self.category_field_markup,
self.portal.foo_module.foo.Foo_view())
self.login()
def stepAccessFooDoesNotDisplayCategoryName(self, sequence = None, sequence_list = None, **kw):
"""
Try to view the Foo_view form, make sure our category name is not displayed
"""
self.loginAs()
self.assertNotIn(
self.category_field_markup,
self.portal.foo_module.foo.Foo_view())
self.login() self.login()
def stepChangeCategorySecurity(self, sequence = None, sequence_list = None, **kw): def stepChangeCategorySecurity(self, sequence = None, sequence_list = None, **kw):
...@@ -102,30 +102,23 @@ class TestGUISecurity(ERP5TypeTestCase): ...@@ -102,30 +102,23 @@ class TestGUISecurity(ERP5TypeTestCase):
here we change security of a category to which the "Foo" is related here we change security of a category to which the "Foo" is related
and which is displayed in the Foo's RelationStringField and which is displayed in the Foo's RelationStringField
""" """
category = self.getPortal().portal_categories.foo_category.a category = self.portal.portal_categories.foo_category.a
args = (('Manager',), 0) for permission in ('Access contents information', 'View'):
category.manage_permission('Access contents information', *args) category.manage_permission(permission, ('Manager',), 0 )
category.manage_permission('View', *args)
self.tic()
def stepResetCategorySecurity(self, sequence = None, sequence_list = None, **kw): def stepResetCategorySecurity(self, sequence = None, sequence_list = None, **kw):
""" """
reset it back reset it back
""" """
category = self.getPortal().portal_categories.foo_category.a category = self.portal.portal_categories.foo_category.a
args = ((), 1) for permission in ('Access contents information', 'View'):
category.manage_permission('Access contents information', *args) category.manage_permission(permission, ('Manager',), 1)
category.manage_permission('View', *args)
self.tic()
def test_01_relationFieldToInaccessibleObject(self, quiet=quiet, run=run_all_test): def test_01_relationFieldToInaccessibleObject(self):
""" """
This test checks if a form can be viewed when it contains a RelationStringField which This test checks if a form can be viewed when it contains a RelationStringField which
links to an object the user is not authorized to view. links to an object the user is not authorized to view.
This fails for now. A proposed patch solving this problem is here:
http://svn.erp5.org/experimental/FSPatch/Products/ERP5Form/ERP5Form_safeRelationField.diff?view=markup
This problem can happen for example in the following situation: This problem can happen for example in the following situation:
- a user is a member of a project P team, so he can view P - a user is a member of a project P team, so he can view P
- the user creates a project-related document and leaves it in "draft" state - the user creates a project-related document and leaves it in "draft" state
...@@ -133,29 +126,39 @@ class TestGUISecurity(ERP5TypeTestCase): ...@@ -133,29 +126,39 @@ class TestGUISecurity(ERP5TypeTestCase):
Then the user can not view the project, but still can view his document as he is the owner. Then the user can not view the project, but still can view his document as he is the owner.
An attempt to view the document form would raise Unauthorized. An attempt to view the document form would raise Unauthorized.
""" """
self.login() # this really depends on the generated markup
if not run: return self.category_field_markup = '<input name="field_my_foo_category_title" value="a" type="text"'
if not quiet:
message = 'test_01_relationFieldToInaccessibleObject'
ZopeTestCase._print('\n%s ' % message)
LOG('Testing... ', 0, message)
sequence_list = SequenceList() sequence_list = SequenceList()
sequence_string = '\ sequence_string = '\
CreateObjects \ CreateObjects \
CreateTestFoo \ CreateTestFoo \
Tic \ Tic \
AccessFoo \ AccessFooDoesNotRaise \
AccessFooDisplaysCategoryName \
ChangeCategorySecurity \ ChangeCategorySecurity \
AccessFoo \ Tic \
AccessFooDoesNotRaise \
AccessFooDoesNotDisplayCategoryName \
ResetCategorySecurity \ ResetCategorySecurity \
AccessFoo \ Tic \
AccessFooDoesNotRaise \
' '
sequence_list.addSequenceString(sequence_string) sequence_list.addSequenceString(sequence_string)
sequence_list.play(self, quiet=quiet) sequence_list.play(self)
def test_read_permission_property(self):
"""
This test checks that property defined with a `read_property` that the
logged in user does not have are not displayed.
"""
self.login() # as manager
self.stepCreateObjects()
self.stepCreateTestFoo()
protected_property_markup = '<input name="field_my_protected_property" value="Protected Property" type="text"'
self.assertIn(protected_property_markup, self.portal.foo_module.foo.Foo_viewSecurity())
def test_suite(): self.loginAs() # user without permission to access protected property
suite = unittest.TestSuite() self.assertNotIn(protected_property_markup, self.portal.foo_module.foo.Foo_viewSecurity())
suite.addTest(unittest.makeSuite(TestGUISecurity))
return suite
...@@ -67,6 +67,7 @@ from Products.ERP5Type.patches.CMFCoreSkinnable import SKINDATA, skinResolve ...@@ -67,6 +67,7 @@ from Products.ERP5Type.patches.CMFCoreSkinnable import SKINDATA, skinResolve
from Products.ERP5Type.Utils import UpperCase from Products.ERP5Type.Utils import UpperCase
from Products.ERP5Type.Utils import convertToUpperCase, convertToMixedCase from Products.ERP5Type.Utils import convertToUpperCase, convertToMixedCase
from Products.ERP5Type.Utils import createExpressionContext, simple_decorator from Products.ERP5Type.Utils import createExpressionContext, simple_decorator
from Products.ERP5Type.Utils import INFINITE_SET
from Products.ERP5Type.Accessor.Accessor import Accessor from Products.ERP5Type.Accessor.Accessor import Accessor
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
from Products.ERP5Type.Accessor.TypeDefinition import list_types from Products.ERP5Type.Accessor.TypeDefinition import list_types
...@@ -755,6 +756,10 @@ class Base( CopyContainer, ...@@ -755,6 +756,10 @@ class Base( CopyContainer,
aq_method_generating = [] aq_method_generating = []
aq_portal_type = {} aq_portal_type = {}
aq_related_generated = 0 aq_related_generated = 0
# These sets are generated when dynamically making a portal type class to
# short-cut guarded_getattr in edit/getProperty. For classes that are not
# dynamically generated from portal type, we always check security.
_restricted_getter_set = _restricted_setter_set = INFINITE_SET
# Only generateIdList may look at this property. Anything else is unsafe. # Only generateIdList may look at this property. Anything else is unsafe.
_id_generator_state = None _id_generator_state = None
...@@ -1216,11 +1221,29 @@ class Base( CopyContainer, ...@@ -1216,11 +1221,29 @@ class Base( CopyContainer,
If an accessor exists for this property, the accessor will be called, If an accessor exists for this property, the accessor will be called,
default value will be passed to the accessor as first positional argument. default value will be passed to the accessor as first positional argument.
""" """
kw['restricted'] = True
return self._getProperty(key, d=d, **kw)
def _getProperty(self, key, d=_MARKER, restricted=False, **kw):
__traceback_info__ = (key,) __traceback_info__ = (key,)
accessor_name = 'get' + UpperCase(key) accessor_name = 'get' + UpperCase(key)
# for restricted properties (ie. properties protected with another permission
# that AccessContentsInformation, which was already checked when calling this
# getProperty), we use guarded_getattr, other we use a simple getattr that
# is slightly faster.
_getattr = guarded_getattr \
if restricted and accessor_name in self.__class__._restricted_getter_set \
else getattr
aq_self = aq_base(self) aq_self = aq_base(self)
if getattr(aq_self, accessor_name, None) is not None: if getattr(aq_self, accessor_name, None) is not None:
method = getattr(self, accessor_name) try:
method = _getattr(self, accessor_name)
except Unauthorized:
if not kw.get('checked_permission'):
raise
return None if d is _MARKER else d
if d is not _MARKER: if d is not _MARKER:
try: try:
# here method is a method defined on the class, we don't know if the # here method is a method defined on the class, we don't know if the
...@@ -1234,16 +1257,21 @@ class Base( CopyContainer, ...@@ -1234,16 +1257,21 @@ class Base( CopyContainer,
# and return it as a list # and return it as a list
if accessor_name.endswith('List'): if accessor_name.endswith('List'):
mono_valued_accessor_name = accessor_name[:-4] mono_valued_accessor_name = accessor_name[:-4]
method = getattr(self.__class__, mono_valued_accessor_name, None) if hasattr(self.__class__, mono_valued_accessor_name):
if method is not None: try:
method = _getattr(self, mono_valued_accessor_name)
except Unauthorized:
if not kw.get('checked_permission'):
raise
return [] if d is _MARKER else d
# We have a monovalued property # We have a monovalued property
if d is _MARKER: if d is _MARKER:
result = method(self, **kw) result = method(**kw)
else: else:
try: try:
result = method(self, d, **kw) result = method(d, **kw)
except TypeError: except TypeError:
result = method(self, **kw) result = method(**kw)
if not isinstance(result, (list, tuple)): if not isinstance(result, (list, tuple)):
result = [result] result = [result]
return result return result
...@@ -1455,14 +1483,8 @@ class Base( CopyContainer, ...@@ -1455,14 +1483,8 @@ class Base( CopyContainer,
unordered_key_list = [k for k in key_list if k not in edit_order] unordered_key_list = [k for k in key_list if k not in edit_order]
ordered_key_list = [k for k in edit_order if k in key_list] ordered_key_list = [k for k in edit_order if k in key_list]
if restricted: if restricted:
# retrieve list of accessors which doesn't use default permissions # accessors which doesn't use default permissions
restricted_method_set = {method restricted_method_set = self.__class__._restricted_setter_set
for ancestor in self.__class__.mro()
for permissions in getattr(ancestor, '__ac_permissions__', ())
if permissions[0] not in ('Access contents information',
'Modify portal content')
for method in permissions[1]
if method.startswith('set')}
else: else:
restricted_method_set = () restricted_method_set = ()
...@@ -1497,7 +1519,7 @@ class Base( CopyContainer, ...@@ -1497,7 +1519,7 @@ class Base( CopyContainer,
accessor_name = 'set' + UpperCase(key) accessor_name = 'set' + UpperCase(key)
if accessor_name in restricted_method_set: if accessor_name in restricted_method_set:
# will raise Unauthorized when not allowed # will raise Unauthorized when not allowed
guarded_getattr(self, accessor_name) guarded_getattr(self, accessor_name, None)
modified_property_dict[key] = old_value modified_property_dict[key] = old_value
if key != 'id': if key != 'id':
modified_object_list = _setProperty(key, kw[key]) modified_object_list = _setProperty(key, kw[key])
...@@ -2654,13 +2676,13 @@ class Base( CopyContainer, ...@@ -2654,13 +2676,13 @@ class Base( CopyContainer,
reference_list = filt.get('reference', None) reference_list = filt.get('reference', None)
if not isinstance(reference_list, (list, tuple)): if not isinstance(reference_list, (list, tuple)):
reference_list = [reference_list] reference_list = [reference_list]
constraints = filter(lambda x:x.getProperty('reference') in \ constraints = filter(lambda x:x.getReference() in \
reference_list, constraints) reference_list, constraints)
if 'constraint_type' in filt: if 'constraint_type' in filt:
constraint_type_list = filt.get('constraint_type', None) constraint_type_list = filt.get('constraint_type', None)
if not isinstance(constraint_type_list, (list, tuple)): if not isinstance(constraint_type_list, (list, tuple)):
constraint_type_list = [constraint_type_list] constraint_type_list = [constraint_type_list]
constraints = filter(lambda x:x.__of__(self).getProperty('constraint_type') in \ constraints = filter(lambda x:x.__of__(self).getConstraintType() in \
constraint_type_list, constraints) constraint_type_list, constraints)
return constraints return constraints
...@@ -3576,9 +3598,10 @@ def removeIContentishInterface(cls): ...@@ -3576,9 +3598,10 @@ def removeIContentishInterface(cls):
removeIContentishInterface(Base) removeIContentishInterface(Base)
class TempBase(Base): class TempBase(Base):
""" """A version of Base that does not persist in ZODB.
If we need Base services (categories, edit, etc) in temporary objects
we shoud used TempBase This class only has the Base methods, so most of the times it is
preferable to use a temporary portal type instead.
""" """
isIndexable = ConstantGetter('isIndexable', value=False) isIndexable = ConstantGetter('isIndexable', value=False)
isTempDocument = ConstantGetter('isTempDocument', value=True) isTempDocument = ConstantGetter('isTempDocument', value=True)
...@@ -3627,3 +3650,27 @@ class TempBase(Base): ...@@ -3627,3 +3650,27 @@ class TempBase(Base):
# allow_class(TempBase) in ERP5Type/Document/__init__.py will trample our # allow_class(TempBase) in ERP5Type/Document/__init__.py will trample our
# ClassSecurityInfo with one that doesn't declare our public methods # ClassSecurityInfo with one that doesn't declare our public methods
InitializeClass(TempBase) InitializeClass(TempBase)
# TempBase is not a dynamic class, so it does not get _restricted_getter_set
# and _restricted_setter_set initialized ( this is only about
# Products.ERP5Type.Document.newTempBase , other temp objects are initialized ).
# Because TempBase.edit is public, there are existing cases in ERP5 code base
# where TempBase.edit is called on documents for which current user does not have
# modify portal content permission, so if we use the default behavior from Base,
# which is to check security for everything, some usages starts to raise Unauthorized.
# Also, these calls would becomes slower and the typical use case is to build a list
# of temp objects for a listbox, so we'd like to keep this fast.
TempBase._restricted_setter_set = {
method for ancestor in TempBase.mro()
for permissions in getattr(ancestor, '__ac_permissions__', ())
if permissions[0] not in (
Permissions.AccessContentsInformation,
Permissions.ModifyPortalContent)
for method in permissions[1] if method.startswith('set')
}
TempBase._restricted_getter_set = {
method for ancestor in TempBase.mro()
for permissions in getattr(ancestor, '__ac_permissions__', ())
if permissions[0] not in (Permissions.AccessContentsInformation, )
for method in permissions[1] if method.startswith('get')
}
...@@ -303,6 +303,10 @@ def cartesianProduct(list_of_list): ...@@ -303,6 +303,10 @@ def cartesianProduct(list_of_list):
append([v] + p) append([v] + p)
return result return result
# Emulate an infinite-set, ie. returning containing all objects.
# At this point we don't implement full API compatibility with set.
INFINITE_SET = type('INFINITE_SET', (object,), {'__contains__': lambda *args: True})()
# Some list operations # Some list operations
def keepIn(value_list, filter_list): def keepIn(value_list, filter_list):
# XXX this is [x for x in value_list if x in filter_list] # XXX this is [x for x in value_list if x in filter_list]
......
...@@ -322,6 +322,21 @@ def generatePortalTypeClass(site, portal_type_name): ...@@ -322,6 +322,21 @@ def generatePortalTypeClass(site, portal_type_name):
if portal_type_name in core_portal_type_class_dict: if portal_type_name in core_portal_type_class_dict:
core_portal_type_class_dict[portal_type_name]['generating'] = False core_portal_type_class_dict[portal_type_name]['generating'] = False
attribute_dict['_restricted_setter_set'] = {method
for ancestor in base_class_list
for permissions in getattr(ancestor, '__ac_permissions__', ())
if permissions[0] not in ('Access contents information',
'Modify portal content')
for method in permissions[1]
if method.startswith('set')}
attribute_dict['_restricted_getter_set'] = {method
for ancestor in base_class_list
for permissions in getattr(ancestor, '__ac_permissions__', ())
if permissions[0] not in ('Access contents information', )
for method in permissions[1]
if method.startswith('get')}
#LOG("ERP5Type.dynamic", INFO, #LOG("ERP5Type.dynamic", INFO,
# "Portal type %s loaded with bases %s" \ # "Portal type %s loaded with bases %s" \
# % (portal_type_name, repr(base_class_list))) # % (portal_type_name, repr(base_class_list)))
......
...@@ -30,12 +30,11 @@ from Products.ERP5Type.Globals import InitializeClass, PersistentMapping ...@@ -30,12 +30,11 @@ from Products.ERP5Type.Globals import InitializeClass, PersistentMapping
from Acquisition import aq_base from Acquisition import aq_base
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.ERP5Type.Utils import cartesianProduct from Products.ERP5Type.Utils import cartesianProduct, INFINITE_SET
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
from zLOG import LOG from zLOG import LOG
INFINITE_SET = type('', (object,), {'__contains__': lambda *args: True})()
class Matrix(object): class Matrix(object):
"""A mix-in class which provides a matrix like access to objects. """A mix-in class which provides a matrix like access to objects.
......
...@@ -57,7 +57,7 @@ def PropertyManager_hasProperty(self, id, local_properties=False): ...@@ -57,7 +57,7 @@ def PropertyManager_hasProperty(self, id, local_properties=False):
return 0 return 0
def PropertyManager_getProperty(self, id, d=None, evaluate=1, def PropertyManager_getProperty(self, id, d=None, evaluate=1,
local_properties=False): local_properties=False, checked_permission=None):
"""Get the property 'id', returning the optional second """Get the property 'id', returning the optional second
argument or None if no such property is found.""" argument or None if no such property is found."""
property_type = self.getPropertyType(id, property_type = self.getPropertyType(id,
......
...@@ -2676,8 +2676,6 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor): ...@@ -2676,8 +2676,6 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor):
self.assertFalse(guarded_hasattr(obj, 'getRegionValueList')) self.assertFalse(guarded_hasattr(obj, 'getRegionValueList'))
self.assertFalse(guarded_hasattr(obj, 'getRegionRelatedValueList')) self.assertFalse(guarded_hasattr(obj, 'getRegionRelatedValueList'))
# Permission definition on Accessor is buggy. TO BE FIXED!
@expectedFailure
def test_PropertySheetSecurityOnAccessors(self): def test_PropertySheetSecurityOnAccessors(self):
# Test accessors are protected correctly when you specify the permission # Test accessors are protected correctly when you specify the permission
# in the property sheet. # in the property sheet.
...@@ -2688,7 +2686,7 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor): ...@@ -2688,7 +2686,7 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor):
write_permission='Set own password', write_permission='Set own password',
read_permission='Manage users', read_permission='Manage users',
portal_type='Standard Property') portal_type='Standard Property')
obj = self.getPersonModule().newContent(portal_type='Person') obj = self.getPersonModule().newContent(portal_type='Person', foo_bar='value')
self.assertTrue(guarded_hasattr(obj, 'setFooBar')) self.assertTrue(guarded_hasattr(obj, 'setFooBar'))
self.assertTrue(guarded_hasattr(obj, 'getFooBar')) self.assertTrue(guarded_hasattr(obj, 'getFooBar'))
...@@ -2700,9 +2698,35 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor): ...@@ -2700,9 +2698,35 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor):
obj.manage_permission('Manage users', [], 0) obj.manage_permission('Manage users', [], 0)
self.assertTrue(guarded_hasattr(obj, 'setFooBar')) self.assertTrue(guarded_hasattr(obj, 'setFooBar'))
self.assertFalse(guarded_hasattr(obj, 'getFooBar')) self.assertFalse(guarded_hasattr(obj, 'getFooBar'))
# getProperty also raises
self.assertRaises(Unauthorized, obj.getProperty, 'foo_bar')
# ... unless called with checked_permission=
self.assertEqual(None,
obj.getProperty('foo_bar', checked_permission='Access content information'))
# When a document has protected properties, PropertyManager API does not
# "leak" protected properties when user cannot access.
self.assertRaises(Unauthorized, obj.propertyItems)
self.assertRaises(Unauthorized, obj.propertyValues)
# Other ERP5 APIs do not allow accessing private properties either.
self.assertRaises(Unauthorized, obj.asXML)
# Make sure that we can use 'Access contents information' as @expectedFailure
# write permission and 'Modify portal content' as read permission. def test_PropertySheetSecurityOnAccessors_nonstandard_permissions(self):
"""Make sure that we can use 'Access contents information' as
write permission and 'Modify portal content' as read permission.
note about the expectedFailure:
`Access contents information` and `Modify portal content` are
special cased and currently cannot be applied for other cases as
getter use access and setter use modify.
This is done in AccessorHolderType._skip_permission_set from
product/ERP5Type/dynamic/accessor_holder.py . Maybe we could be more
specific and define the skip permission on the accessor class, so that
we can define separatly the skipped permission for setter and getter.
For now I (Jerome) feel it's not important.
"""
self._addProperty('Person', self._addProperty('Person',
'test_PropertySheetSecurityOnAccessors', 'test_PropertySheetSecurityOnAccessors',
'hoge_hoge', 'hoge_hoge',
...@@ -2725,7 +2749,7 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor): ...@@ -2725,7 +2749,7 @@ class TestERP5Type(PropertySheetTestCase, LogInterceptor):
# Make sure that getProperty and setProperty respect accessor's # Make sure that getProperty and setProperty respect accessor's
# security protection. # security protection.
createZODBPythonScript(portal.portal_skins.custom, createZODBPythonScript(self.portal.portal_skins.custom,
'Base_callAccessorHogeHoge', 'Base_callAccessorHogeHoge',
'mode', 'mode',
'''\ '''\
...@@ -2736,7 +2760,7 @@ elif mode == 'getProperty': ...@@ -2736,7 +2760,7 @@ elif mode == 'getProperty':
elif mode == 'setter': elif mode == 'setter':
context.setHogeHoge('waa') context.setHogeHoge('waa')
elif mode == 'setProperty': elif mode == 'setProperty':
context.setProperty('waa') context.setProperty('hoge_hoge', 'waa')
return True''') return True''')
# test accessors # test accessors
obj.manage_permission('Access contents information', ['Manager'], 1) obj.manage_permission('Access contents information', ['Manager'], 1)
......
...@@ -31,6 +31,7 @@ from time import time ...@@ -31,6 +31,7 @@ from time import time
import gc import gc
import subprocess import subprocess
from zExceptions import Unauthorized
from DateTime import DateTime from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from zLOG import LOG from zLOG import LOG
...@@ -110,8 +111,13 @@ LISTBOX_COEF=0.00173 # 0.02472 ...@@ -110,8 +111,13 @@ LISTBOX_COEF=0.00173 # 0.02472
# LISTBOX_COEF : 0.02472 -> 0.001725 # LISTBOX_COEF : 0.02472 -> 0.001725
DO_TEST = 1 DO_TEST = 1
# Profiler support.
# set 1 to get profiler's result (unit_test/tests/<func_name>) # set 1 to get profiler's result (unit_test/tests/<func_name>)
PROFILE=0 PROFILE = 0
# set this to 'pprofile' to profile with pprofile ( https://github.com/vpelletier/pprofile )
# instad of python's standard library profiler ( https://docs.python.org/2/library/profile.html )
PROFILER = 'pprofile'
class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor): class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor):
...@@ -147,15 +153,26 @@ class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor): ...@@ -147,15 +153,26 @@ class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor):
""" """
return self.portal['bar_module'] return self.portal['bar_module']
def profile(self, func, suffix=''): def profile(self, func, suffix='', args=(), kw=None):
"""Profile `func(*args, **kw)` with selected profiler,
and dump output in a file called `func.__name__ + suffix`
"""
if not kw:
kw = {}
if PROFILER == 'pprofile':
import pprofile
prof = pprofile.Profile()
else:
from cProfile import Profile from cProfile import Profile
prof = Profile()
prof_file = '%s%s' % (func.__name__, suffix) prof_file = '%s%s' % (func.__name__, suffix)
try: try:
os.unlink(prof_file) os.unlink(prof_file)
except OSError: except OSError:
pass pass
prof = Profile() prof.runcall(func, *args, **kw)
prof.runcall(func)
prof.dump_stats(prof_file) prof.dump_stats(prof_file)
def beforeTearDown(self): def beforeTearDown(self):
...@@ -163,6 +180,7 @@ class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor): ...@@ -163,6 +180,7 @@ class TestPerformanceMixin(ERP5TypeTestCase, LogInterceptor):
gc.enable() gc.enable()
self.abort() self.abort()
class TestPerformance(TestPerformanceMixin): class TestPerformance(TestPerformanceMixin):
def getTitle(self): def getTitle(self):
...@@ -368,3 +386,75 @@ class TestPerformance(TestPerformanceMixin): ...@@ -368,3 +386,75 @@ class TestPerformance(TestPerformanceMixin):
MIN_OBJECT_MANY_LINES_VIEW, MIN_OBJECT_MANY_LINES_VIEW,
req_time, req_time,
MAX_OBJECT_MANY_LINES_VIEW)) MAX_OBJECT_MANY_LINES_VIEW))
class TestPropertyPerformance(TestPerformanceMixin):
def afterSetUp(self):
super(TestPerformanceMixin, self).afterSetUp()
self.foo = self.portal.foo_module.newContent(
portal_type='Foo',
title='Foo Test',
protected_property='Restricted Property',
)
# we will run the test as anonymous user. Setup permissions so that anymous can
# get and set all properties, except `protected_property` (unless test change to another user)
for permission in ('View', 'Access contents information', 'Modify portal content'):
self.foo.manage_permission(permission, ['Anonymous'], 1)
self.tic()
self.logout()
def _benchmark(self, nb_iterations, min_time, max_time):
def decorated(f):
before = time()
for i in xrange(nb_iterations):
f(i)
after = time()
total_time = (after - before) / 100.
print ("time %s.%s %.4f < %.4f < %.4f\n" % \
( self.id(),
f.__doc__ or f.__name__,
min_time,
total_time,
max_time ))
if PROFILE:
self.profile(f, args=(i, ))
if DO_TEST:
self.assertTrue(
min_time < total_time < max_time,
'%.4f < %.4f < %.4f' %
(min_time, total_time, max_time))
return decorated
def test_getProperty_protected_property_refused(self):
getProperty = self.foo.getProperty
self.assertRaises(Unauthorized, getProperty, 'protected_property')
@self._benchmark(100000, 0.0001, 1)
def getPropertyWithRestrictedPropertyRefused(_):
getProperty('protected_property', checked_permission='Access contents information')
def test_getProperty_protected_property_allowed(self):
getProperty = self.foo.getProperty
self.login()
@self._benchmark(100000, 0.0001, 1)
def getPropertyWithRestrictedPropertyAllowed(_):
getProperty('protected_property', checked_permission='Access contents information')
def test_getProperty_simple_property(self):
getProperty = self.foo.getProperty
@self._benchmark(100000, 0.0001, 1)
def getPropertyWithSimpleProperty(_):
getProperty('title', checked_permission='Access contents information')
def test_edit_restricted_properties(self):
_edit = self.foo.edit
self.login()
@self._benchmark(10000, 0.0001, 1)
def edit(i):
_edit(
title=str(i),
protected_property=str(i)
)
...@@ -1395,7 +1395,7 @@ class Catalog(Folder, ...@@ -1395,7 +1395,7 @@ class Catalog(Folder,
# objects but we could also use over multiple transactions # objects but we could also use over multiple transactions
# if this can improve performance significantly # if this can improve performance significantly
# ZZZ - we could find a way to compute this once only # ZZZ - we could find a way to compute this once only
cache_key = tuple(object.getProperty(key) for key cache_key = tuple(object._getProperty(key) for key
in expression_cache_key_list) in expression_cache_key_list)
try: try:
if expression_result_cache[cache_key]: if expression_result_cache[cache_key]:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment