testERP5Security.py 39.4 KB
Newer Older
1
# -*- coding: utf-8 -*-
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 32
# 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.
"""

33
import unittest
Nicolas Dumazet's avatar
Nicolas Dumazet committed
34
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
35
from Products.ERP5Type.tests.utils import createZODBPythonScript
36
from AccessControl.SecurityManagement import newSecurityManager
37
from AccessControl.SecurityManagement import getSecurityManager
38 39
from zLOG import LOG
from Products.PluggableAuthService import PluggableAuthService
40
from zope.interface.verify import verifyClass
41
from DateTime import DateTime
42

43 44 45
class TestUserManagement(ERP5TypeTestCase):
  """Tests User Management in ERP5Security.
  """
46

47 48
  def getTitle(self):
    """Title of the test."""
49
    return "ERP5Security: User Management"
50

51 52
  def getBusinessTemplateList(self):
    """List of BT to install. """
53
    return ('erp5_base',)
54

55 56 57 58 59
  def beforeTearDown(self):
    """Clears person module and invalidate caches when tests are finished."""
    self.getPersonModule().manage_delObjects([x for x in
                             self.getPersonModule().objectIds()])
    self.tic()
60

61
  def login(self):
62
    uf = self.getUserFolder()
63 64 65 66
    uf._doAddUser('alex', '', ['Manager', 'Assignee', 'Assignor',
                               'Associate', 'Auditor', 'Author'], [])
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
67 68 69 70 71

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

72
  def test_GroupManagerInterfaces(self):
73
    """Tests group manager plugin respects interfaces."""
74
    # XXX move to GroupManager test class
75 76 77 78
    from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin
    from Products.ERP5Security.ERP5GroupManager import ERP5GroupManager
    verifyClass(IGroupsPlugin, ERP5GroupManager)

79
  def test_UserManagerInterfaces(self):
80
    """Tests user manager plugin respects interfaces."""
81 82 83 84 85 86
    from Products.PluggableAuthService.interfaces.plugins import\
                IAuthenticationPlugin, IUserEnumerationPlugin
    from Products.ERP5Security.ERP5UserManager import ERP5UserManager
    verifyClass(IAuthenticationPlugin, ERP5UserManager)
    verifyClass(IUserEnumerationPlugin, ERP5UserManager)

87
  def test_UserFolder(self):
88
    """Tests user folder has correct meta type."""
89
    self.assertTrue(isinstance(self.getUserFolder(),
90 91
        PluggableAuthService.PluggableAuthService))

92 93 94 95 96
  def loginAsUser(self, username):
    uf = self.portal.acl_users
    user = uf.getUserById(username).__of__(uf)
    newSecurityManager(None, user)

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

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  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))
128

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  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))

144
  def test_PersonWithLoginPasswordAreUsers(self):
145
    """Tests a person with a login & password is a valid user."""
146
    p = self._makePerson(reference='the_user', password='secret',)
147
    self._assertUserExists('the_user', 'secret')
148

149 150
  def test_PersonLoginCaseSensitive(self):
    """Login/password are case sensitive."""
151
    p = self._makePerson(reference='the_user', password='secret',)
152
    self._assertUserExists('the_user', 'secret')
153
    self._assertUserDoesNotExists('the_User', 'secret')
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  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')

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  def test_PersonLoginQuote(self):
    p = self._makePerson(reference="'", password='secret',)
    self._assertUserExists("'", 'secret')

  def test_PersonLogin_OR_Keyword(self):
    p = self._makePerson(reference='foo OR bar', password='secret',)
    self._assertUserExists('foo OR bar', 'secret')
    self._assertUserDoesNotExists('foo', 'secret')

  def test_PersonLoginCatalogKeyWord(self):
    # use something that would turn the username in a ZSQLCatalog catalog keyword
    p = self._makePerson(reference="foo%", password='secret',)
    self._assertUserExists("foo%", 'secret')
    self._assertUserDoesNotExists("foo", 'secret')
    self._assertUserDoesNotExists("foobar", 'secret')

  def test_PersonLoginNGT(self):
    p = self._makePerson(reference='< foo', password='secret',)
    self._assertUserExists('< foo', 'secret')

190 191
  def test_PersonLoginNonAscii(self):
    """Login can contain non ascii chars."""
192
    p = self._makePerson(reference='j\xc3\xa9', password='secret',)
193 194 195
    self._assertUserExists('j\xc3\xa9', 'secret')

  def test_PersonWithLoginWithEmptyPasswordAreNotUsers(self):
196
    """Tests a person with a login but no password is not a valid user."""
197
    self._makePerson(reference='the_user')
198
    self._assertUserDoesNotExists('the_user', None)
199
    self._makePerson(reference='another_user', password='',)
200
    self._assertUserDoesNotExists('another_user', '')
201

202
  def test_PersonWithEmptyLoginAreNotUsers(self):
203
    """Tests a person with empty login & password is a valid user."""
204
    self._makePerson(reference='', password='secret')
205
    self._assertUserDoesNotExists('', 'secret')
206

207 208
  def test_PersonWithLoginWithNotAssignmentAreNotUsers(self):
    """Tests a person with a login & password and no assignment open is not a valid user."""
209 210
    self._makePerson(reference='the_user', password='secret', open_assignment=0)
    self._assertUserDoesNotExists('the_user', 'secret')
211

212
  def test_PersonWithSuperUserLoginCannotBeCreated(self):
213 214 215
    """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)
216

217
  def test_PersonWithSuperUserLogin(self):
218 219 220 221
    """Tests one cannot use the "super user" special login."""
    from Products.ERP5Security.ERP5UserManager import SUPER_USER
    self._assertUserDoesNotExists(SUPER_USER, '')

222 223 224
  def test_searchUsers(self):
    p1 = self._makePerson(reference='person1')
    p2 = self._makePerson(reference='person2')
225
    self.assertEqual(set(['person1', 'person2']),
226 227 228 229 230 231 232
      set([x['userid'] for x in
        self.portal.acl_users.searchUsers(id='person')]))

  def test_searchUsersExactMatch(self):
    p = self._makePerson(reference='person')
    p1 = self._makePerson(reference='person1')
    p2 = self._makePerson(reference='person2')
233
    self.assertEqual(['person', ],
234
         [x['userid'] for x in
235 236
           self.portal.acl_users.searchUsers(id='person', exact_match=True)])

237
  def test_MultiplePersonReference(self):
238 239 240
    """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')
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  def test_MultiplePersonReferenceWithoutCommit(self):
    """
    Tests that it's refused to create two Persons with same reference.
    Check if both persons are created in the same transaction
    """
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
                     portal_type='Person', reference='new_person')
    self.assertRaises(RuntimeError, person_module.newContent,
                     portal_type='Person', reference='new_person')

  def test_MultiplePersonReferenceWithoutTic(self):
    """
    Tests that it's refused to create two Persons with same reference.
    Check if both persons are created in 2 different transactions.
    """
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
                     portal_type='Person', reference='new_person')
261
    self.commit()
262 263 264 265 266 267
    self.assertRaises(RuntimeError, person_module.newContent,
                     portal_type='Person', reference='new_person')

  def test_MultiplePersonReferenceConcurrentTransaction(self):
    """
    Tests that it's refused to create two Persons with same reference.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
268
    Check if both persons are created in 2 concurrent transactions.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    For now, just verify that serialize is called on person_module.
    """
    class DummyTestException(Exception):
      pass

    def verify_serialize_call(self):
      # Check that serialize is called on person module
      if self.getRelativeUrl() == 'person_module':
        raise DummyTestException
      else:
        return self.serialize_call()

    # Replace serialize by a dummy method
    from Products.ERP5Type.Base import Base
    Base.serialize_call = Base.serialize
    Base.serialize = verify_serialize_call

    person_module = self.getPersonModule()
    try:
      self.assertRaises(DummyTestException, person_module.newContent,
                       portal_type='Person', reference='new_person')
    finally:
      Base.serialize = Base.serialize_call

293
  def test_PersonCopyAndPaste(self):
294 295 296 297 298 299 300
    """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())
301

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  def test_PreferenceTool_setNewPassword(self):
    # Preference Tool has an action to change password
    pers = self._makePerson(reference='the_user', password='secret',)
    self.tic()
    self._assertUserExists('the_user', 'secret')
    self.loginAsUser('the_user')
    self.portal.REQUEST.set('current_password', 'secret')
    self.portal.REQUEST.set('new_password', 'new_secret')
    self.portal.portal_preferences.PreferenceTool_setNewPassword()
    self._assertUserExists('the_user', 'new_secret')
    self._assertUserDoesNotExists('the_user', 'secret')

    # password is not stored in plain text
    self.assertNotEquals('new_secret', pers.getPassword())


318 319 320 321 322 323 324 325 326 327
  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')
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

  def test_PersonNotIndexedNotCached(self):
    pers = self._makePerson(password='secret',)
    pers.setReference('the_user')
    # not indexed yet
    self._assertUserDoesNotExists('the_user', 'secret')

    self.tic()

    self._assertUserExists('the_user', 'secret')

  def test_PersonNotValidNotCached(self):
    pers = self._makePerson(reference='the_user', password='other',)
    self._assertUserDoesNotExists('the_user', 'secret')
    pers.setPassword('secret')
    self._assertUserExists('the_user', 'secret')
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
  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')

370 371 372 373 374
  def test_DeletedPersonIsNotUser(self):
    p = self._makePerson(reference='the_user', password='secret')
    self._assertUserExists('the_user', 'secret')

    p.delete()
375
    self.commit()
376 377 378

    self._assertUserDoesNotExists('the_user', 'secret')

379 380 381 382 383
  def test_ReallyDeletedPersonIsNotUser(self):
    p = self._makePerson(reference='the_user', password='secret')
    self._assertUserExists('the_user', 'secret')

    p.getParentValue().deleteContent(p.getId())
384
    self.commit()
385 386 387

    self._assertUserDoesNotExists('the_user', 'secret')

388
  def test_InvalidatedPersonIsUser(self):
389 390 391 392 393
    p = self._makePerson(reference='the_user', password='secret')
    self._assertUserExists('the_user', 'secret')

    p.validate()
    p.invalidate()
394
    self.commit()
395

396
    self._assertUserExists('the_user', 'secret')
397

398 399
  def test_PersonLoginIsPossibleToUnset(self):
    """Make sure that it is possible to remove reference"""
400 401
    person = self._makePerson(reference='foo', password='secret',)
    person.setReference(None)
402 403 404
    self.tic()
    self.assertEqual(None, person.getReference())

405
class TestUserManagementExternalAuthentication(TestUserManagement):
406 407 408 409
  def getTitle(self):
    """Title of the test."""
    return "ERP5Security: User Management with External Authentication plugin"

410 411 412 413 414 415 416 417 418 419 420 421 422
  def afterSetUp(self):
    self.user_id_key = 'openAMid'
    # add key authentication PAS plugin
    uf = self.portal.acl_users
    plugin_id = 'erp5_external_authentication_plugin'
    if plugin_id not in uf.objectIds():
      uf.manage_addProduct['ERP5Security'].addERP5ExternalAuthenticationPlugin(
        id=plugin_id, \
        title='ERP5 External Authentication Plugin',\
        user_id_key=self.user_id_key,)

      getattr(uf, plugin_id).manage_activateInterfaces(
        interfaces=['IExtractionPlugin'])
423
      self.tic()
424 425 426 427 428 429 430 431 432 433 434 435

  def testERP5ExternalAuthenticationPlugin(self):
    """
     Make sure that we can grant security using a ERP5 External Authentication Plugin.
    """

    reference = 'external_auth_person'
    loginable_person = self.getPersonModule().newContent(portal_type='Person',
                                                         reference=reference,
                                                         password='guest')
    assignment = loginable_person.newContent(portal_type='Assignment')
    assignment.open()
436
    self.tic()
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

    base_url = self.portal.absolute_url(relative=1)

    # without key we are Anonymous User so we should be redirected with proper HTML
    # status code to login_form
    response = self.publish(base_url)
    self.assertEqual(response.getStatus(), 302)
    # TODO we should not have redirect but output 403 or 404, because
    # login process should be provided by an external application.
    # self.assertTrue('location' in response.headers.keys())
    # self.assertTrue(response.headers['location'].endswith('login_form'))

    # view front page we should be logged in if we use authentication key
    response = self.publish(base_url, env={self.user_id_key.replace('-', '_').upper():reference})
    self.assertEqual(response.getStatus(), 200)
    self.assertTrue(reference in response.getBody())


455 456 457 458 459 460 461 462 463 464 465 466
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()
467 468 469 470 471 472 473 474 475 476
    # create a security configuration script
    skin_folder = self.portal.portal_skins.custom
    if 'ERP5Type_getSecurityCategoryMapping' not in skin_folder.objectIds():
      createZODBPythonScript(
        skin_folder, 'ERP5Type_getSecurityCategoryMapping', '',
        """return ((
          'ERP5Type_getSecurityCategoryFromAssignment',
          context.getPortalObject().getPortalAssignmentBaseCategoryList()
          ),)
        """)
477
    # configure group, site, function categories
478
    category_tool = self.getCategoryTool()
479
    for bc in ['group', 'site', 'function']:
480
      base_cat = category_tool[bc]
481
      code = bc[0].upper()
482 483
      if base_cat.get('subcat', None) is not None:
        continue
484 485 486
      base_cat.newContent(portal_type='Category',
                          id='subcat',
                          codification="%s1" % code)
487
    # add another function subcategory.
488
    function_category = category_tool['function']
489
    if function_category.get('another_subcat', None) is None:
490 491 492
      function_category.newContent(portal_type='Category',
                                   id='another_subcat',
                                   codification='F2')
493 494 495 496 497 498 499
    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)

Romain Courteaud's avatar
Romain Courteaud committed
500
    self.username = 'usérn@me'
501 502 503 504 505 506 507 508 509
    # 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()
510
    self.person = pers
511
    self.tic()
512

513 514 515
  def beforeTearDown(self):
    """Called before teardown."""
    # clear base categories
516
    self.person.getParentValue().manage_delObjects([self.person.getId()])
517 518
    for bc in ['group', 'site', 'function']:
      base_cat = self.getCategoryTool()[bc]
519
      base_cat.manage_delObjects(list(base_cat.objectIds()))
520
    # clear role definitions
521
    for ti in self.getTypesTool().objectValues():
522
      ti.manage_delObjects([x.id for x in ti.getRoleInformationList()])
523
    # clear modules
524 525 526
    for module in self.portal.objectValues():
      if module.getId().endswith('_module'):
        module.manage_delObjects(list(module.objectIds()))
527
    # commit this
528
    self.tic()
529 530 531 532 533

  def loginAsUser(self, username):
    uf = self.portal.acl_users
    user = uf.getUserById(username).__of__(uf)
    newSecurityManager(None, user)
534

535 536
  def _getTypeInfo(self):
    return self.getTypesTool()['Organisation']
537

538 539
  def _getModuleTypeInfo(self):
    return self.getTypesTool()['Organisation Module']
540

541 542
  def _makeOne(self):
    return self.getOrganisationModule().newContent(portal_type='Organisation')
543

544 545
  def getBusinessTemplateList(self):
    """List of BT to install. """
546
    return ('erp5_base', 'erp5_web', 'erp5_ingestion', 'erp5_dms',)
547

548 549 550 551 552 553
  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)

554 555 556 557
  def testMemberRole(self):
    """Test users have the Member role.
    """
    self.loginAsUser(self.username)
558
    self.assertTrue('Member' in
559
            getSecurityManager().getUser().getRolesInContext(self.portal))
560
    self.assertTrue('Member' in
561
            getSecurityManager().getUser().getRoles())
562

563 564 565
  def testSimpleLocalRole(self):
    """Test simple case of setting a role.
    """
566 567 568 569
    self._getTypeInfo().newContent(portal_type='Role Information',
      role_name='Assignor',
      description='desc.',
      title='an Assignor role for testing',
570
      role_category=self.defined_category)
571
    self.loginAsUser(self.username)
572 573 574 575 576 577
    user = getSecurityManager().getUser()

    obj = self._makeOne()
    self.assertEqual(['Assignor'], obj.__ac_local_roles__.get('F1_G1_S1'))
    self.assertTrue('Assignor' in user.getRolesInContext(obj))
    self.assertFalse('Assignee' in user.getRolesInContext(obj))
578
    self.abort()
579

580 581 582
  def testLocalRolesGroupId(self):
    """Assigning a role with local roles group id.
    """
583 584 585 586
    self.portal.portal_categories.local_role_group.newContent(
      portal_type='Category', 
      reference = 'Alternate',
      id = 'Alternate')
587 588
    self._getTypeInfo().newContent(portal_type='Role Information',
      role_name='Assignor',
589
      local_role_group_value=self.portal.portal_categories.local_role_group.Alternate.getRelativeUrl(),      
590 591 592 593 594 595 596 597
      role_category=self.defined_category)

    self.loginAsUser(self.username)
    user = getSecurityManager().getUser()

    obj = self._makeOne()
    self.assertEqual(['Assignor'], obj.__ac_local_roles__.get('F1_G1_S1'))
    self.assertTrue('Assignor' in user.getRolesInContext(obj))
598
    self.assertEqual(set([('F1_G1_S1', 'Assignor')]),
599
      obj.__ac_local_roles_group_id_dict__.get('Alternate'))
600
    self.abort()
601 602


603 604 605 606 607
  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.
    """
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    for role, function in (('Assignee', 'subcat'),
                           ('Assignor', 'another_subcat')):
      self._getTypeInfo().newContent(portal_type='Role Information',
        role_name=role,
        title='an Assignor role for testing',
        role_category_list=('group/subcat', 'function/' + function),
        role_base_category_script_id='ERP5Type_getSecurityCategoryFromAssignment',
        role_base_category='site')
    self.loginAsUser(self.username)
    user = getSecurityManager().getUser()

    obj = self._makeOne()
    self.assertEqual(['Assignee'], obj.__ac_local_roles__.get('F1_G1_S1'))
    self.assertEqual(['Assignor'], obj.__ac_local_roles__.get('F2_G1_S1'))
    self.assertTrue('Assignee' in user.getRolesInContext(obj))
    self.assertFalse('Assignor' in user.getRolesInContext(obj))
624
    self.abort()
625 626 627 628 629 630 631

  def testSeveralFunctionsOnASingleAssignment(self):
    """Test dynamic role generation when an assignment defines several functions
    """
    assignment, = self.portal.portal_catalog(portal_type='Assignment',
                                             parent_reference=self.username)
    assignment.setFunctionList(('subcat', 'another_subcat'))
632
    self._getTypeInfo().newContent(portal_type='Role Information',
633
      role_name='Assignee',
634
      title='an Assignor role for testing',
635
      role_category_list=('group/subcat', 'site/subcat'),
636
      role_base_category_script_id='ERP5Type_getSecurityCategoryFromAssignment',
637
      role_base_category='function')
638
    self.loginAsUser(self.username)
639 640
    user = getSecurityManager().getUser()

641
    obj = self._makeOne()
642 643 644 645
    self.assertEqual(['Assignee'], obj.__ac_local_roles__.get('F1_G1_S1'))
    self.assertEqual(['Assignee'], obj.__ac_local_roles__.get('F2_G1_S1'))
    self.assertTrue('Assignee' in user.getRolesInContext(obj))
    self.assertFalse('Assignor' in user.getRolesInContext(obj))
646
    self.abort()
647

648
  def testAcquireLocalRoles(self):
649 650 651 652
    """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
653 654 655 656 657 658
    self._getModuleTypeInfo().newContent(portal_type='Role Information',
      role_name='Assignor',
      description='desc.',
      title='an Assignor role for testing',
      role_category=self.defined_category,
      role_base_category_script_id='ERP5Type_getSecurityCategoryFromAssignment')
659 660 661 662
    obj = self._makeOne()
    module = obj.getParentValue()
    module.updateLocalRolesOnSecurityGroups()
    # we said the we do not want acquire local roles.
663
    self.assertFalse(obj._getAcquireLocalRoles())
664
    # the local role is set on the module
665
    self.assertEqual(['Assignor'], module.__ac_local_roles__.get('F1_G1_S1'))
666
    # but not on the document
667
    self.assertEqual(None, obj.__ac_local_roles__.get('F1_G1_S1'))
668 669
    # same testing with roles in context.
    self.loginAsUser(self.username)
670
    self.assertTrue('Assignor' in
671
            getSecurityManager().getUser().getRolesInContext(module))
672
    self.assertFalse('Assignor' in
673
            getSecurityManager().getUser().getRolesInContext(obj))
674 675 676 677 678 679 680 681

  def testGetUserByLogin(self):
    """Test getUserByLogin method
    """
    self.loginAsUser(self.username)

    # getUserByLogin accept login as a string
    self.portal.portal_caches.clearAllCache()
682
    self.commit()
683
    person_list = self.portal.acl_users.erp5_users.getUserByLogin(self.username)
684 685
    self.assertEqual(1, len(person_list))
    self.assertEqual(self.username, person_list[0].getReference())
686 687 688

    # getUserByLogin accept login as a list
    self.portal.portal_caches.clearAllCache()
689
    self.commit()
690
    person_list = self.portal.acl_users.erp5_users.getUserByLogin([self.username])
691 692
    self.assertEqual(1, len(person_list))
    self.assertEqual(self.username, person_list[0].getReference())
693 694 695

    # getUserByLogin accept login as a tuple
    self.portal.portal_caches.clearAllCache()
696
    self.commit()
697
    person_list = self.portal.acl_users.erp5_users.getUserByLogin((self.username,))
698 699
    self.assertEqual(1, len(person_list))
    self.assertEqual(self.username, person_list[0].getReference())
700 701 702 703

    # PreferenceTool pass a user as parameter
    user = getSecurityManager().getUser()
    self.portal.portal_caches.clearAllCache()
704
    self.commit()
705
    person_list = self.portal.acl_users.erp5_users.getUserByLogin(user)
706 707
    self.assertEqual(1, len(person_list))
    self.assertEqual(self.username, person_list[0].getReference())
708 709 710 711 712

  def testLocalRoleWithTraverser(self):
    """Make sure that local role works correctly when traversing
    """
    self.assert_(not self.portal.portal_types.Person.acquire_local_roles)
713

714 715 716 717 718 719 720 721 722 723 724 725 726
    self.getPersonModule().newContent(portal_type='Person',
                                      id='first_last',
                                      first_name='First',
                                      last_name='Last')
    loginable_person = self.getPersonModule().newContent(portal_type='Person',
                                                         reference='guest',
                                                         password='guest')
    assignment = loginable_person.newContent(portal_type='Assignment',
                                             function='another_subcat')
    assignment.open()
    self.tic()

    person_module_type_information = self.getTypesTool()['Person Module']
727 728
    person_module_type_information.newContent(portal_type='Role Information',
      role_name='Auditor',
729
      description='',
730 731
      title='An Auditor role for testing',
      role_category='function/another_subcat')
732 733 734 735
    person_module_type_information.updateRoleMapping()
    self.tic()

    person_module_path = self.getPersonModule().absolute_url(relative=1)
736
    response = self.publish(person_module_path,
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
                            basic='guest:guest')
    self.assertEqual(response.getStatus(), 200)
    response = self.publish('/%s/first_last/getFirstName' % person_module_path,
                            basic='guest:guest')
    self.assertEqual(response.getStatus(), 401)

    # Organisation does not have explicitly declared getTitle method in
    # the class definition.
    # Add organisation and make sure guest cannot access to its getTitle.
    self.getOrganisationModule().newContent(portal_type='Organisation',
                                            id='my_company',
                                            title='Nexedi')
    self.tic()
    response = self.publish('/%s/my_company/getTitle' % self.getOrganisationModule().absolute_url(relative=1),
                            basic='guest:guest')
    self.assertEqual(response.getStatus(), 401)

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
  def testKeyAuthentication(self):
    """
     Make sure that we can grant security using a key.
    """
    # add key authentication PAS plugin
    portal = self.portal
    uf = portal.acl_users
    uf.manage_addProduct['ERP5Security'].addERP5KeyAuthPlugin(
         id="erp5_auth_key", \
         title="ERP5 Auth key",\
         encryption_key='fdgfhkfjhltylutyu',
         cookie_name='__key',\
         default_cookie_name='__ac')

    erp5_auth_key_plugin = getattr(uf, "erp5_auth_key")
    erp5_auth_key_plugin.manage_activateInterfaces(
       interfaces=['IExtractionPlugin',
                   'IAuthenticationPlugin',
                   'ICredentialsUpdatePlugin',
                   'ICredentialsResetPlugin'])
774
    self.tic()
775 776 777 778 779 780 781 782

    reference = 'UserReferenceTextWhichShouldBeHardToGeneratedInAnyHumanOrComputerLanguage'
    loginable_person = self.getPersonModule().newContent(portal_type='Person',
                                                         reference=reference,
                                                         password='guest')
    assignment = loginable_person.newContent(portal_type='Assignment',
                                             function='another_subcat')
    assignment.open()
783 784 785 786 787 788 789 790 791
    portal_types = portal.portal_types
    for portal_type in ('Person Module', 'Person', 'Web Site Module', 'Web Site',
                        'Web Page'):
      type_information = portal_types[portal_type]
      type_information.newContent(
        portal_type='Role Information',
        role_name=('Auditor', 'Assignee'),
        role_category='function/another_subcat')
      type_information.updateRoleMapping()
792
    self.tic()
793

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
794
    # encrypt & decrypt works
795 796
    key = erp5_auth_key_plugin.encrypt(reference)
    self.assertNotEquals(reference, key)
797
    self.assertEqual(reference, erp5_auth_key_plugin.decrypt(key))
798
    base_url = portal.absolute_url(relative=1)
799 800 801 802 803 804 805

    # without key we are Anonymous User so we should be redirected with proper HTML
    # status code to login_form
    response = self.publish(base_url)
    self.assertEqual(response.getStatus(), 302)
    self.assertTrue('location' in response.headers.keys())
    self.assertTrue(response.headers['location'].endswith('login_form'))
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
806

807 808 809 810
    # view front page we should be logged in if we use authentication key
    response = self.publish('%s?__ac_key=%s' %(base_url, key))
    self.assertEqual(response.getStatus(), 200)
    self.assertTrue(reference in response.getBody())
811 812 813 814 815 816 817 818 819 820 821 822 823 824

    # check if key authentication works other page than front page
    person_module = portal.person_module
    base_url = person_module.absolute_url(relative=1)
    response = self.publish(base_url)
    self.assertEqual(response.getStatus(), 302)
    self.assertTrue('location' in response.headers.keys())
    self.assertTrue('%s/login_form?came_from=' % portal.getId(), response.headers['location'])
    response = self.publish('%s?__ac_key=%s' %(base_url, key))
    self.assertEqual(response.getStatus(), 200)
    self.assertTrue(reference in response.getBody())

    # check if key authentication works with web_mode too
    web_site = portal.web_site_module.newContent(portal_type='Web Site')
825 826
    web_page = portal.web_page_module.newContent(portal_type='Web Page', reference='ref')
    web_page.release()
827
    self.tic()
828 829 830 831 832
    base_url = web_site.absolute_url(relative=1)
    response = self.publish(base_url)
    self.assertEqual(response.getStatus(), 302)
    self.assertTrue('location' in response.headers.keys())
    self.assertTrue('%s/login_form?came_from=' % portal.getId(), response.headers['location'])
833
    # web site access
834 835
    response = self.publish('%s?__ac_key=%s' %(base_url, key))
    self.assertEqual(response.getStatus(), 200)
836 837 838 839 840 841 842 843
    # web page access by path
    response = self.publish('%s/%s?__ac_key=%s' %(base_url, web_page.getRelativeUrl(),
                                                  key))
    self.assertEqual(response.getStatus(), 200)
    # web page access by reference
    response = self.publish('%s/%s?__ac_key=%s' %(base_url, web_page.getReference(),
                                                  key))
    self.assertEqual(response.getStatus(), 200)
844 845 846 847 848 849
    response = self.publish('%s/%s?__ac_name=%s&__ac_password=%s' % (
      base_url, web_page.getReference(), reference, 'guest'))
    self.assertEqual(response.getStatus(), 200)
    response = self.publish('%s/%s?__ac_name=%s&__ac_password=%s' % (
      base_url, web_page.getReference(), 'ERP5TypeTestCase', ''))
    self.assertEqual(response.getStatus(), 200)
850

851 852 853 854 855 856 857 858
  def _createZodbUser(self, login, role_list=None):
    if role_list is None:
      role_list = ['Member', 'Assignee', 'Assignor', 'Author', 'Auditor',
          'Associate']
    uf = self.portal.acl_users
    uf._doAddUser(login, '', role_list, [])

  def test_owner_local_role_on_clone(self):
859 860
    # check that tested stuff is ok
    parent_type = 'Person'
861
    self.assertEqual(self.portal.portal_types[parent_type].acquire_local_roles, 0)
862 863 864 865 866

    original_owner_id = 'original_user' + self.id()
    cloning_owner_id = 'cloning_user' + self.id()
    self._createZodbUser(original_owner_id)
    self._createZodbUser(cloning_owner_id)
867
    self.commit()
868 869 870
    module = self.portal.getDefaultModule(portal_type=parent_type)
    self.login(original_owner_id)
    document = module.newContent(portal_type=parent_type)
871
    self.tic()
872 873
    self.login(cloning_owner_id)
    cloned_document = document.Base_createCloneDocument(batch_mode=1)
874
    self.tic()
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    self.login()
    # real assertions
    # roles on original document
    self.assertEqual(
        document.get_local_roles(),
        (((original_owner_id), ('Owner',)),)
    )

    # roles on cloned document
    self.assertEqual(
        cloned_document.get_local_roles(),
        (((cloning_owner_id), ('Owner',)),)
    )

  def test_owner_local_role_on_clone_with_subobjects(self):
890 891 892
    # check that tested stuff is ok
    parent_type = 'Person'
    acquiring_type = 'Email'
893 894
    self.assertEqual(self.portal.portal_types[acquiring_type].acquire_local_roles, 1)
    self.assertEqual(self.portal.portal_types[parent_type].acquire_local_roles, 0)
895

896 897
    original_owner_id = 'original_user' + self.id()
    cloning_owner_id = 'cloning_user' + self.id()
898 899
    self._createZodbUser(original_owner_id)
    self._createZodbUser(cloning_owner_id)
900
    self.commit()
901 902 903 904
    module = self.portal.getDefaultModule(portal_type=parent_type)
    self.login(original_owner_id)
    document = module.newContent(portal_type=parent_type)
    subdocument = document.newContent(portal_type=acquiring_type)
905
    self.tic()
906 907
    self.login(cloning_owner_id)
    cloned_document = document.Base_createCloneDocument(batch_mode=1)
908
    self.tic()
909 910 911 912 913
    self.login()
    self.assertEqual(1, len(document.contentValues()))
    self.assertEqual(1, len(cloned_document.contentValues()))
    cloned_subdocument = cloned_document.contentValues()[0]
    # real assertions
914
    # roles on original documents
915 916 917 918 919 920 921 922 923
    self.assertEqual(
        document.get_local_roles(),
        (((original_owner_id), ('Owner',)),)
    )
    self.assertEqual(
        subdocument.get_local_roles(),
        (((original_owner_id), ('Owner',)),)
    )

924
    # roles on cloned original documents
925 926 927 928 929
    self.assertEqual(
        cloned_document.get_local_roles(),
        (((cloning_owner_id), ('Owner',)),)
    )
    self.assertEqual(
930
        cloned_subdocument.get_local_roles(),
931 932
        (((cloning_owner_id), ('Owner',)),)
    )
933

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  def _checkMessageMethodIdList(self, expected_method_id_list):
    actual_method_id_list = sorted([
        message.method_id
        for message in self.portal.portal_activities.getMessageList()
    ])
    self.assertEqual(expected_method_id_list, actual_method_id_list)

  def test_reindexObjectSecurity_on_modules(self):
    person_module = self.portal.person_module
    portal_activities = self.portal.portal_activities
    check = self._checkMessageMethodIdList

    check([])
    # We need at least one person for this test.
    self.assertTrue(len(person_module.keys()))
    # When we update security of a module...
    person_module.reindexObjectSecurity()
951
    self.commit()
952 953 954 955 956 957 958 959 960 961 962
    # we don't want all underlying objects to be recursively
    # reindexed. After all, its contents do not acquire local roles.
    check(['immediateReindexObject'])
    self.tic()
    check([])
    # But non-module objects, with subobjects that acquire local
    # roles, should reindex their security recursively:
    person, = [rec.getObject()
               for rec in person_module.searchFolder(reference=self.username)]
    self.assertTrue(len(person.objectIds()))
    person.reindexObjectSecurity()
963
    self.commit()
964 965 966
    check(['recursiveImmediateReindexObject'])
    self.tic()

967 968 969
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestUserManagement))
970
  suite.addTest(unittest.makeSuite(TestUserManagementExternalAuthentication))
971 972
  suite.addTest(unittest.makeSuite(TestLocalRoleManagement))
  return suite