testERP5Security.py 17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
##############################################################################
#
# Copyright (c) 2004 Nexedi SARL and Contributors. All Rights Reserved.
#                                    Jerome Perrin <jerome@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

"""Tests ERP5 User Management.
"""

32
import unittest
33

34 35
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                     get_request
36
from AccessControl.SecurityManagement import newSecurityManager
37
from AccessControl.SecurityManagement import getSecurityManager
38
from zLOG import LOG
39
from Products.ERP5Type.Cache import clearCache
40
from Products.PluggableAuthService import PluggableAuthService
41
try:
42
  from Interface.Verify import verifyClass
43
except ImportError:
44
  from zope.interface.verify import verifyClass
45
from DateTime import DateTime
46

47 48 49
class TestUserManagement(ERP5TypeTestCase):
  """Tests User Management in ERP5Security.
  """
50 51 52
  
  def getTitle(self):
    """Title of the test."""
53
    return "ERP5Security: User Management"
54 55 56 57 58
  
  def getBusinessTemplateList(self):
    """List of BT to install. """
    return ('erp5_base',)
  
59 60
  def beforeTearDown(self):
    """Clears person module and invalidate caches when tests are finished."""
61
    # XXX Isn't it better to clear the cache when deleting a Person ?
Romain Courteaud's avatar
Romain Courteaud committed
62
    clearCache(cache_factory_list=('erp5_content_short', ))
63 64 65 66 67
    self.getPersonModule().manage_delObjects([x for x in
                             self.getPersonModule().objectIds()])
    get_transaction().commit()
    self.tic()
  
68
  def login(self):
69
    uf = self.getUserFolder()
70 71 72 73
    uf._doAddUser('alex', '', ['Manager', 'Assignee', 'Assignor',
                               'Associate', 'Auditor', 'Author'], [])
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
74 75 76 77 78

  def getUserFolder(self):
    """Returns the acl_users. """
    return self.getPortal().acl_users

79
  def test_GroupManagerInterfaces(self):
80
    """Tests group manager plugin respects interfaces."""
81
    # XXX move to GroupManager test class
82 83 84 85
    from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin
    from Products.ERP5Security.ERP5GroupManager import ERP5GroupManager
    verifyClass(IGroupsPlugin, ERP5GroupManager)

86
  def test_UserManagerInterfaces(self):
87
    """Tests user manager plugin respects interfaces."""
88 89 90 91 92 93
    from Products.PluggableAuthService.interfaces.plugins import\
                IAuthenticationPlugin, IUserEnumerationPlugin
    from Products.ERP5Security.ERP5UserManager import ERP5UserManager
    verifyClass(IAuthenticationPlugin, ERP5UserManager)
    verifyClass(IUserEnumerationPlugin, ERP5UserManager)

94
  def test_UserFolder(self):
95
    """Tests user folder has correct meta type."""
96
    self.failUnless(isinstance(self.getUserFolder(),
97 98
        PluggableAuthService.PluggableAuthService))

99 100
  def _makePerson(self, open_assignment=1, assignment_start_date=None,
                  assignment_stop_date=None, **kw):
101 102
    """Creates a person in person module, and returns the object, after
    indexing is done. """
103 104
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
105
                     portal_type='Person', **kw)
106 107 108
    assignment = new_person.newContent(portal_type = 'Assignment',
                                       start_date=assignment_start_date,
                                       stop_date=assignment_stop_date,)
109 110
    if open_assignment:
      assignment.open()
111 112
    get_transaction().commit()
    self.tic()
113 114
    return new_person

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  def _assertUserExists(self, login, password):
    """Checks that a user with login and password exists and can log in to the
    system.
    """
    from Products.PluggableAuthService.interfaces.plugins import\
                                                      IAuthenticationPlugin
    uf = self.getUserFolder()
    self.assertNotEquals(uf.getUserById(login, None), None)
    for plugin_name, plugin in uf._getOb('plugins').listPlugins(
                                IAuthenticationPlugin ):
      if plugin.authenticateCredentials(
                  {'login':login, 'password':password}) is not None:
        break
    else:
      self.fail("No plugin could authenticate '%s' with password '%s'" %
              (login, password))
  
  def _assertUserDoesNotExists(self, login, password):
    """Checks that a user with login and password does not exists and cannot
    log in to the system.
    """
    from Products.PluggableAuthService.interfaces.plugins import\
                                                        IAuthenticationPlugin
    uf = self.getUserFolder()
    for plugin_name, plugin in uf._getOb('plugins').listPlugins(
                              IAuthenticationPlugin ):
      if plugin.authenticateCredentials(
                {'login':login, 'password':password}) is not None:
        self.fail(
           "Plugin %s should not have authenticated '%s' with password '%s'" %
           (plugin_name, login, password))

147
  def test_PersonWithLoginPasswordAreUsers(self):
148
    """Tests a person with a login & password is a valid user."""
149
    p = self._makePerson(reference='the_user', password='secret',)
150 151
    self._assertUserExists('the_user', 'secret')
    
152 153
  def test_PersonLoginCaseSensitive(self):
    """Login/password are case sensitive."""
154
    p = self._makePerson(reference='the_user', password='secret',)
155
    self._assertUserExists('the_user', 'secret')
156 157
    self._assertUserDoesNotExists('the_User', 'secret')
  
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  def test_PersonLoginIsNotStripped(self):
    """Make sure 'foo ', ' foo' and ' foo ' do not match user 'foo'. """
    p = self._makePerson(reference='foo', password='secret',)
    self._assertUserExists('foo', 'secret')
    self._assertUserDoesNotExists('foo ', 'secret')
    self._assertUserDoesNotExists(' foo', 'secret')
    self._assertUserDoesNotExists(' foo ', 'secret')

  def test_PersonLoginCannotBeComposed(self):
    """Make sure ZSQLCatalog keywords cannot be used at login time"""
    p = self._makePerson(reference='foo', password='secret',)
    self._assertUserExists('foo', 'secret')
    self._assertUserDoesNotExists('bar', 'secret')
    self._assertUserDoesNotExists('bar OR foo', 'secret')

173 174
  def test_PersonLoginNonAscii(self):
    """Login can contain non ascii chars."""
175
    p = self._makePerson(reference='j\xc3\xa9', password='secret',)
176 177 178
    self._assertUserExists('j\xc3\xa9', 'secret')

  def test_PersonWithLoginWithEmptyPasswordAreNotUsers(self):
179
    """Tests a person with a login but no password is not a valid user."""
180
    self._makePerson(reference='the_user')
181
    self._assertUserDoesNotExists('the_user', None)
182
    self._makePerson(reference='another_user', password='',)
183 184
    self._assertUserDoesNotExists('another_user', '')
  
185
  def test_PersonWithEmptyLoginAreNotUsers(self):
186
    """Tests a person with a login & password is a valid user."""
187
    self._makePerson(reference='', password='secret')
188 189
    self._assertUserDoesNotExists('', 'secret')
  
190 191
  def test_PersonWithLoginWithNotAssignmentAreNotUsers(self):
    """Tests a person with a login & password and no assignment open is not a valid user."""
192 193
    self._makePerson(reference='the_user', password='secret', open_assignment=0)
    self._assertUserDoesNotExists('the_user', 'secret')
194

195
  def test_PersonWithSuperUserLoginCannotBeCreated(self):
196 197 198 199
    """Tests one cannot create person with the "super user" special login."""
    from Products.ERP5Security.ERP5UserManager import SUPER_USER
    self.assertRaises(RuntimeError, self._makePerson, reference=SUPER_USER)
  
200
  def test_PersonWithSuperUserLogin(self):
201 202 203 204
    """Tests one cannot use the "super user" special login."""
    from Products.ERP5Security.ERP5UserManager import SUPER_USER
    self._assertUserDoesNotExists(SUPER_USER, '')

205
  def test_MultiplePersonReference(self):
206 207 208
    """Tests that it's refused to create two Persons with same reference."""
    self._makePerson(reference='new_person')
    self.assertRaises(RuntimeError, self._makePerson, reference='new_person')
209

210
  def test_PersonCopyAndPaste(self):
211 212 213 214 215 216 217
    """If we copy and paste a person, login must not be copyied."""
    person = self._makePerson(reference='new_person')
    person_module = self.getPersonModule()
    copy_data = person_module.manage_copyObjects([person.getId()])
    changed, = person_module.manage_pasteObjects(copy_data)
    self.assertNotEquals(person_module[changed['new_id']].getReference(),
                         person_module[changed['id']].getReference())
218
  
219 220 221 222 223 224 225 226 227 228 229 230
  def test_OpenningAssignmentClearCache(self):
    """Openning an assignment for a person clear the cache automatically."""
    pers = self._makePerson(reference='the_user', password='secret',
                            open_assignment=0)
    self._assertUserDoesNotExists('the_user', 'secret')
    assi = pers.newContent(portal_type='Assignment')
    assi.open()
    self._assertUserExists('the_user', 'secret')
    assi.close()
    self._assertUserDoesNotExists('the_user', 'secret')


231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  def test_AssignmentWithDate(self):
    """Tests a person with an assignment with correct date is a valid user."""
    date = DateTime()
    p = self._makePerson(reference='the_user', password='secret',
                         assignment_start_date=date-5,
                         assignment_stop_date=date+5)
    self._assertUserExists('the_user', 'secret')

  def test_AssignmentWithBadStartDate(self):
    """Tests a person with an assignment with bad start date is not a valid user."""
    date = DateTime()
    p = self._makePerson(reference='the_user', password='secret',
                         assignment_start_date=date+1,
                         assignment_stop_date=date+5)
    self._assertUserDoesNotExists('the_user', 'secret')

  def test_AssignmentWithBadStopDate(self):
    """Tests a person with an assignment with bad stop date is not a valid user."""
    date = DateTime()
    p = self._makePerson(reference='the_user', password='secret',
                         assignment_start_date=date-5,
                         assignment_stop_date=date-1)
    self._assertUserDoesNotExists('the_user', 'secret')

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
class TestLocalRoleManagement(ERP5TypeTestCase):
  """Tests Local Role Management with ERP5Security.

  This test should probably part of ERP5Type ?
  """
  def getTitle(self):
    return "ERP5Security: User Role Management"

  def afterSetUp(self):
    """Called after setup completed.
    """
    self.portal = self.getPortal()
    # configure group, site, function categories
    for bc in ['group', 'site', 'function']:
      base_cat = self.getCategoryTool()[bc]
      code = bc[0].upper()
      base_cat.newContent(portal_type='Category',
                          id='subcat',
                          codification="%s1" % code)
    self.defined_category = "group/subcat\n"\
                            "site/subcat\n"\
                            "function/subcat"
    # any member can add organisations
    self.portal.organisation_module.manage_permission(
            'Add portal content', roles=['Member', 'Manager'], acquire=1)

    self.username = 'username'
    # create a user and open an assignement
    pers = self.getPersonModule().newContent(portal_type='Person',
                                             reference=self.username,
                                             password=self.username)
    assignment = pers.newContent( portal_type='Assignment',
                                  group='subcat',
                                  site='subcat',
                                  function='subcat' )
    assignment.open()
    get_transaction().commit()
    self.tic()
  
  def beforeTearDown(self):
    """Called before teardown."""
    # clear base categories
    for bc in ['group', 'site', 'function']:
      base_cat = self.getCategoryTool()[bc]
      base_cat.manage_delObjects([x for x in base_cat.objectIds()])
    # clear role definitions
    for ti in self.getTypesTool().objectValues(spec=('ERP5 Type Information',)):
      ti._roles = ()
    # clear modules
    for module in self.portal.objectValues(spec=('ERP5 Folder',)):
      module.manage_delObjects([x for x in module.objectIds()])
    # commit this
    get_transaction().commit()
308
    self.tic()
309
    # XXX Isn't it better to clear the cache when deleting a Person ?
Romain Courteaud's avatar
Romain Courteaud committed
310
    clearCache(cache_factory_list=('erp5_content_short', ))
311 312 313 314 315 316 317 318 319

  def loginAsUser(self, username):
    uf = self.portal.acl_users
    user = uf.getUserById(username).__of__(uf)
    newSecurityManager(None, user)
  
  def _getTypeInfo(self):
    return self.getTypesTool()['Organisation']
  
320 321 322
  def _getModuleTypeInfo(self):
    return self.getTypesTool()['Organisation Module']
  
323 324 325 326 327 328 329
  def _makeOne(self):
    return self.getOrganisationModule().newContent(portal_type='Organisation')
  
  def getBusinessTemplateList(self):
    """List of BT to install. """
    return ('erp5_base',)
  
330 331 332 333 334 335
  def test_RolesManagerInterfaces(self):
    """Tests group manager plugin respects interfaces."""
    from Products.PluggableAuthService.interfaces.plugins import IRolesPlugin
    from Products.ERP5Security.ERP5RoleManager import ERP5RoleManager
    verifyClass(IRolesPlugin, ERP5RoleManager)

336 337 338 339 340 341 342 343
  def testMemberRole(self):
    """Test users have the Member role.
    """
    self.loginAsUser(self.username)
    self.failUnless('Member' in
            getSecurityManager().getUser().getRolesInContext(self.portal))
    self.failUnless('Member' in
            getSecurityManager().getUser().getRoles())
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  def testSimpleLocalRole(self):
    """Test simple case of setting a role.
    """
    ti = self._getTypeInfo()
    ti.addRole(id='Assignor', description='desc.',
           name='an Assignor role for testing',
           condition='',
           category=self.defined_category,
           base_category_script='ERP5Type_getSecurityCategoryFromAssignment',
           base_category='')
    obj = self._makeOne()
    self.assertEquals(['Assignor'], obj.__ac_local_roles__.get('F1_G1_S1'))
    
    self.loginAsUser(self.username)
    self.failUnless('Assignor' in
            getSecurityManager().getUser().getRolesInContext(obj))
        
  def testDynamicLocalRole(self):
    """Test simple case of setting a dynamic role.
    The site category is not defined explictly the role, and will have the
    current site of the user.
    """
    ti = self._getTypeInfo()
    ti.addRole(id='Assignor', description='desc.',
           name='an Assignor role for testing',
           condition='',
           category='group/subcat\nfunction/subcat',
           base_category_script='ERP5Type_getSecurityCategoryFromAssignment',
           base_category='site')
    
    self.loginAsUser(self.username)
    obj = self._makeOne()
    self.assertEquals(['Assignor'], obj.__ac_local_roles__.get('F1_G1_S1'))
    self.failUnless('Assignor' in
            getSecurityManager().getUser().getRolesInContext(obj))
380

381
  def testAcquireLocalRoles(self):
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    """Tests that document does not acquire loal roles from their parents if
    "acquire local roles" is not checked."""
    ti = self._getTypeInfo()
    ti.acquire_local_roles = False
    module_ti = self._getModuleTypeInfo()
    module_ti.addRole(id='Assignor', description='desc.',
           name='an Assignor role for testing',
           condition='',
           category=self.defined_category,
           base_category_script='ERP5Type_getSecurityCategoryFromAssignment',
           base_category='')
    obj = self._makeOne()
    module = obj.getParentValue()
    module.updateLocalRolesOnSecurityGroups()
    # we said the we do not want acquire local roles.
    self.failIf(obj._getAcquireLocalRoles())
    # the local role is set on the module
    self.assertEquals(['Assignor'], module.__ac_local_roles__.get('F1_G1_S1'))
    # but not on the document
    self.assertEquals(None, obj.__ac_local_roles__.get('F1_G1_S1'))
    # same testing with roles in context.
    self.loginAsUser(self.username)
    self.failUnless('Assignor' in
            getSecurityManager().getUser().getRolesInContext(module))
    self.failIf('Assignor' in
            getSecurityManager().getUser().getRolesInContext(obj))
408
    
409 410 411 412 413
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestUserManagement))
  suite.addTest(unittest.makeSuite(TestLocalRoleManagement))
  return suite
414