Esempio n. 1
0
 def revoke_permission(self, username, action):
     # DefaultPermissionPolicy will cache permissions for 5 seconds so we
     # need to reset the cache
     DefaultPermissionPolicy(self.env).permission_cache = {}
     PermissionSystem(self.env).revoke_permission(username, action)
     assert action not in PermissionSystem(
         self.env).get_user_permissions(username)
Esempio n. 2
0
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'bitten.*'])
        self.env.path = tempfile.mkdtemp()

        # Create tables
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        connector, _ = DatabaseManager(self.env)._get_connector()
        for table in schema:
            for stmt in connector.to_sql(table):
                cursor.execute(stmt)

        # Set up permissions
        self.env.config.set('trac', 'permission_store',
                            'DefaultPermissionStore')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_CREATE')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_DELETE')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_MODIFY')
        if DefaultPermissionPolicy is not None and hasattr(
                DefaultPermissionPolicy, "CACHE_EXPIRY"):
            self.old_perm_cache_expiry = DefaultPermissionPolicy.CACHE_EXPIRY
            DefaultPermissionPolicy.CACHE_EXPIRY = -1

        # Hook up a dummy repository
        self.repos = Mock(get_node=lambda path, rev=None: Mock(
            get_history=lambda: [], isdir=True),
                          normalize_path=lambda path: path,
                          sync=lambda: None)
        self.env.get_repository = lambda authname=None: self.repos
Esempio n. 3
0
 def runTest(self):
     """Test for regression of http://trac.edgewall.org/ticket/11069
     The permissions list should only be populated with permissions that
     the user can grant."""
     self._tester.go_to_front()
     self._tester.logout()
     self._tester.login('user')
     self._testenv.grant_perm('user', 'PERMISSION_GRANT')
     env = self._testenv.get_trac_environment()
     from trac.perm import PermissionSystem
     user_perms = PermissionSystem(env).get_user_permissions('user')
     all_actions = PermissionSystem(env).get_actions()
     try:
         self._tester.go_to_admin("Permissions")
         for action in all_actions:
             option = r"<option>%s</option>" % action
             if action in user_perms and user_perms[action] is True:
                 tc.find(option)
             else:
                 tc.notfind(option)
     finally:
         self._testenv.revoke_perm('user', 'PERMISSION_GRANT')
         self._tester.go_to_front()
         self._tester.logout()
         self._tester.login('admin')
Esempio n. 4
0
    def get_permission_actions(self):
        def expand_action(action):
            actions = set([])
            if isinstance(action, list):
                for a in action:
                    actions = actions | expand_action(a)
                return actions
            elif isinstance(action, tuple):
                actions.add(action[0])
                actions = actions | expand_action(action[1])
                return actions
            else:
                return set([action])

        try:
            if self.recursing: return []
        except:
            pass

        actions = ['NONE', 'INHERIT']

        #Work only in master project
        if self.env != get_master_env(self.env): return actions

        self.recursing = True
        known_actions = set(actions)
        for requestor in [
                r for r in PermissionSystem(self.env).requestors
                if r is not self
        ]:
            known_actions = known_actions | expand_action(
                requestor.get_permission_actions())
        try:
            del self.recursing
        except:
            pass

        projects = get_project_list(self.env)
        for project, project_path, project_url, env in projects:
            for requestor in [
                    r for r in PermissionSystem(env).requestors
                    if r is not self
            ]:
                #if requestor == self: continue
                for action in requestor.get_permission_actions():
                    #if action not in actions: actions.append(action)
                    if isinstance(action, tuple):
                        if action[0] not in known_actions:
                            actions.append(action)
                            known_actions.add(action[0])
                    else:
                        if action not in known_actions:
                            actions.append(action)
                            known_actions.add(action)

        #Return permissions from all projects if this is master project
        return list(actions)
Esempio n. 5
0
    def has_permission(self, username, action):
        # DefaultPermissionPolicy will cache permissions for 5 seconds so we
        # need to reset the cache
        DefaultPermissionPolicy(self.env).permission_cache = {}

        if AgiloTicketSystem.is_trac_1_0():
            del PermissionSystem(self.env).store._all_permissions

        return PermissionSystem(self.env).check_permission(action, username)
Esempio n. 6
0
    def process_admin_request(self, req, cat, page, path_info):
        envs = DatamoverSystem(self.env).all_environments()
        permissions = PermissionSystem(self.env).get_all_permissions()

        if req.method == 'POST':
            source_type = req.args.get('source')
            if not source_type or source_type not in ('permission', 'all'):
                raise TracError, "Source type not specified or invalid"
            source = req.args.get(source_type)
            dest = req.args.get('destination')
            action = None
            if 'copy' in req.args.keys():
                action = 'copy'
            elif 'move' in req.args.keys():
                action = 'move'
            else:
                raise TracError, 'Action not specified or invalid'

            action_verb = {'copy': 'Copied', 'move': 'Moved'}[action]

            perm_filter = None
            if source_type == 'permission':
                in_permissions = [
                    tuple(p.split(':', 2)) for p in req.args.getlist('perm')
                ]
                perm_filter = lambda p: p in in_permissions
            elif source_type == 'all':
                perm_filter = lambda p: True

            try:
                sel_permissions = [p for p in permissions if perm_filter(p)]
                dest_env = _open_environment(dest)
                for perm in sel_permissions:
                    # revoke first in case it's already there
                    # also, go directly to the store to bypass validity checks
                    PermissionSystem(dest_env).store.revoke_permission(
                        perm[0], perm[1])
                    PermissionSystem(dest_env).store.grant_permission(
                        perm[0], perm[1])

                if action == 'move':
                    for perm in sel_permissions:
                        PermissionSystem(self.env).revoke_permission(
                            perm[0], perm[1])

                req.hdf['datamover.message'] = '%s permissions %s' % (
                    action_verb, ', '.join(
                        ["%s:%s" % (u, a) for u, a in sel_permissions]))
            except TracError, e:
                req.hdf[
                    'datamover.message'] = "An error has occured: \n" + str(e)
                self.log.warn(req.hdf['datamover.message'], exc_info=True)
Esempio n. 7
0
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'bitten.*'])
        self.env.path = tempfile.mkdtemp()

        # Create tables
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        connector, _ = DatabaseManager(self.env)._get_connector()
        for table in schema:
            for stmt in connector.to_sql(table):
                cursor.execute(stmt)

        # Set up permissions
        self.env.config.set('trac', 'permission_store',
                            'DefaultPermissionStore')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_CREATE')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_DELETE')
        PermissionSystem(self.env).grant_permission('joe', 'BUILD_MODIFY')
        if DefaultPermissionPolicy is not None and hasattr(
                DefaultPermissionPolicy, "CACHE_EXPIRY"):
            self.old_perm_cache_expiry = DefaultPermissionPolicy.CACHE_EXPIRY
            DefaultPermissionPolicy.CACHE_EXPIRY = -1

        # Hook up a dummy repository
        self.repos = Mock(get_node=lambda path, rev=None: Mock(
            get_history=lambda: [], isdir=True),
                          normalize_path=lambda path: path,
                          sync=lambda: None,
                          resource=Resource('repository', None))
        self.env.get_repository = lambda authname=None: self.repos  # 0.11
        try:  # 0.12+
            from trac.core import Component, implements
            from trac.versioncontrol.api import IRepositoryConnector, \
                                                IRepositoryProvider

            class DummyRepos(Component):
                implements(IRepositoryConnector, IRepositoryProvider)

                def get_supported_types(self):
                    yield ('dummy', 9)

                def get_repository(this, repos_type, repos_dir, params):
                    return self.repos  # Note: 'this' vs 'self' usage

                def get_repositories(self):
                    yield ('', {'dir': 'dummy_dir', 'type': 'dummy'})

            self.dummy = DummyRepos
        except ImportError:
            self.dummy = None  # not supported, will use get_repository()
Esempio n. 8
0
    def setUp(self):
        self._mp_setup()
        self.global_env = self.env
        self.env = ProductEnvironment(self.global_env, self.default_product)

        self.global_env.enable_component(TestRequestSpy)
        self.env.enable_component(TestRequestSpy)
        TestRequestSpy(self.global_env).testMatch = self._assert_product_match
        PermissionSystem(self.global_env).grant_permission(
            'testuser', 'PRODUCT_CREATE')
        PermissionSystem(self.global_env).grant_permission(
            'testuser', 'PRODUCT_VIEW')
        PermissionSystem(self.global_env).grant_permission(
            'testuser', 'PRODUCT_MODIFY')
Esempio n. 9
0
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tractags.*'])
        self.env.path = tempfile.mkdtemp()
        self.perms = PermissionSystem(self.env)

        setup = TagSetup(self.env)
        # Current tractags schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_tractags_schema_init()
        setup.upgrade_environment()

        self.provider = TicketTagProvider(self.env)
        self.realm = 'ticket'
        self.tag_sys = TagSystem(self.env)
        self.tags = ['tag1', 'tag2']

        # Populate tables with initial test data.
        self._create_ticket(self.tags)

        # Mock an anonymous request.
        self.anon_req = Mock()
        self.anon_req.perm = PermissionCache(self.env)

        self.req = Mock(authname='editor')
        self.req.authname = 'editor'
        self.req.perm = PermissionCache(self.env, username='******')
Esempio n. 10
0
 def setUp(self):
     self.env = EnvironmentStub(default_data=True)
     self.perm_sys = PermissionSystem(self.env)
     self.ctlr = TicketSystem(self.env).action_controllers[0]
     self.ticket = Ticket(self.env)
     self.ticket['status'] = 'new'
     self.ticket.insert()
     with self.env.db_transaction as db:
         for user in ('user1', 'user2', 'user3', 'user4'):
             db("INSERT INTO session VALUES (%s, %s, %s)", (user, 1, 0))
     permissions = [
         ('user1', 'TICKET_EDIT_CC'),
         ('user2', 'TICKET_EDIT_CC'),
         ('user2', 'TICKET_BATCH_MODIFY'),
         ('user3', 'TICKET_ADMIN'),
         ('user4', 'TICKET_VIEW'),
         ('user1', 'group1'),
         ('user2', 'group1'),
         ('user2', 'group2'),
         ('user3', 'group2'),
         ('user4', 'group3')
     ]
     for perm in permissions:
         self.perm_sys.grant_permission(*perm)
     self.req = Mock(authname='user1', args={},
                     perm=PermissionCache(self.env, 'user0'))
     self.expected = """\
Esempio n. 11
0
    def check_permission(self, action, username, resource, perm):
        if resource is None or action.split('_')[0] != resource.realm.upper():
            return None

        from tractags.api import TagSystem

        class FakeRequest(object):
            def __init__(self, perm):
                self.perm = perm

        permission = action.lower().split('_')[1]
        req = FakeRequest(perm)
        tags = TagSystem(self.env).get_tags(None, resource)

        # Explicitly denied?
        if ':-'.join((username, permission)) in tags:
            return False

        # Find all granted permissions for the requesting user from
        # tagged permissions by expanding any meta action as well.
        if action in set(
                PermissionSystem(self.env).expand_actions([
                    '_'.join([resource.realm, t.split(':')[1]]).upper()
                    for t in tags if t.split(':')[0] == username
                ])):
            return True
Esempio n. 12
0
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tractags.*'])
        self.env.path = tempfile.mkdtemp()
        self.perms = PermissionSystem(self.env)

        self.db = self.env.get_db_cnx()
        setup = TagSetup(self.env)
        # Current tractags schema is setup with enabled component anyway.
        #   Revert these changes for getting default permissions inserted.
        self._revert_tractags_schema_init()
        setup.upgrade_environment(self.db)

        self.provider = TicketTagProvider(self.env)
        self.realm = 'ticket'
        self.tag_sys = TagSystem(self.env)
        self.tags = ['tag1']

        cursor = self.db.cursor()
        # Populate table with initial test data, not synced with tickets yet.
        cursor.execute("""
            INSERT INTO tags
                   (tagspace, name, tag)
            VALUES ('ticket', '1', 'deleted')""")
        self.realm = 'ticket'
        self._create_ticket(self.tags)

        self.req = Mock()
        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
Esempio n. 13
0
    def test_complete_milestone_retarget_tickets(self):
        name = 'milestone1'
        target = 'milestone2'
        insert_ticket(self.env, summary='Ticket 1', milestone=name)
        insert_ticket(self.env, summary='Ticket 2', milestone=name)
        ps = PermissionSystem(self.env)
        ps.grant_permission('user1', 'TICKET_ADMIN')
        ps.grant_permission('user1', 'MILESTONE_MODIFY')
        req = MockRequest(self.env, authname='user1', method='POST',
            path_info='/admin/ticket/milestones/%s' % name,
            args=dict(action='edit', save='Submit changes', name=name,
                      description='', retarget='on', target=target,
                      comment='', completed='on',
                      completeddate='May 20, 2020, 9:07:52 PM'))

        mod = AdminModule(self.env)
        self.assertTrue(mod.match_request(req))
        with self.assertRaises(RequestDone):
            mod.process_request(req)

        self.assertEqual(2, len(req.chrome['notices']))
        self.assertEqual(
            'The open tickets associated with milestone "milestone1" '
            'have been retargeted to milestone "milestone2".',
            req.chrome['notices'][0])
        self.assertEqual('Your changes have been saved.',
                         req.chrome['notices'][1])
        self.assertEqual([], req.chrome['warnings'])
        self.assertEqual(['303 See Other'], req.status_sent)
        self.assertEqual('http://example.org/trac.cgi/admin/ticket/milestones',
                         req.headers_sent['Location'])
        self.assertTrue(Milestone(self.env, name).is_completed)
        self.assertEqual(target, Ticket(self.env, 1)['milestone'])
        self.assertEqual(target, Ticket(self.env, 2)['milestone'])
Esempio n. 14
0
 def test_user_with_ticket_admin_can_view(self):
     """User with MILESTONE_VIEW and TICKET_ADMIN can view."""
     PermissionSystem(self.env).grant_permission('user1', 'TICKET_ADMIN')
     req = MockRequest(self.env, authname='user1')
     rv = MilestoneAdminPanel(self.env).get_admin_panels(req)
     self.assertEqual([('ticket', "Ticket System", 'milestones',
                        "Milestones")], list(rv))
Esempio n. 15
0
    def test_view_config_paging(self):
        config = BuildConfig(self.env, name='test', path='trunk')
        config.insert()
        platform = TargetPlatform(self.env, config='test', name='any')
        platform.insert()

        PermissionSystem(self.env).grant_permission('joe', 'BUILD_VIEW')
        req = Mock(method='GET',
                   base_path='',
                   cgi_location='',
                   path_info='/build/test',
                   href=Href('/trac'),
                   args={},
                   chrome={},
                   authname='joe',
                   perm=PermissionCache(self.env, 'joe'))

        root = Mock(get_entries=lambda: ['foo'],
                    get_history=lambda: [('trunk', rev, 'edit')
                                         for rev in range(123, 110, -1)])
        self.repos = Mock(get_node=lambda path, rev=None: root,
                          sync=lambda: None,
                          normalize_path=lambda path: path,
                          normalize_rev=lambda rev: rev,
                          youngest_rev=123)
        self.repos.authz = Mock(has_permission=lambda path: True,
                                assert_permission=lambda path: None)

        module = BuildConfigController(self.env)
        assert module.match_request(req)
        _, data, _ = module.process_request(req)

        if req.chrome:
            self.assertEqual('/trac/build/test?page=2',
                             req.chrome['links']['next'][0]['href'])
 def _grant_permission(self, username, action):
     from trac.perm import DefaultPermissionPolicy, PermissionSystem
     if self._has_permission(username, action):
         return
     DefaultPermissionPolicy(self.env).permission_cache = {}
     PermissionSystem(self.env).grant_permission(username, action)
     assert self._has_permission(username, action)
Esempio n. 17
0
    def test_new_blog_post(self):
        PermissionSystem(self.env).grant_permission('user', 'BLOG_ADMIN')
        req = MockRequest(self.env,
                          method='POST',
                          path_info='/blog/create',
                          authname='user',
                          args={
                              'name': 'new_post',
                              'title': 'New post',
                              'author': 'user',
                              'body': 'The body',
                              'action': 'new',
                              'blog-save': ''
                          })

        module = FullBlogModule(self.env)
        self.assertTrue(module.match_request(req))
        self.assertRaises(RequestDone, module.process_request, req)
        self.assertEquals('http://example.org/trac.cgi/blog/new_post',
                          req.headers_sent['Location'])
        self.assertEquals([], req.chrome['warnings'])

        posts = get_blog_posts(self.env)
        self.assertEquals(1, len(posts))
        self.assertEquals('New post', posts[0][4])
Esempio n. 18
0
    def _do_users(self, req):
        perm = PermissionSystem(self.env)
        listing_enabled = self.account_manager.supports('get_users')
        create_enabled = self.account_manager.supports('set_password')
        delete_enabled = self.account_manager.supports('delete_user')

        req.hdf['listing_enabled'] = listing_enabled
        req.hdf['create_enabled'] = create_enabled
        req.hdf['delete_enabled'] = delete_enabled

        if req.method == 'POST':
            if req.args.get('add'):
                if create_enabled:
                    try:
                        _create_user(req, self.env, check_permissions=False)
                    except TracError, e:
                        req.hdf['registration.error'] = e.message
                else:
                    req.hdf['registration_error'] = 'The password store does ' \
                                                    'not support creating users'
            elif req.args.get('remove'):
                if delete_enabled:
                    sel = req.args.get('sel')
                    sel = isinstance(sel, list) and sel or [sel]
                    for account in sel:
                        self.account_manager.delete_user(account)
                else:
                    req.hdf['deletion_error'] = 'The password store does not ' \
                                                'support deleting users'
Esempio n. 19
0
def _ticket_change_subscribers(subscriber, candidates):
    if not candidates:
        return
    if not isinstance(candidates, (list, set, tuple)):
        candidates = [candidates]

    # Get members of permission groups
    groups = PermissionSystem(subscriber.env).get_groups_dict()
    for cc in set(candidates):
        if cc in groups:
            candidates.remove(cc)
            candidates.update(groups[cc])

    matcher = RecipientMatcher(subscriber.env)
    klass = subscriber.__class__.__name__
    sids = set()
    for candidate in candidates:
        recipient = matcher.match_recipient(candidate)
        if not recipient:
            continue
        sid, auth, addr = recipient

        # Default subscription
        for s in subscriber.default_subscriptions():
            yield s[0], s[1], sid, auth, addr, s[2], s[3], s[4]
        if sid:
            sids.add((sid, auth))

    for s in Subscription.find_by_sids_and_class(subscriber.env, sids, klass):
        yield s.subscription_tuple()
Esempio n. 20
0
    def _do_notice(self, req):
        perm = PermissionSystem(self.env)
        perms = perm.get_all_permissions()

        self._get_notice_options()
        (userinfos, groupinfos) = self._get_infos(perms)
        if req.method == 'POST':
            if req.args.get('fill'):
                self._set_notice_options(req)
                if req.args.get('use_ldap'):
                    self._fill_from_ldap(userinfos, groupinfos)
                if req.args.get('use_file'):
                    self._fill_from_file(req, userinfos, groupinfos)
            if req.args.get('change'):
                self._fill_from_fields(req, userinfos, groupinfos)
            if req.args.get('rmuser'):
                self._rm_user(req, userinfos, groupinfos)
                (userinfos, groupinfos) = self._get_infos(perms)
            if req.args.get('rminfo'):
                self._rm_info(req, userinfos, groupinfos)
            if req.args.get('rmall'):
                self._rm_all(req, userinfos, groupinfos)
                (userinfos, groupinfos) = self._get_infos(perms)
                if (len(userinfos) > 0) or (len(groupinfos) > 0):
                    self.error_message = "As long as permissions are defined for users/group, " + \
                 "they cannot be delete from this list."
            if req.args.get('extract'):
                self._extract_groups(req, userinfos, groupinfos)

        req.hdf['admin.userinfos'] = userinfos
        req.hdf['admin.groupinfos'] = groupinfos
        req.hdf['admin.options'] = self.options
        if self.error_message:
            req.hdf['admin.error_message'] = self.error_message
        return 'admin_notice.cs', None
Esempio n. 21
0
    def test_add_comment_requires_ticket_append(self):
        """Adding a ticket comment requires TICKET_APPEND."""
        ps = PermissionSystem(self.env)
        ps.revoke_permission('authenticated', 'TICKET_MODIFY')
        ps.grant_permission('user1', 'TICKET_APPEND')
        ps.grant_permission('user2', 'TICKET_CHGPROP')
        ticket = self._insert_ticket(summary='the summary')
        comment = 'the comment'

        def make_req(authname):
            change_time = Ticket(self.env, 1)['changetime']
            return MockRequest(
                self.env, authname=authname,
                method='POST', path_info='/ticket/1',
                args={'comment': comment, 'action': 'leave', 'submit': True,
                      'view_time': unicode(to_utimestamp(change_time))})

        req = make_req('user1')
        self.assertTrue(self.ticket_module.match_request(req))
        self.assertRaises(RequestDone, self.ticket_module.process_request,
                          req)
        self.assertEqual([], req.chrome['warnings'])
        self.assertEqual(comment,
                         ticket.get_change(1)['fields']['comment']['new'])

        req = make_req('user2')
        self.assertTrue(self.ticket_module.match_request(req))
        self.ticket_module.process_request(req)
        self.assertEqual(1, len(req.chrome['warnings']))
        self.assertEqual("No permissions to add a comment.",
                         unicode(req.chrome['warnings'][0]))
Esempio n. 22
0
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tractags.*'])
        self.env.path = tempfile.mkdtemp()
        self.perms = PermissionSystem(self.env)

        self.tag_s = TagSystem(self.env)
        self.tag_wp = WikiTagProvider(self.env)

        self.db = self.env.get_db_cnx()
        setup = TagSetup(self.env)
        # Current tractags schema is partially setup with enabled component.
        #   Revert these changes for getting a clean setup.
        self._revert_tractags_schema_init()
        setup.upgrade_environment(self.db)

        cursor = self.db.cursor()
        # Populate table with initial test data.
        cursor.execute("""
            INSERT INTO tags
                   (tagspace, name, tag)
            VALUES ('wiki', 'WikiStart', 'tag1')
        """)

        self.req = Mock()
        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
        self.realm = 'wiki'
        self.tags = ['tag1']
Esempio n. 23
0
    def setUp(self):
        self.env = EnvironmentStub(enable=[
            'trac.*', 'acct_mgr.api.*', 'acct_mgr.admin.*', 'acct_mgr.db.*',
            'acct_mgr.register.*', 'acct_mgr.pwhash.HtDigestHashMethod',
            'acct_mgr.tests.admin.BadCheck', 'acct_mgr.tests.admin.DummyCheck'
        ])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)

        # Create a user reference in the permission system.
        self.perm.grant_permission('admin', 'ACCTMGR_ADMIN')
        # Prepare a generic request object for admin actions.
        self.req = Mock(authname='admin',
                        method='GET',
                        args=dict(),
                        abs_href=self.env.abs_href,
                        chrome=dict(notices=[], warnings=[]),
                        href=self.env.abs_href,
                        locale='',
                        redirect=lambda x: None,
                        session=dict(),
                        tz='')
        self.req.perm = PermissionCache(self.env, 'admin')

        self.acctmgr = AccountManager(self.env)
Esempio n. 24
0
    def test_preview_comment_validate_max_comment_size(self):
        """The [ticket] max_comment_size attribute is validated during
        ticket comment edit preview.
        """
        perm_sys = PermissionSystem(self.env)
        perm_sys.grant_permission('user1', 'TICKET_VIEW')
        perm_sys.grant_permission('user1', 'TICKET_APPEND')
        self.env.config.set('ticket', 'max_comment_size', 5)
        ticket = self._insert_ticket(summary='the summary')
        ticket.save_changes('user1', '12345')
        req = MockRequest(self.env,
                          method='POST',
                          authname='user1',
                          path_info='/ticket/%d' % ticket.id,
                          args={
                              'id': '1',
                              'preview_comment': True,
                              'cnum_edit': '1',
                              'edited_comment': '123456'
                          })

        self.assertTrue(self.ticket_module.match_request(req))
        self.ticket_module.process_request(req)

        self.assertEqual(
            "The ticket comment is invalid: Must be less than or "
            "equal to 5 characters", unicode(req.chrome['warnings'][0]))
Esempio n. 25
0
    def _to_users(self, users_perms_and_groups, ticket):
        """Finds all users contained in the list of `users_perms_and_groups`
        by recursive lookup of users when a `group` is encountered.
        """
        ps = PermissionSystem(self.env)
        groups = ps.get_groups_dict()

        def append_owners(users_perms_and_groups):
            for user_perm_or_group in users_perms_and_groups:
                if user_perm_or_group == 'authenticated':
                    owners.update({u[0] for u in self.env.get_known_users()})
                elif user_perm_or_group.isupper():
                    perm = user_perm_or_group
                    for user in ps.get_users_with_permission(perm):
                        if perm in PermissionCache(self.env, user,
                                                   ticket.resource):
                            owners.add(user)
                elif user_perm_or_group not in groups:
                    owners.add(user_perm_or_group)
                else:
                    append_owners(groups[user_perm_or_group])

        owners = set()
        append_owners(users_perms_and_groups)

        return sorted(owners)
Esempio n. 26
0
 def setUp(self):
     self.env = EnvironmentStub(default_data=True)
     self.perm_sys = PermissionSystem(self.env)
     self.ctlr = TicketSystem(self.env).action_controllers[0]
     self.req1 = MockRequest(self.env, authname='user1')
     self.req2 = MockRequest(self.env, authname='user2')
     self.ticket = insert_ticket(self.env, status='invalid')
Esempio n. 27
0
    def setUp(self):
        BaseProductAdminPanelTestCase.setUp(self)
        self.global_env.config.set('multiproduct', 'admin_blacklist',
                                   'testcat1:panel1,testcat3:panel2')
        self.env.config.set('multiproduct', 'admin_blacklist',
                            'testcat1:panel3,testcat3:panel1,testcat2:*')
        global_permsys = PermissionSystem(self.global_env)
        permsys = PermissionSystem(self.env)

        global_permsys.grant_permission('adminuser', 'TRAC_ADMIN')
        global_permsys.grant_permission('prodadmin', 'PRODUCT_ADMIN')
        global_permsys.grant_permission('testuser', 'TEST_ADMIN')
        permsys.grant_permission('prodadmin', 'PRODUCT_ADMIN')
        permsys.grant_permission('testuser', 'TEST_ADMIN')

        self.req = self._get_request_obj()
Esempio n. 28
0
    def check_permission(self, action, username, resource, perm):
        if ConfigObj is None:
            self.log.error('configobj package not found')
            return None

        if self.authz_file and not self.authz_mtime or \
                os.path.getmtime(self.get_authz_file()) > self.authz_mtime:
            self.parse_authz()
        resource_key = self.normalise_resource(resource)
        self.log.debug('Checking %s on %s', action, resource_key)
        permissions = self.authz_permissions(resource_key, username)
        if permissions is None:
            return None  # no match, can't decide
        elif permissions == ['']:
            return False  # all actions are denied

        # FIXME: expand all permissions once for all
        ps = PermissionSystem(self.env)
        for deny, perms in groupby(permissions,
                                   key=lambda p: p.startswith('!')):
            if deny and action in ps.expand_actions([p[1:] for p in perms]):
                return False  # action is explicitly denied
            elif action in ps.expand_actions(perms):
                return True  # action is explicitly granted

        return None  # no match for action, can't decide
Esempio n. 29
0
    def setUp(self):
        tmpdir = os.path.realpath(tempfile.gettempdir())
        self.env = EnvironmentStub(enable=['trac.*', AuthzPolicy], path=tmpdir)
        self.env.config.set('trac', 'permission_policies',
                            'AuthzPolicy, DefaultPermissionPolicy')
        self.env.config.set('ticket', 'restrict_owner', True)

        self.perm_sys = PermissionSystem(self.env)
        self.env.insert_known_users([
            ('user1', '', ''), ('user2', '', ''),
            ('user3', '', ''), ('user4', '', '')
        ])
        self.perm_sys.grant_permission('user1', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user2', 'TICKET_VIEW')
        self.perm_sys.grant_permission('user3', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user4', 'TICKET_MODIFY')
        self.authz_file = os.path.join(tmpdir, 'trac-authz-policy')
        create_file(self.authz_file)
        self.env.config.set('authz_policy', 'authz_file', self.authz_file)
        self.ctlr = TicketSystem(self.env).action_controllers[0]
        self.req1 = Mock(authname='user1', args={},
                         perm=PermissionCache(self.env, 'user1'))
        self.ticket = Ticket(self.env)
        self.ticket['status'] = 'new'
        self.ticket.insert()
Esempio n. 30
0
    def test_change_milestone_requires_milestone_view(self):
        """Changing ticket milestone requires MILESTONE_VIEW."""
        perm_sys = PermissionSystem(self.env)
        perm_sys.revoke_permission('anonymous', 'MILESTONE_VIEW')
        perm_sys.grant_permission('user_w_mv', 'MILESTONE_VIEW')
        self._insert_ticket(summary='the summary')

        def make_req(authname):
            return MockRequest(self.env, authname=authname, method='GET',
                               path_info='/ticket/1')

        def get_milestone_field(fields):
            for field in fields:
                if 'milestone' == field['name']:
                    return field

        req = make_req('user')

        self.assertTrue(self.ticket_module.match_request(req))
        data = self.ticket_module.process_request(req)[1]
        milestone_field = get_milestone_field(data['fields'])
        self.assertFalse(milestone_field['editable'])
        self.assertEqual([], milestone_field['optgroups'][0]['options'])
        self.assertEqual([], milestone_field['optgroups'][1]['options'])

        req = make_req('user_w_mv')

        self.assertTrue(self.ticket_module.match_request(req))
        data = self.ticket_module.process_request(req)[1]
        milestone_field = get_milestone_field(data['fields'])
        self.assertTrue(milestone_field['editable'])
        self.assertEqual([], milestone_field['optgroups'][0]['options'])
        self.assertEqual(['milestone1', 'milestone2',
                          'milestone3', 'milestone4'],
                         milestone_field['optgroups'][1]['options'])