testERP5Security.py 54 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 itertools
34
import transaction
35
import unittest
Nicolas Dumazet's avatar
Nicolas Dumazet committed
36
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
37
from Products.ERP5Type.tests.utils import createZODBPythonScript
38
from AccessControl.SecurityManagement import newSecurityManager
39
from AccessControl.SecurityManagement import getSecurityManager
40
from AccessControl import SpecialUsers
41
from Products.PluggableAuthService import PluggableAuthService
42 43
from Products.PluggableAuthService.interfaces.plugins \
  import IAuthenticationPlugin, IUserEnumerationPlugin
44
from zope.interface.verify import verifyClass
45
from DateTime import DateTime
46
from Products import ERP5Security
47
from Products.DCWorkflow.DCWorkflow import ValidationFailed
48

49 50
AUTO_LOGIN = object()

51 52 53 54

class UserManagementTestCase(ERP5TypeTestCase):
  """TestCase for user manement, with utilities to create users and helpers
  assertion methods.
55
  """
56
  _login_generator = itertools.count().next
57 58


59 60
  def getBusinessTemplateList(self):
    """List of BT to install. """
61
    return ('erp5_base', 'erp5_administration',)
62

63 64
  def beforeTearDown(self):
    """Clears person module and invalidate caches when tests are finished."""
65
    transaction.abort()
66 67 68
    self.getPersonModule().manage_delObjects([x for x in
                             self.getPersonModule().objectIds()])
    self.tic()
69

70 71 72 73
  def getUserFolder(self):
    """Returns the acl_users. """
    return self.getPortal().acl_users

74 75 76 77 78
  def loginAsUser(self, username):
    uf = self.portal.acl_users
    user = uf.getUserById(username).__of__(uf)
    newSecurityManager(None, user)

79
  def _makePerson(self, login=AUTO_LOGIN, open_assignment=1, assignment_start_date=None,
80
                  assignment_stop_date=None, tic=True, password='secret', group_value=None, **kw):
81 82
    """Creates a person in person module, and returns the object, after
    indexing is done. """
83 84
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
85
                     portal_type='Person', **kw)
86 87
    assignment = new_person.newContent(portal_type = 'Assignment',
                                       start_date=assignment_start_date,
88 89
                                       stop_date=assignment_stop_date,
                                       group_value=group_value,)
90 91
    if open_assignment:
      assignment.open()
92 93 94 95 96 97 98 99 100 101 102
    if login is not None:
      if login is AUTO_LOGIN:
        login = 'login_%s' % self._login_generator()
      new_person.newContent(
        portal_type='ERP5 Login',
        reference=login,
        password=password,
      ).validate()
    if tic:
      self.tic()
    return new_person.Person_getUserId(), login, password
103

104 105 106 107 108 109 110
  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()
Vincent Pelletier's avatar
Vincent Pelletier committed
111
    self.assertNotEquals(uf.getUser(login), None)
112 113 114 115 116 117 118 119
    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))
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  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))

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  def _getOrCreateGroupValue(self):
    group_id = 'dummy_group'
    group = self.portal.portal_categories.group
    if group_id in group.objectIds():
      return group[group_id]
    else:
      return self.portal.portal_categories.group.newContent(
        id=group_id
      )

  def _createDummyDocument(self):
    types_tool = self.portal.portal_types
    # Create Portal Types if needed
    if 'Dummy Object' not in types_tool.objectIds():
      dummy_type = types_tool.newContent(
        'Dummy Object',
        'Base Type',
        type_class='XMLObject'
      )
      dummy_type.newContent(
        portal_type='Role Information',
        role_category_list=self.portal.portal_categories.\
          group.dummy_group.getRelativeUrl(),
        role_name_list=('Assignee', )
      )
    if 'Dummy Module' not in types_tool.objectIds():
      types_tool.newContent(
        'Dummy Module',
        'Base Type',
        type_class='Folder',
        type_filter_content_type=1,
        type_allowed_content_type_list=('Dummy Object', ),
      )
    # clean-up dummy_module in any way
    if 'dummy_module' in self.portal.objectIds():
      self.portal.manage_delObjects(['dummy_module'])
    self.tic()
    self.portal.newContent(portal_type='Dummy Module', id='dummy_module')
    dummy_document = self.portal.dummy_module.newContent(portal_type='Dummy Object')
    self.tic()
    return dummy_document

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

class RoleManagementTestCase(UserManagementTestCase):
  """Test case with required configuration to test role definitions.
  """
  def afterSetUp(self):
    """Initialize requirements of security configuration.
    """
    super(RoleManagementTestCase, self).afterSetUp()
    # 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()
          ),)
        """)
    # configure group, site, function categories
    category_tool = self.getCategoryTool()
    for bc in ['group', 'site', 'function']:
      base_cat = category_tool[bc]
      code = bc[0].upper()
      if base_cat.get('subcat', None) is not None:
        continue
      base_cat.newContent(portal_type='Category',
                          id='subcat',
                          codification="%s1" % code)
      base_cat.newContent(portal_type='Category',
                          id='another_subcat',
                          codification="%s2" % code)
    self.defined_category = "group/subcat\n"\
                            "site/subcat\n"\
                            "function/subcat"

  def beforeTearDown(self):
    """Clean up after test.
    """
    # clear base categories
    for bc in ['group', 'site', 'function']:
      base_cat = self.getCategoryTool()[bc]
      base_cat.manage_delObjects(list(base_cat.objectIds()))
    # clear role definitions
    for ti in self.getTypesTool().objectValues():
      ti.manage_delObjects([x.id for x in ti.getRoleInformationList()])
    # clear modules
    for module in self.portal.objectValues():
      if module.getId().endswith('_module'):
        module.manage_delObjects(list(module.objectIds()))
    # commit this
    self.tic()


class TestUserManagement(UserManagementTestCase):
  """Tests User Management in ERP5Security.
  """
234
  def test_PersonWithLoginPasswordAreUsers(self):
235
    """Tests a person with a login & password is a valid user."""
236 237
    _, login, password = self._makePerson()
    self._assertUserExists(login, password)
238

239 240
  def test_PersonLoginCaseSensitive(self):
    """Login/password are case sensitive."""
241 242 243 244
    login = 'case_test_user'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists('case_test_User', password)
245

246 247
  def test_PersonLoginIsNotStripped(self):
    """Make sure 'foo ', ' foo' and ' foo ' do not match user 'foo'. """
248 249 250 251 252
    _, login, password = self._makePerson()
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists(login + ' ', password)
    self._assertUserDoesNotExists(' ' + login, password)
    self._assertUserDoesNotExists(' ' + login + ' ', password)
253 254 255

  def test_PersonLoginCannotBeComposed(self):
    """Make sure ZSQLCatalog keywords cannot be used at login time"""
256 257 258 259 260 261
    _, login, password = self._makePerson()
    self._assertUserExists(login, password)
    doest_not_exist = 'bar'
    self._assertUserDoesNotExists(doest_not_exist, password)
    self._assertUserDoesNotExists(login + ' OR ' + doest_not_exist, password)
    self._assertUserDoesNotExists(doest_not_exist + ' OR ' + login, password)
262

263
  def test_PersonLoginQuote(self):
264 265 266 267 268 269
    login = "'"
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
    login = '"'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
270 271

  def test_PersonLogin_OR_Keyword(self):
272 273 274 275 276
    base_login = 'foo'
    login = base_login + ' OR bar'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists(base_login, password)
277 278 279

  def test_PersonLoginCatalogKeyWord(self):
    # use something that would turn the username in a ZSQLCatalog catalog keyword
280 281 282 283 284 285
    base_login ='foo'
    login = base_login + '%'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists(base_login, password)
    self._assertUserDoesNotExists(base_login + "bar", password)
286 287

  def test_PersonLoginNGT(self):
288 289 290 291
    login = '< foo'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists('fo', password)
292

293 294
  def test_PersonLoginNonAscii(self):
    """Login can contain non ascii chars."""
295 296 297
    login = 'j\xc3\xa9'
    _, _, password = self._makePerson(login=login)
    self._assertUserExists(login, password)
298 299

  def test_PersonWithLoginWithEmptyPasswordAreNotUsers(self):
300
    """Tests a person with a login but no password is not a valid user."""
301 302 303 304 305 306
    password = None
    _, login, _ = self._makePerson(password=password)
    self._assertUserDoesNotExists(login, password)
    password = ''
    _, login, self._makePerson(password=password)
    self._assertUserDoesNotExists(login, password)
307

308
  def test_PersonWithEmptyLoginAreNotUsers(self):
309 310 311 312 313 314 315 316 317 318
    """Tests a person with empty login & password is not a valid user."""
    _, login, _ = self._makePerson()
    pas_user, = self.portal.acl_users.searchUsers(login=login, exact_match=True)
    pas_login, = pas_user['login_list']
    login_value = self.portal.restrictedTraverse(pas_login['path'])
    login_value.invalidate()
    login_value.setReference('')
    self.commit()
    self.assertRaises(ValidationFailed, login_value.validate)
    self.assertRaises(ValidationFailed, self.portal.portal_workflow.doActionFor, login_value, 'validate_action')
319

320 321
  def test_PersonWithLoginWithNotAssignmentAreNotUsers(self):
    """Tests a person with a login & password and no assignment open is not a valid user."""
322 323
    _, login, password = self._makePerson(open_assignment=0)
    self._assertUserDoesNotExists(login, password)
324

325 326 327 328
  def _testUserNameExistsButCannotLoginAndCannotCreate(self, login):
    self.assertTrue(self.getUserFolder().searchUsers(login=login, exact_match=True))
    self._assertUserDoesNotExists(login, '')
    self.assertRaises(ValidationFailed, self._makePerson, login=login)
329

330
  def test_PersonWithSuperUserLogin(self):
331
    """Tests one cannot use the "super user" special login."""
332 333 334 335 336 337 338 339 340 341
    self._testUserNameExistsButCannotLoginAndCannotCreate(ERP5Security.SUPER_USER)

  def test_PersonWithAnonymousLogin(self):
    """Tests one cannot use the "anonymous user" special login."""
    self._testUserNameExistsButCannotLoginAndCannotCreate(SpecialUsers.nobody.getUserName())

  def test_PersonWithSystemUserLogin(self):
    """Tests one cannot use the "system user" special login."""
    self._testUserNameExistsButCannotLoginAndCannotCreate(SpecialUsers.system.getUserName())

342 343 344 345 346 347 348
  def test_DeletedPersonIsNotUser(self):
    user_id, login, password = self._makePerson()
    self._assertUserExists(login, password)
    acl_user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    self.portal.restrictedTraverse(acl_user['path']).delete()
    self.commit()
    self._assertUserDoesNotExists(login, password)
349

350 351 352 353 354 355 356 357
  def test_ReallyDeletedPersonIsNotUser(self):
    user_id, login, password = self._makePerson()
    acl_user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    p = self.portal.restrictedTraverse(acl_user['path'])
    self._assertUserExists(login, password)
    p.getParentValue().deleteContent(p.getId())
    self.commit()
    self._assertUserDoesNotExists(login, password)
358

359 360 361 362 363 364 365 366 367
  def test_InvalidatedPersonIsUser(self):
    user_id, login, password = self._makePerson()
    acl_user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    p = self.portal.restrictedTraverse(acl_user['path'])
    self._assertUserExists(login, password)
    p.validate()
    p.invalidate()
    self.commit()
    self._assertUserExists(login, password)
368

369 370 371 372 373 374 375 376
  def test_UserIdIsPossibleToUnset(self):
    """Make sure that it is possible to remove user id"""
    user_id, login, password = self._makePerson()
    acl_user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    person = self.portal.restrictedTraverse(acl_user['path'])
    person.setUserId(None)
    self.tic()
    self.assertEqual(None, person.Person_getUserId())
377

378 379

class DuplicatePrevention(UserManagementTestCase):
380 381 382
  def test_MultipleUsers(self):
    """Tests that it's refused to create two Persons with same user id."""
    user_id, login, _ = self._makePerson()
383
    self.assertRaises(ValidationFailed, self._makePerson, user_id=user_id)
384
    self.assertRaises(ValidationFailed, self._makePerson, login=login)
385

386 387
  def test_MultiplePersonReferenceWithoutCommit(self):
    """
388
    Tests that it's refused to create two Persons with same user id.
389 390 391 392
    Check if both persons are created in the same transaction
    """
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
393
                     portal_type='Person', user_id='new_person')
394
    self.assertRaises(ValidationFailed, person_module.newContent,
395
                     portal_type='Person', user_id='new_person')
396 397 398

  def test_MultiplePersonReferenceWithoutTic(self):
    """
399
    Tests that it's refused to create two Persons with same user id.
400 401 402 403
    Check if both persons are created in 2 different transactions.
    """
    person_module = self.getPersonModule()
    new_person = person_module.newContent(
404
                     portal_type='Person', user_id='new_person')
405
    self.commit()
406
    self.assertRaises(ValidationFailed, person_module.newContent,
407
                     portal_type='Person', user_id='new_person')
408 409 410

  def test_MultiplePersonReferenceConcurrentTransaction(self):
    """
411
    Tests that it's refused to create two Persons with same user id.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
412
    Check if both persons are created in 2 concurrent transactions.
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    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,
433
                       portal_type='Person', user_id='new_person')
434 435 436
    finally:
      Base.serialize = Base.serialize_call

437
  def test_PersonCopyAndPaste(self):
438
    """If we copy and paste a person, login must not be copyied."""
439
    user_id, _, _ = self._makePerson(user_id='new_person')
440 441 442 443 444 445 446 447 448 449
    user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    user_value = self.portal.restrictedTraverse(user['path'])
    container = user_value.getParentValue()
    changed, = container.manage_pasteObjects(
      container.manage_copyObjects([user_value.getId()]),
    )
    self.assertNotEquals(
      container[changed['new_id']].Person_getUserId(),
      user_id,
    )
450

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
  def test_duplicateLoginReference(self):
    _, login1, _ = self._makePerson()
    _, login2, _ = self._makePerson()
    pas_user2, = self.portal.acl_users.searchUsers(login=login2, exact_match=True)
    pas_login2, = pas_user2['login_list']
    login2_value = self.portal.restrictedTraverse(pas_login2['path'])
    login2_value.invalidate()
    login2_value.setReference(login1)
    self.commit()
    self.assertRaises(ValidationFailed, login2_value.validate)
    self.assertRaises(ValidationFailed, self.portal.portal_workflow.doActionFor, login2_value, 'validate_action')

  def _duplicateLoginReference(self, commit):
    _, login1, _ = self._makePerson(tic=False)
    user_id2, login2, _ = self._makePerson(tic=False)
    if commit:
      self.commit()
    # Note: cannot rely on catalog, on purpose.
    person_value, = [
      x for x in self.portal.person_module.objectValues()
      if x.Person_getUserId() == user_id2
    ]
    login_value, = [
      x for x in person_value.objectValues(portal_type='ERP5 Login')
      if x.getReference() == login2
    ]
    login_value.invalidate()
    login_value.setReference(login1)
    self.portal.portal_workflow.doActionFor(login_value, 'validate_action')
    result = [x for x in self.portal.portal_catalog(portal_type='ERP5 Login') if x.checkConsistency()]
    self.assertEqual(result, [])
    self.tic()
    result = [x for x in self.portal.portal_catalog(portal_type='ERP5 Login') if x.checkConsistency()]
    self.assertEqual(len(result), 2)

  def test_duplicateLoginReferenceInSameTransaction(self):
    self._duplicateLoginReference(False)

  def test_duplicateLoginReferenceInAnotherTransaction(self):
    self._duplicateLoginReference(True)


class TestPreferences(UserManagementTestCase):

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
  def test_Preference_created_for_new_user_on_getActiveUserPreference(self):
    # Creating a user will create a preference on the first time `getActiveUserPreference`
    # is called
    preference_tool = self.portal.portal_preferences
    preference_count = len(preference_tool.contentValues())

    user_id, login, password = self._makePerson()
    # creating a person does not create a preference
    self.assertEqual(preference_count, len(preference_tool.contentValues()))

    self.loginAsUser(user_id)

    # getActiveUserPreference will create a user preference
    new_preference = preference_tool.getActiveUserPreference()
    self.assertNotEqual(None, new_preference)
    self.assertEqual(preference_count+1, len(preference_tool.contentValues()))
    self.assertEqual('enabled', new_preference.getPreferenceState())

    self.tic()

    # subsequent calls to getActiveUserPreference returns the same preference
    active_preference = preference_tool.getActiveUserPreference()
    self.assertEqual(active_preference, new_preference)
    self.assertEqual(preference_count+1, len(preference_tool.contentValues()))

520 521
  def test_PreferenceTool_setNewPassword(self):
    # Preference Tool has an action to change password
522 523 524 525 526 527 528 529
    user_id, login, password = self._makePerson()
    self._assertUserExists(login, password)
    pas_user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    pas_login, = pas_user['login_list']
    login_value = self.portal.restrictedTraverse(pas_login['path'])
    new_password = 'new' + password

    self.loginAsUser(user_id)
530 531
    result = self.portal.portal_preferences.PreferenceTool_setNewPassword(
      dialog_id='PreferenceTool_viewChangePasswordDialog',
532 533
      current_password='bad' + password,
      new_password=new_password,
534 535
    )
    self.assertEqual(result, self.portal.absolute_url()+'/portal_preferences/PreferenceTool_viewChangePasswordDialog?portal_status_message=Current%20password%20is%20wrong.')
536 537 538 539 540 541

    self.login()
    self._assertUserExists(login, password)
    self._assertUserDoesNotExists(login, new_password)

    self.loginAsUser(user_id)
542 543
    result = self.portal.portal_preferences.PreferenceTool_setNewPassword(
      dialog_id='PreferenceTool_viewChangePasswordDialog',
544 545
      current_password=password,
      new_password=new_password,
546 547
    )
    self.assertEqual(result, self.portal.absolute_url()+'/logout')
548

549 550 551
    self.login()
    self._assertUserExists(login, new_password)
    self._assertUserDoesNotExists(login, password)
552
    # password is not stored in plain text
553
    self.assertNotEquals(new_password, self.portal.restrictedTraverse(pas_user['path']).getPassword())
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

class TestAssignmentAndRoles(UserManagementTestCase):
  def test_AssignmentWithDate(self):
    """Tests a person with an assignment with correct date is a valid user."""
    date = DateTime()
    _, login, password = self._makePerson(
      assignment_start_date=date - 5,
      assignment_stop_date=date + 5,
    )
    self._assertUserExists(login, password)

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

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

  def test_securityGroupAssignmentCorrectDate(self):
    """
      Tests a person with an assignment with correct date
      gets correctly assigned to security groups.
    """
    date = DateTime()
    user_id, login, password = self._makePerson(
      assignment_start_date=date - 5,
      assignment_stop_date=date + 5,
      group_value=self._getOrCreateGroupValue()
    )
    self.assertIn(
      'Assignee',
      self.portal.acl_users.getUserById(user_id).\
        getRolesInContext(self._createDummyDocument())
    )

  def test_securityGroupAssignmentBadStartDate(self):
    """
      Tests a person with an assignment with bad (future) start date
      does not get assigned to security groups.
    """
    date = DateTime()
    user_id, login, password = self._makePerson(
      assignment_start_date=date + 1,
      assignment_stop_date=date + 5,
      group_value=self._getOrCreateGroupValue()
    )
    self.assertNotIn(
      'Assignee',
      self.portal.acl_users.getUserById(user_id).\
        getRolesInContext(self._createDummyDocument())
    )

  def test_securityGroupAssignmentBadStopDate(self):
    """
      Tests a person with an assignment with bad (past) stop date
      does not get assigned to security groups.
    """
    date = DateTime()
    user_id, login, password = self._makePerson(
      assignment_start_date=date - 5,
      assignment_stop_date=date - 1,
      group_value=self._getOrCreateGroupValue()
    )
    self.assertNotIn(
      'Assignee',
      self.portal.acl_users.getUserById(user_id).\
        getRolesInContext(self._createDummyDocument())
    )


class TestPermissionCache(UserManagementTestCase):
637
  def test_OpenningAssignmentClearCache(self):
638 639 640 641
    """Openning an assignment for a person clear the cache automatically.

    XXX this works only on a single zope and not on a ZEO cluster.
    """
642 643 644 645
    user_id, login, password = self._makePerson(open_assignment=0)
    self._assertUserDoesNotExists(login, password)
    user, = self.portal.acl_users.searchUsers(id=user_id, exact_match=True)
    pers = self.portal.restrictedTraverse(user['path'])
646 647
    assi = pers.newContent(portal_type='Assignment')
    assi.open()
648
    self.commit()
649
    self._assertUserExists(login, password)
650
    assi.close()
651
    self.commit()
652
    self._assertUserDoesNotExists(login, password)
653

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
  def test_PersonNotIndexedNotCached(self):
    user_id, login, password = self._makePerson(tic=False)
    # not indexed yet
    self._assertUserDoesNotExists(login, password)
    self.tic()
    self._assertUserExists(login, password)

  def test_PersonNotValidNotCached(self):
    user_id, login, password = self._makePerson()
    password += '2'
    pas_user, = self.portal.acl_users.searchUsers(login=login, exact_match=True)
    pas_login, = pas_user['login_list']
    self._assertUserDoesNotExists(login, password)
    self.portal.restrictedTraverse(pas_login['path']).setPassword(password)
    self._assertUserExists(login, password)


class TestPASAPI(UserManagementTestCase):
  """Test low level PAS API works as expected.
  """
  def test_GroupManagerInterfaces(self):
    """Tests group manager plugin respects interfaces."""
    from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin
    from Products.ERP5Security.ERP5GroupManager import ERP5GroupManager
    verifyClass(IGroupsPlugin, ERP5GroupManager)

  def test_UserManagerInterfaces(self):
    """Tests user manager plugin respects interfaces."""
    from Products.PluggableAuthService.interfaces.plugins import\
                IAuthenticationPlugin, IUserEnumerationPlugin
    from Products.ERP5Security.ERP5UserManager import ERP5UserManager
    verifyClass(IAuthenticationPlugin, ERP5UserManager)
    verifyClass(IUserEnumerationPlugin, ERP5UserManager)

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

  def test_searchUserId(self):
    substring = 'person_id'
    user_id_set = {substring + '1', '1' + substring}
    for user_id in user_id_set:
      self._makePerson(user_id=user_id)
    self.assertEqual(
      user_id_set,
      {x['userid'] for x in self.portal.acl_users.searchUsers(id=substring, exact_match=False)},
    )

  def test_searchLogin(self):
    substring = 'person_login'
    login_set = {substring + '1', '1' + substring}
    for login in login_set:
      self._makePerson(login=login)
    self.assertEqual(
      login_set,
      {x['login'] for x in self.portal.acl_users.searchUsers(login=substring, exact_match=False)},
    )

  def test_searchUsersIdExactMatch(self):
    substring = 'person2_id'
    self._makePerson(user_id=substring)
    self._makePerson(user_id=substring + '1')
    self._makePerson(user_id='1' + substring)
    self.assertEqual(
      [substring],
      [x['userid'] for x in self.portal.acl_users.searchUsers(id=substring, exact_match=True)],
    )
722

723 724 725 726 727 728 729 730 731
  def test_searchUsersLoginExactMatch(self):
    substring = 'person2_login'
    self._makePerson(login=substring)
    self._makePerson(login=substring + '1')
    self._makePerson(login='1' + substring)
    self.assertEqual(
      [substring],
      [x['login'] for x in self.portal.acl_users.searchUsers(login=substring, exact_match=True)],
    )
732

733 734 735 736

class TestMigration(UserManagementTestCase):
  """Tests migration to from login on the person to ERP5 Login documents.
  """
737
  def test_PersonLoginMigration(self):
738 739
    if 'erp5_users' not in self.portal.acl_users:
      self.portal.acl_users.manage_addProduct['ERP5Security'].addERP5UserManager('erp5_users')
740 741 742 743 744 745 746
    self.portal.acl_users.erp5_users.manage_activateInterfaces([
      'IAuthenticationPlugin',
      'IUserEnumerationPlugin',
    ])
    pers = self.portal.person_module.newContent(
      portal_type='Person',
      reference='the_user',
747
      user_id=None,
748 749 750 751 752 753 754 755 756 757 758 759 760
    )
    pers.newContent(
      portal_type='Assignment',
    ).open()
    pers.setPassword('secret')
    self.assertEqual(len(pers.objectValues(portal_type='ERP5 Login')), 0)
    self.tic()
    self._assertUserExists('the_user', 'secret')
    self.portal.portal_templates.fixConsistency(filter={'constraint_type': 'post_upgrade'})
    self.portal.portal_caches.clearAllCache()
    self.tic()
    self._assertUserExists('the_user', 'secret')
    self.assertEqual(pers.getPassword(), None)
761
    self.assertEqual(pers.Person_getUserId(), 'the_user')
762 763 764 765 766 767
    login = pers.objectValues(portal_type='ERP5 Login')[0]
    login.setPassword('secret2')
    self.portal.portal_caches.clearAllCache()
    self.tic()
    self._assertUserDoesNotExists('the_user', 'secret')
    self._assertUserExists('the_user', 'secret2')
768 769 770 771
    self.assertFalse('erp5_users' in \
                     [x[0] for x in self.portal.acl_users.plugins.listPlugins(IAuthenticationPlugin)])
    self.assertFalse('erp5_users' in \
                     [x[0] for x in self.portal.acl_users.plugins.listPlugins(IUserEnumerationPlugin)])
772 773 774 775 776

  def test_ERP5LoginUserManagerMigration(self):
    acl_users= self.portal.acl_users
    acl_users.manage_delObjects(ids=['erp5_login_users'])
    portal_templates = self.portal.portal_templates
777
    self.assertNotEqual(portal_templates.checkConsistency(filter={'constraint_type': 'post_upgrade'}) , [])
778
    # call checkConsistency again to check if FIX does not happen by checkConsistency().
779 780 781
    self.assertNotEqual(portal_templates.checkConsistency(filter={'constraint_type': 'post_upgrade'}) , [])
    portal_templates.fixConsistency(filter={'constraint_type': 'post_upgrade'})
    self.assertEqual(portal_templates.checkConsistency(filter={'constraint_type': 'post_upgrade'}) , [])
782 783 784 785
    self.assertTrue('erp5_login_users' in \
                     [x[0] for x in self.portal.acl_users.plugins.listPlugins(IAuthenticationPlugin)])
    self.assertTrue('erp5_login_users' in \
                     [x[0] for x in self.portal.acl_users.plugins.listPlugins(IUserEnumerationPlugin)])
786

787

788
class TestUserManagementExternalAuthentication(TestUserManagement):
789 790 791 792
  def getTitle(self):
    """Title of the test."""
    return "ERP5Security: User Management with External Authentication plugin"

793 794 795 796 797 798 799 800 801 802 803 804 805
  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'])
806
      self.tic()
807 808 809 810 811 812

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

813 814 815
    _, login, _ = self._makePerson()
    pas_user, = self.portal.acl_users.searchUsers(login=login, exact_match=True)
    reference = self.portal.restrictedTraverse(pas_user['path']).getReference()
816 817 818 819 820 821 822 823 824 825 826 827 828

    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
829
    response = self.publish(base_url, env={self.user_id_key.replace('-', '_').upper(): login})
830 831 832 833
    self.assertEqual(response.getStatus(), 200)
    self.assertTrue(reference in response.getBody())


834
class TestLocalRoleManagement(RoleManagementTestCase):
835 836 837 838 839 840 841 842 843
  """Tests Local Role Management with ERP5Security.

  """
  def getTitle(self):
    return "ERP5Security: User Role Management"

  def afterSetUp(self):
    """Called after setup completed.
    """
844 845
    super(TestLocalRoleManagement, self).afterSetUp()

846 847 848 849
    # 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
850
    self.username = 'usérn@me'
851 852
    # create a user and open an assignement
    pers = self.getPersonModule().newContent(portal_type='Person',
853
                                             user_id=self.username)
854 855 856 857 858
    assignment = pers.newContent( portal_type='Assignment',
                                  group='subcat',
                                  site='subcat',
                                  function='subcat' )
    assignment.open()
859 860 861
    pers.newContent(portal_type='ERP5 Login',
                    reference=self.username,
                    password=self.username).validate()
862
    self.person = pers
863
    self.tic()
864

865 866 867 868
  def loginAsUser(self, username):
    uf = self.portal.acl_users
    user = uf.getUserById(username).__of__(uf)
    newSecurityManager(None, user)
869

870 871
  def _getTypeInfo(self):
    return self.getTypesTool()['Organisation']
872

873 874
  def _getModuleTypeInfo(self):
    return self.getTypesTool()['Organisation Module']
875

876 877
  def _makeOne(self):
    return self.getOrganisationModule().newContent(portal_type='Organisation')
878

879 880
  def getBusinessTemplateList(self):
    """List of BT to install. """
881
    return ('erp5_base', 'erp5_web', 'erp5_ingestion', 'erp5_dms', 'erp5_administration')
882

883 884 885 886 887 888
  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)

889 890 891 892
  def testMemberRole(self):
    """Test users have the Member role.
    """
    self.loginAsUser(self.username)
893
    self.assertTrue('Member' in
894
            getSecurityManager().getUser().getRolesInContext(self.portal))
895
    self.assertTrue('Member' in
896
            getSecurityManager().getUser().getRoles())
897

898 899 900
  def testSimpleLocalRole(self):
    """Test simple case of setting a role.
    """
901 902 903 904
    self._getTypeInfo().newContent(portal_type='Role Information',
      role_name='Assignor',
      description='desc.',
      title='an Assignor role for testing',
905
      role_category=self.defined_category)
906
    self.loginAsUser(self.username)
907 908 909 910 911 912
    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))
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

    # check if assignment change is effective immediately
    self.login()
    res = self.publish(self.portal.absolute_url_path() + \
                       '/Base_viewSecurity?__ac_name=%s&__ac_password=%s' % \
                       (self.username, self.username))
    self.assertEqual([x for x in res.body.splitlines() if x.startswith('-->')],
                     ["--> ['F1_G1_S1']"], res.body)
    assignment = self.person.newContent( portal_type='Assignment',
                                  group='subcat',
                                  site='subcat',
                                  function='another_subcat' )
    assignment.open()
    res = self.publish(self.portal.absolute_url_path() + \
                       '/Base_viewSecurity?__ac_name=%s&__ac_password=%s' % \
                       (self.username, self.username))
    self.assertEqual([x for x in res.body.splitlines() if x.startswith('-->')],
                     ["--> ['F1_G1_S1']", "--> ['F2_G1_S1']"], res.body)
    assignment.setGroup('another_subcat')
    res = self.publish(self.portal.absolute_url_path() + \
                       '/Base_viewSecurity?__ac_name=%s&__ac_password=%s' % \
                       (self.username, self.username))
    self.assertEqual([x for x in res.body.splitlines() if x.startswith('-->')],
                     ["--> ['F1_G1_S1']", "--> ['F2_G2_S1']"], res.body)
937
    self.abort()
938

939 940 941
  def testLocalRolesGroupId(self):
    """Assigning a role with local roles group id.
    """
942
    self.portal.portal_categories.local_role_group.newContent(
943
      portal_type='Category',
944 945
      reference = 'Alternate',
      id = 'Alternate')
946 947
    self._getTypeInfo().newContent(portal_type='Role Information',
      role_name='Assignor',
948
      local_role_group_value=self.portal.portal_categories.local_role_group.Alternate,
949 950 951 952 953 954 955 956
      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))
957
    self.assertEqual({('F1_G1_S1', 'Assignor')},
958
      obj.__ac_local_roles_group_id_dict__.get('Alternate'))
959
    self.abort()
960 961


962 963 964 965 966
  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.
    """
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    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))
983
    self.abort()
984 985 986 987 988

  def testSeveralFunctionsOnASingleAssignment(self):
    """Test dynamic role generation when an assignment defines several functions
    """
    assignment, = self.portal.portal_catalog(portal_type='Assignment',
989
                                             parent_reference=self.person.getReference())
990
    assignment.setFunctionList(('subcat', 'another_subcat'))
991
    self._getTypeInfo().newContent(portal_type='Role Information',
992
      role_name='Assignee',
993
      title='an Assignor role for testing',
994
      role_category_list=('group/subcat', 'site/subcat'),
995
      role_base_category_script_id='ERP5Type_getSecurityCategoryFromAssignment',
996
      role_base_category='function')
997
    self.loginAsUser(self.username)
998 999
    user = getSecurityManager().getUser()

1000
    obj = self._makeOne()
1001 1002 1003 1004
    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))
1005
    self.abort()
1006

1007
  def testAcquireLocalRoles(self):
1008 1009 1010
    """Tests that document does not acquire loal roles from their parents if
    "acquire local roles" is not checked."""
    ti = self._getTypeInfo()
1011 1012
    ti.setTypeAcquireLocalRole(False)
    self.commit() # So dynamic class gets updated for setTypeAcquireLocalRole change
1013 1014 1015 1016 1017 1018
    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')
1019 1020 1021 1022
    obj = self._makeOne()
    module = obj.getParentValue()
    module.updateLocalRolesOnSecurityGroups()
    # we said the we do not want acquire local roles.
1023
    self.assertFalse(obj._getAcquireLocalRoles())
1024
    # the local role is set on the module
1025
    self.assertEqual(['Assignor'], module.__ac_local_roles__.get('F1_G1_S1'))
1026
    # but not on the document
1027
    self.assertEqual(None, obj.__ac_local_roles__.get('F1_G1_S1'))
1028 1029
    # same testing with roles in context.
    self.loginAsUser(self.username)
1030
    self.assertTrue('Assignor' in
1031
            getSecurityManager().getUser().getRolesInContext(module))
1032
    self.assertFalse('Assignor' in
1033
            getSecurityManager().getUser().getRolesInContext(obj))
1034

1035 1036 1037 1038
  def testLocalRoleWithTraverser(self):
    """Make sure that local role works correctly when traversing
    """
    self.assert_(not self.portal.portal_types.Person.acquire_local_roles)
1039

1040 1041 1042 1043 1044
    self.getPersonModule().newContent(portal_type='Person',
                                      id='first_last',
                                      first_name='First',
                                      last_name='Last')
    loginable_person = self.getPersonModule().newContent(portal_type='Person',
1045
                                                         user_id='guest',
1046 1047 1048 1049
                                                         password='guest')
    assignment = loginable_person.newContent(portal_type='Assignment',
                                             function='another_subcat')
    assignment.open()
1050 1051 1052
    loginable_person.newContent(portal_type='ERP5 Login',
                                reference='guest',
                                password='guest').validate()
1053 1054 1055
    self.tic()

    person_module_type_information = self.getTypesTool()['Person Module']
1056 1057
    person_module_type_information.newContent(portal_type='Role Information',
      role_name='Auditor',
1058
      description='',
1059 1060
      title='An Auditor role for testing',
      role_category='function/another_subcat')
1061 1062 1063 1064
    person_module_type_information.updateRoleMapping()
    self.tic()

    person_module_path = self.getPersonModule().absolute_url(relative=1)
1065
    response = self.publish(person_module_path,
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
                            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)

1083 1084 1085 1086 1087 1088 1089 1090 1091

class TestKeyAuthentication(RoleManagementTestCase):
  def getBusinessTemplateList(self):
    """This test also uses web and dms
    """
    return super(TestKeyAuthentication, self).getBusinessTemplateList() + (
        'erp5_base', 'erp5_web', 'erp5_ingestion', 'erp5_dms', 'erp5_administration')


1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
  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'])
1112
    self.tic()
1113 1114 1115

    reference = 'UserReferenceTextWhichShouldBeHardToGeneratedInAnyHumanOrComputerLanguage'
    loginable_person = self.getPersonModule().newContent(portal_type='Person',
1116
                                                         reference=reference)
1117 1118 1119
    assignment = loginable_person.newContent(portal_type='Assignment',
                                             function='another_subcat')
    assignment.open()
1120 1121 1122
    loginable_person.newContent(portal_type='ERP5 Login',
                                reference=reference,
                                password='guest').validate()
1123 1124 1125 1126 1127 1128 1129 1130 1131
    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()
1132
    self.tic()
1133

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1134
    # encrypt & decrypt works
1135 1136
    key = erp5_auth_key_plugin.encrypt(reference)
    self.assertNotEquals(reference, key)
1137
    self.assertEqual(reference, erp5_auth_key_plugin.decrypt(key))
1138
    base_url = portal.absolute_url(relative=1)
1139 1140 1141 1142 1143 1144 1145

    # 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
1146

1147 1148 1149 1150
    # 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())
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

    # 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')
1165 1166
    web_page = portal.web_page_module.newContent(portal_type='Web Page', reference='ref')
    web_page.release()
1167
    self.tic()
1168 1169 1170 1171 1172
    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'])
1173
    # web site access
1174 1175
    response = self.publish('%s?__ac_key=%s' %(base_url, key))
    self.assertEqual(response.getStatus(), 200)
1176 1177 1178 1179 1180 1181 1182 1183
    # 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)
1184 1185 1186 1187 1188 1189
    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)
1190

1191 1192

class TestOwnerRole(UserManagementTestCase):
1193 1194 1195 1196 1197 1198 1199 1200
  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):
1201 1202
    # check that tested stuff is ok
    parent_type = 'Person'
1203
    self.assertEqual(self.portal.portal_types[parent_type].acquire_local_roles, 0)
1204 1205 1206 1207 1208

    original_owner_id = 'original_user' + self.id()
    cloning_owner_id = 'cloning_user' + self.id()
    self._createZodbUser(original_owner_id)
    self._createZodbUser(cloning_owner_id)
1209
    self.commit()
1210
    module = self.portal.getDefaultModule(portal_type=parent_type)
1211
    self.loginByUserName(original_owner_id)
1212
    document = module.newContent(portal_type=parent_type)
1213
    self.tic()
1214
    self.loginByUserName(cloning_owner_id)
1215
    cloned_document = document.Base_createCloneDocument(batch_mode=1)
1216
    self.tic()
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    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):
1232 1233 1234
    # check that tested stuff is ok
    parent_type = 'Person'
    acquiring_type = 'Email'
1235 1236
    self.assertEqual(self.portal.portal_types[acquiring_type].acquire_local_roles, 1)
    self.assertEqual(self.portal.portal_types[parent_type].acquire_local_roles, 0)
1237

1238 1239
    original_owner_id = 'original_user' + self.id()
    cloning_owner_id = 'cloning_user' + self.id()
1240 1241
    self._createZodbUser(original_owner_id)
    self._createZodbUser(cloning_owner_id)
1242
    self.commit()
1243
    module = self.portal.getDefaultModule(portal_type=parent_type)
1244
    self.loginByUserName(original_owner_id)
1245 1246
    document = module.newContent(portal_type=parent_type)
    subdocument = document.newContent(portal_type=acquiring_type)
1247
    self.tic()
1248
    self.loginByUserName(cloning_owner_id)
1249
    cloned_document = document.Base_createCloneDocument(batch_mode=1)
1250
    self.tic()
1251 1252 1253 1254 1255
    self.login()
    self.assertEqual(1, len(document.contentValues()))
    self.assertEqual(1, len(cloned_document.contentValues()))
    cloned_subdocument = cloned_document.contentValues()[0]
    # real assertions
1256
    # roles on original documents
1257 1258 1259 1260 1261 1262 1263 1264 1265
    self.assertEqual(
        document.get_local_roles(),
        (((original_owner_id), ('Owner',)),)
    )
    self.assertEqual(
        subdocument.get_local_roles(),
        (((original_owner_id), ('Owner',)),)
    )

1266
    # roles on cloned original documents
1267 1268 1269 1270 1271
    self.assertEqual(
        cloned_document.get_local_roles(),
        (((cloning_owner_id), ('Owner',)),)
    )
    self.assertEqual(
1272
        cloned_subdocument.get_local_roles(),
1273 1274
        (((cloning_owner_id), ('Owner',)),)
    )
1275

1276

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
class TestAuthenticationCookie(UserManagementTestCase):
  """Test the authentication cookie.

  Most of this functionality is already tested in testCookieiCrumbler, this
  test uses a fully setup ERP5 site.
  """
  def testCookieAttributes(self):
    """ERP5 sets some cookie attributes
    """
    _, login, password = self._makePerson()
    self.tic()
    request = self.portal.REQUEST
    request.form['__ac_name'] = login
    request.form['__ac_password'] = password
    request['PARENTS'] = [self.portal]
    # (the secure flag is only set if we accessed through https)
    request.setServerURL('https', 'example.com')

    request.traverse('/')

    response = request.RESPONSE
    ac_cookie, = [v for (k, v) in response.listHeaders() if k.lower() == 'set-cookie' and '__ac=' in v]
    # Secure flag so that cookie is sent only on https
    self.assertIn('; Secure', ac_cookie)

    # HTTPOnly flag so that javascript cannot access cookie
    self.assertIn('; HTTPOnly', ac_cookie)


1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
class TestReindexObjectSecurity(UserManagementTestCase):
  def afterSetUp(self):
    super(TestReindexObjectSecurity, self).afterSetUp()
    self.username = 'usérn@me'
    # create a user and open an assignement
    pers = self.getPersonModule().newContent(portal_type='Person',
                                             user_id=self.username)
    assignment = pers.newContent( portal_type='Assignment',
                                  group='subcat',
                                  site='subcat',
                                  function='subcat' )
    assignment.open()
    pers.newContent(portal_type='ERP5 Login',
                    reference=self.username,
                    password=self.username).validate()
    self.tic()

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  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()
1340
    self.commit()
1341 1342 1343 1344 1345 1346 1347 1348
    # 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()
1349
               for rec in person_module.searchFolder(user_id=self.username)]
1350 1351
    self.assertTrue(len(person.objectIds()))
    person.reindexObjectSecurity()
1352
    self.commit()
1353 1354
    # One reindexation activity per subobject, and one on the person itself.
    check(['immediateReindexObject'] * (len(person) + 1))
1355 1356
    self.tic()