Beispiel #1
0
class CryptoAdminPanelTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'crypto.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.crypto_ap = CryptoAdminPanel(self.env)

    def tearDown(self):
        shutil.rmtree(self.env.path)

    def test_available_actions(self):
        self.failIf('CRYPTO_ADMIN' not in self.perm.get_actions())
        self.failIf('CRYPTO_DELETE' not in self.perm.get_actions())

    def test_available_actions_no_perms(self):
        self.perm.grant_permission('admin', 'authenticated')
        self.assertFalse(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertFalse(self.perm.check_permission('CRYPTO_DELETE', 'admin'))

    def test_available_actions_delete_only(self):
        self.perm.grant_permission('admin', 'CRYPTO_DELETE')
        self.assertFalse(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertTrue(self.perm.check_permission('CRYPTO_DELETE', 'admin'))

    def test_available_actions_full_perms(self):
        self.perm.grant_permission('admin', 'TRAC_ADMIN')
        self.assertTrue(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertTrue(self.perm.check_permission('CRYPTO_DELETE', 'admin'))
Beispiel #2
0
class CryptoAdminPanelTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'crypto.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()

        self.crypto_ap = CryptoAdminPanel(self.env)

    def tearDown(self):
        shutil.rmtree(self.env.path)

    def test_available_actions(self):
        self.failIf('CRYPTO_ADMIN' not in self.perm.get_actions())
        self.failIf('CRYPTO_DELETE' not in self.perm.get_actions())

    def test_available_actions_no_perms(self):
        self.perm.grant_permission('admin', 'authenticated')
        self.assertFalse(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertFalse(self.perm.check_permission('CRYPTO_DELETE', 'admin'))

    def test_available_actions_delete_only(self):
        self.perm.grant_permission('admin', 'CRYPTO_DELETE')
        self.assertFalse(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertTrue(self.perm.check_permission('CRYPTO_DELETE', 'admin'))

    def test_available_actions_full_perms(self):
        self.perm.grant_permission('admin', 'TRAC_ADMIN')
        self.assertTrue(self.perm.check_permission('CRYPTO_ADMIN', 'admin'))
        self.assertTrue(self.perm.check_permission('CRYPTO_DELETE', 'admin'))
Beispiel #3
0
    def process_admin_request(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        perms = self._get_all_permissions()
        subject = req.args.get('subject')
        action = req.args.get('action')
        group = req.args.get('group')

        if req.method == 'POST':
            # Grant permission to subject
            if req.args.get('add') and subject and action:
                if action not in perm.get_actions():
                    raise TracError('Unknown action')
                self._grant_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                self._grant_permission(subject, group)
                req.redirect(self.env.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    if (subject, action) in perms:
                        self._revoke_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))

        perms.sort(lambda a, b: cmp(a[0], b[0]))
        req.hdf['admin.actions'] = perm.get_actions()
        req.hdf['admin.perms'] = [{
            'subject': p[0],
            'action': p[1],
            'key': '%s:%s' % p
        } for p in perms]

        return 'tracforge_admin_perm.cs', None
Beispiel #4
0
    def process_admin_request(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        perms = perm.get_all_permissions()
        subject = req.args.get('subject')
        action = req.args.get('action')
        group = req.args.get('group')

        if req.method == 'POST':
            # Grant permission to subject
            if req.args.get('add') and subject and action:
                if action not in perm.get_actions():
                    raise TracError('Unknown action')
                perm.grant_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                perm.grant_permission(subject, group)
                req.redirect(self.env.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    if (subject, action) in perms:
                        perm.revoke_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))
        
        perms.sort(lambda a, b: cmp(a[0], b[0]))
        req.hdf['admin.actions'] = perm.get_actions()
        req.hdf['admin.perms'] = [{'subject': p[0],
                                   'action': p[1],
                                   'key': '%s:%s' % p
                                  } for p in perms]
        
        return 'admin_perm.cs', None
Beispiel #5
0
    def check_permission(self, action, username, resource, perm):
        # FIXME: Better handling of recursive imports
        from multiproduct.env import ProductEnvironment

        if isinstance(self.env, ProductEnvironment):
            permsys = PermissionSystem(self.env.parent)
            if permsys.check_permission('TRAC_ADMIN', username):
                return action in PermissionSystem(self.env).get_actions() \
                        or None     # FIXME: maybe False is better
            elif username == self.env.product.owner:
                # Product owner granted with PRODUCT_ADMIN permission ootb
                permsys = PermissionSystem(self.env)
                # FIXME: would `action != 'TRAC_ADMIN'` be enough ?
                return True if action in permsys.get_actions() and \
                                action != 'TRAC_ADMIN' \
                            else None
Beispiel #6
0
    def check_permission(self, action, username, resource, perm):
        # FIXME: Better handling of recursive imports
        from multiproduct.env import ProductEnvironment

        if isinstance(self.env, ProductEnvironment):
            permsys = PermissionSystem(self.env.parent)
            if permsys.check_permission('TRAC_ADMIN', username):
                return action in PermissionSystem(self.env).get_actions() \
                        or None     # FIXME: maybe False is better
            elif username == self.env.product.owner:
                # Product owner granted with PRODUCT_ADMIN permission ootb
                permsys = PermissionSystem(self.env)
                # FIXME: would `action != 'TRAC_ADMIN'` be enough ?
                return True if action in permsys.get_actions() and \
                                action != 'TRAC_ADMIN' \
                            else None
Beispiel #7
0
class PermissionTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(enable=['trac.*', 'acct_mgr.api.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()
        self.actions = [
            'ACCTMGR_ADMIN', 'ACCTMGR_CONFIG_ADMIN', 'ACCTMGR_USER_ADMIN',
            'EMAIL_VIEW', 'USER_VIEW'
        ]

    def tearDown(self):
        shutil.rmtree(self.env.path)

    def test_available_actions(self):
        for action in self.actions:
            self.failIf(action not in self.perm.get_actions())

    def test_available_actions_no_perms(self):
        for action in self.actions:
            self.assertFalse(self.perm.check_permission(action, 'anonymous'))

    def test_available_actions_config_admin(self):
        user = '******'
        self.perm.grant_permission(user, 'ACCTMGR_CONFIG_ADMIN')
        actions = [self.actions[0]] + self.actions[2:]
        for action in actions:
            self.assertFalse(self.perm.check_permission(action, user))

    def test_available_actions_user_admin(self):
        user = '******'
        self.perm.grant_permission(user, 'ACCTMGR_USER_ADMIN')
        for action in self.actions[2:]:
            self.assertTrue(self.perm.check_permission(action, user))
        for action in self.actions[:2] + ['TRAC_ADMIN']:
            self.assertFalse(self.perm.check_permission(action, user))

    def test_available_actions_full_perms(self):
        perm_map = dict(acctmgr_admin='ACCTMGR_ADMIN', trac_admin='TRAC_ADMIN')
        for user in perm_map:
            self.perm.grant_permission(user, perm_map[user])
            for action in self.actions:
                self.assertTrue(self.perm.check_permission(action, user))
            if user != 'trac_admin':
                self.assertFalse(self.perm.check_permission(
                    'TRAC_ADMIN', user))
Beispiel #8
0
class PermissionTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(
                enable=['trac.*', 'acct_mgr.api.*'])
        self.env.path = tempfile.mkdtemp()
        self.perm = PermissionSystem(self.env)
        self.req = Mock()
        self.actions = ['ACCTMGR_ADMIN', 'ACCTMGR_CONFIG_ADMIN',
                        'ACCTMGR_USER_ADMIN', 'EMAIL_VIEW', 'USER_VIEW']

    def tearDown(self):
        shutil.rmtree(self.env.path)

    def test_available_actions(self):
        for action in self.actions:
            self.failIf(action not in self.perm.get_actions())

    def test_available_actions_no_perms(self):
        for action in self.actions:
            self.assertFalse(self.perm.check_permission(action, 'anonymous'))

    def test_available_actions_config_admin(self):
        user = '******'
        self.perm.grant_permission(user, 'ACCTMGR_CONFIG_ADMIN')
        actions = [self.actions[0]] + self.actions[2:]
        for action in actions:
            self.assertFalse(self.perm.check_permission(action, user))

    def test_available_actions_user_admin(self):
        user = '******'
        self.perm.grant_permission(user, 'ACCTMGR_USER_ADMIN')
        for action in self.actions[2:]:
            self.assertTrue(self.perm.check_permission(action, user))
        for action in self.actions[:2] + ['TRAC_ADMIN']:
            self.assertFalse(self.perm.check_permission(action, user))

    def test_available_actions_full_perms(self):
        perm_map = dict(acctmgr_admin='ACCTMGR_ADMIN', trac_admin='TRAC_ADMIN')
        for user in perm_map:
            self.perm.grant_permission(user, perm_map[user])
            for action in self.actions:
                self.assertTrue(self.perm.check_permission(action, user))
            if user != 'trac_admin':
                self.assertFalse(self.perm.check_permission('TRAC_ADMIN',
                                                            user))
Beispiel #9
0
class TagSystemTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tractags.*'])
        self.env.path = tempfile.mkdtemp()
        self.perms = PermissionSystem(self.env)
        self.req = Mock()

        self.actions = ['TAGS_ADMIN', 'TAGS_MODIFY', 'TAGS_VIEW']
        self.tag_s = TagSystem(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)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _revert_tractags_schema_init(self):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS tags")
        cursor.execute("DELETE FROM system WHERE name='tags_version'")
        cursor.execute("DELETE FROM permission WHERE action %s"
                       % self.db.like(), ('TAGS_%',))

    # Tests

    def test_available_actions(self):
        for action in self.actions:
            self.failIf(action not in self.perms.get_actions())

    def test_available_providers(self):
        # Standard implementations of DefaultTagProvider should be registered.
        seen = []
        for provider in [TicketTagProvider(self.env),
                         WikiTagProvider(self.env)]:
            self.failIf(provider not in self.tag_s.tag_providers)
            # Ensure unique provider references, a possible bug in Trac-0.11.
            self.failIf(provider in seen)
            seen.append(provider)

    def test_set_tags_no_perms(self):
        resource = Resource('wiki', 'WikiStart')
        tags = ['tag1']
        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
        self.assertRaises(PermissionError, self.tag_s.set_tags, self.req,
                          resource, tags)

    def test_set_tags(self):
        resource = Resource('wiki', 'WikiStart')
        tags = ['tag1']
        self.req.perm = PermissionCache(self.env, username='******')
        # Shouldn't raise an error with appropriate permission.
        self.tag_s.set_tags(self.req, resource, tags)

    def test_query_no_args(self):
        # Regression test for query without argument,
        #   reported as th:ticket:7857.

        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
        self.assertEquals([(res, tags) for res, tags in
                           self.tag_s.query(self.req, query='')],
                          [])
Beispiel #10
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(
                    _("All upper-cased tokens are reserved for "
                      "permission names."))

            # Grant permission to subject
            if 'add' in req.args and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                try:
                    perm.grant_permission(subject, action)
                except TracError as e:
                    add_warning(req, e)
                else:
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "granted the permission %(action)s.",
                            subject=subject,
                            action=action))

            # Add subject to group
            elif 'add' in req.args and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    req.perm.require(
                        action,
                        message=_(
                            "The subject %(subject)s was not added to "
                            "the group %(group)s because the group has "
                            "%(perm)s permission and users cannot grant "
                            "permissions they don't possess.",
                            subject=subject,
                            group=group,
                            perm=action))
                try:
                    perm.grant_permission(subject, group)
                except TracError as e:
                    add_warning(req, e)
                else:
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "added to the group %(group)s.",
                            subject=subject,
                            group=group))

            # Copy permissions to subject
            elif 'copy' in req.args and subject and target:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')

                subject_permissions = perm.get_users_dict().get(subject, [])
                if not subject_permissions:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s does not "
                            "have any permissions.",
                            subject=subject))

                for action in subject_permissions:
                    if action not in all_actions:  # plugin disabled?
                        self.log.warning(
                            "Skipped granting %s to %s: "
                            "permission unavailable.", action, target)
                    else:
                        if action not in req.perm:
                            add_warning(
                                req,
                                _(
                                    "The permission %(action)s was "
                                    "not granted to %(subject)s "
                                    "because users cannot grant "
                                    "permissions they don't possess.",
                                    action=action,
                                    subject=subject))
                            continue
                        try:
                            perm.grant_permission(target, action)
                        except PermissionExistsError:
                            pass
                        else:
                            add_notice(
                                req,
                                _(
                                    "The subject %(subject)s has "
                                    "been granted the permission "
                                    "%(action)s.",
                                    subject=target,
                                    action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif 'remove' in req.args and 'sel' in req.args:
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                for key in req.args.getlist('sel'):
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _("The selected permissions have been "
                             "revoked."))

            req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'allowed_actions': [a for a in all_actions if a in req.perm],
            'perms': perm.get_users_dict(),
            'groups': perm.get_groups_dict(),
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #11
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                   group and group.isupper():
                raise TracError(
                    _('All upper-cased tokens are reserved for '
                      'permission names'))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm.require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_('Unknown action'))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(
                        req,
                        _(
                            'The subject %(subject)s has been '
                            'granted the permission %(action)s.',
                            subject=subject,
                            action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            'The permission %(action)s was already '
                            'granted to %(subject)s.',
                            action=action,
                            subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm.require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: " \
                            "Permission %s unavailable, skipping perm check." \
                            % (subject, group, action))
                    else:
                        req.perm.require(action)
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(
                        req,
                        _(
                            'The subject %(subject)s has been added '
                            'to the group %(group)s.',
                            subject=subject,
                            group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            'The subject %(subject)s was already '
                            'added to the group %(group)s.',
                            subject=subject,
                            group=group))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm.require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _('The selected permissions have been '
                             'revoked.'))
                req.redirect(req.href.admin(cat, page))

        perms = [perm for perm in all_permissions if perm[1].isupper()]
        groups = [perm for perm in all_permissions if not perm[1].isupper()]

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perms,
            'groups': groups,
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #12
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                   group and group.isupper():
                raise TracError(_('All upper-cased tokens are reserved for '
                                  'permission names'))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm.require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_('Unknown action'))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(req, _('The subject %(subject)s has been '
                                      'granted the permission %(action)s.',
                                      subject=subject, action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _('The permission %(action)s was already '
                                       'granted to %(subject)s.',
                                       action=action, subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm.require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: " \
                            "Permission %s unavailable, skipping perm check." \
                            % (subject, group, action))
                    else:
                        req.perm.require(action)
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(req, _('The subject %(subject)s has been added '
                                      'to the group %(group)s.',
                                      subject=subject, group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _('The subject %(subject)s was already '
                                       'added to the group %(group)s.',
                                       subject=subject, group=group))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm.require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req, _('The selected permissions have been '
                                  'revoked.'))
                req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': all_permissions
        }
Beispiel #13
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(_("All upper-cased tokens are reserved for "
                                  "permission names."))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(req, _("The subject %(subject)s has been "
                                      "granted the permission %(action)s.",
                                      subject=subject, action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _("The permission %(action)s was already "
                                       "granted to %(subject)s.",
                                       action=action, subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: "
                            "Permission %s unavailable, skipping perm check.",
                            subject, group, action)
                    else:
                        req.perm.require(action,
                            message=_("The subject %(subject)s was not added "
                                      "to the group %(group)s because the "
                                      "group has %(perm)s permission and "
                                      "users cannot grant permissions they "
                                      "don't possess.", subject=subject,
                                      group=group, perm=action))
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(req, _("The subject %(subject)s has been added "
                                      "to the group %(group)s.",
                                      subject=subject, group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _("The subject %(subject)s was already "
                                       "added to the group %(group)s.",
                                       subject=subject, group=group))

            # Copy permissions to subject
            elif req.args.get('copy') and subject and target:
                req.perm.require('PERMISSION_GRANT')

                subject_permissions = [i[1] for i in all_permissions
                                            if i[0] == subject and
                                               i[1].isupper()]
                if not subject_permissions:
                    add_warning(req,_("The subject %(subject)s does not "
                                      "have any permissions.",
                                      subject=subject))

                for action in subject_permissions:
                    if (target, action) in all_permissions:
                        continue
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Skipped granting %s to %s: "
                                          "permission unavailable.",
                                          action, target)
                    else:
                        if action not in req.perm:
                            add_warning(req,
                                        _("The permission %(action)s was "
                                          "not granted to %(subject)s "
                                          "because users cannot grant "
                                          "permissions they don't possess.",
                                          action=action, subject=subject))
                            continue
                        perm.grant_permission(target, action)
                        add_notice(req, _("The subject %(subject)s has "
                                          "been granted the permission "
                                          "%(action)s.",
                                          subject=target, action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req, _("The selected permissions have been "
                                  "revoked."))
                req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perm.get_users_dict(),
            'groups': perm.get_groups_dict(),
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #14
0
    def render_admin_panel(self, req, cat, page, path_info):

        add_script(req, "multiproject/js/jquery-ui.js")
        add_script(req, "multiproject/js/permissions.js")
        add_stylesheet(req, "multiproject/css/jquery-ui.css")
        add_stylesheet(req, "multiproject/css/permissions.css")

        is_normal_project = self.env.project_identifier != self.env.config.get("multiproject", "sys_home_project_name")

        # API instances
        perm_sys = PermissionSystem(self.env)
        group_store = CQDEUserGroupStore(env=self.env)
        org_store = CQDEOrganizationStore.instance()
        if is_normal_project:
            membership = MembershipApi(self.env, Project.get(self.env))
        else:
            membership = None

        if req.method == "POST":
            action = req.args.get("action")
            if action == "remove_member":
                self._remove_member(req, group_store)
            elif action == "add_member":
                add_type = req.args.get("add_type")
                if add_type == "user":
                    self._add_user(req, group_store, membership)
                elif add_type == "organization":
                    self._add_organization(req, group_store)
                elif add_type == "ldap_group":
                    self._add_ldap_group(req, group_store)
                elif add_type == "login_status":
                    login_status = req.args.get("login_status")
                    if login_status not in ("authenticated", "anonymous"):
                        raise TracError("Invalid arguments")
                    self._add_user(req, group_store, membership, username=login_status)
                else:
                    raise TracError("Invalid add_type")
            elif action == "add_permission":
                self._add_perm_to_group(req, group_store, perm_sys)
            elif action == "remove_permission":
                self._remove_permission(req, group_store, perm_sys)
            elif action == "create_group":
                self._create_group(req, group_store, perm_sys)
            elif action == "remove_group":
                self._remove_group(req, group_store)
            elif action == "add_organization":
                self._add_organization(req, group_store)
            elif action == "decline_membership":
                self._decline_membership(req, membership)
            else:
                raise TracError("Unknown action %s" % action)

        # get membership request list after form posts have been processed
        if is_normal_project:
            membership_requests = set(membership.get_membership_requests())
        else:
            membership_requests = set()

        permissions = set(perm_sys.get_actions())

        # check if project if current configuration and permission state is in such state that
        # permission editions are likely fail
        invalid_state = None
        try:
            group_store.is_valid_group_members()
        except InvalidPermissionsState, e:
            add_warning(
                req,
                _(
                    "Application permission configuration conflicts with project permissions. "
                    "Before you can fully edit permissions or users you will need to either remove "
                    "offending permissions or set correct application configuration. Page reload"
                    "is required to update this warning."
                ),
            )
            add_warning(req, e.message)
    def render_admin_panel(self, req, cat, page, path_info):

        add_script(req, 'multiproject/js/jquery-ui.js')
        add_script(req, 'multiproject/js/permissions.js')
        add_stylesheet(req, 'multiproject/css/jquery-ui.css')
        add_stylesheet(req, 'multiproject/css/permissions.css')

        project = Project.get(self.env)  #
        is_normal_project = self.env.project_identifier != \
                            self.env.config.get('multiproject', 'sys_home_project_name')

        # API instances
        perm_sys = PermissionSystem(self.env)
        group_store = CQDEUserGroupStore(env=self.env)
        org_store = CQDEOrganizationStore.instance()
        if is_normal_project:
            membership = MembershipApi(self.env, Project.get(self.env))
        else:
            membership = None

        if req.method == 'POST':
            action = req.args.get('action')
            if action == 'remove_member':
                self._remove_member(req, group_store)
            elif action == 'add_member':
                add_type = req.args.get('add_type')
                if add_type == 'user':
                    self._add_user(req, group_store, membership)
                elif add_type == 'organization':
                    self._add_organization(req, group_store)
                elif add_type == 'ldap_group':
                    self._add_ldap_group(req, group_store)
                elif add_type == 'login_status':
                    login_status = req.args.get('login_status')
                    if login_status not in ('authenticated', 'anonymous'):
                        raise TracError('Invalid arguments')
                    self._add_user(req,
                                   group_store,
                                   membership,
                                   username=login_status)
                else:
                    raise TracError('Invalid add_type')
            elif action == 'add_permission':
                self._add_perm_to_group(req, group_store, perm_sys)
            elif action == 'remove_permission':
                self._remove_permission(req, group_store, perm_sys)
            elif action == 'create_group':
                self._create_group(req, group_store, perm_sys)
            elif action == 'remove_group':
                self._remove_group(req, group_store)
            elif action == 'add_organization':
                self._add_organization(req, group_store)
            elif action == 'decline_membership':
                self._decline_membership(req, membership)
            elif 'makepublic' in req.args:
                project_api = Projects()
                if conf.allow_public_projects:
                    self._make_public(req, project)
                    project_api.add_public_project_visibility(project.id)
                    # Reload page
                    return req.redirect(req.href(req.path_info))
                else:
                    raise TracError("Public projects are disabled", "Error!")
            elif 'makeprivate' in req.args:
                project_api = Projects()
                self._make_private(req, project)
                project_api.remove_public_project_visibility(project.id)
                # Reload page
                return req.redirect(req.href(req.path_info))
            else:
                raise TracError('Unknown action %s' % action)

        # get membership request list after form posts have been processed
        if is_normal_project:
            membership_requests = set(membership.get_membership_requests())
        else:
            membership_requests = set()

        permissions = set(perm_sys.get_actions())

        # check if project if current configuration and permission state is in such state that
        # permission editions are likely fail
        invalid_state = None

        if is_normal_project:
            is_a_public = project.public
        else:
            is_a_public = ""

        try:
            group_store.is_valid_group_members()
        except InvalidPermissionsState, e:
            add_warning(
                req,
                _('Application permission configuration conflicts with project permissions. '
                  'Before you can fully edit permissions or users you will need to either remove '
                  'offending permissions or set correct application configuration. Page reload'
                  'is required to update this warning.'))
            add_warning(req, e.message)
Beispiel #16
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(
                    _("All upper-cased tokens are reserved for "
                      "permission names."))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "granted the permission %(action)s.",
                            subject=subject,
                            action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            "The permission %(action)s was already "
                            "granted to %(subject)s.",
                            action=action,
                            subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn(
                            "Adding %s to group %s: "
                            "Permission %s unavailable, skipping perm check.",
                            subject, group, action)
                    else:
                        req.perm.require(
                            action,
                            message=_(
                                "The subject %(subject)s was not added "
                                "to the group %(group)s because the "
                                "group has %(perm)s permission and "
                                "users cannot grant permissions they "
                                "don't possess.",
                                subject=subject,
                                group=group,
                                perm=action))
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been added "
                            "to the group %(group)s.",
                            subject=subject,
                            group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s was already "
                            "added to the group %(group)s.",
                            subject=subject,
                            group=group))

            # Copy permissions to subject
            elif req.args.get('copy') and subject and target:
                req.perm.require('PERMISSION_GRANT')

                subject_permissions = [
                    i[1] for i in all_permissions
                    if i[0] == subject and i[1].isupper()
                ]
                if not subject_permissions:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s does not "
                            "have any permissions.",
                            subject=subject))

                for action in subject_permissions:
                    if (target, action) in all_permissions:
                        continue
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn(
                            "Skipped granting %s to %s: "
                            "permission unavailable.", action, target)
                    else:
                        if action not in req.perm:
                            add_warning(
                                req,
                                _(
                                    "The permission %(action)s was "
                                    "not granted to %(subject)s "
                                    "because users cannot grant "
                                    "permissions they don't possess.",
                                    action=action,
                                    subject=subject))
                            continue
                        perm.grant_permission(target, action)
                        add_notice(
                            req,
                            _(
                                "The subject %(subject)s has "
                                "been granted the permission "
                                "%(action)s.",
                                subject=target,
                                action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _("The selected permissions have been "
                             "revoked."))
                req.redirect(req.href.admin(cat, page))

        perms = [perm for perm in all_permissions if perm[1].isupper()]
        groups = [perm for perm in all_permissions if not perm[1].isupper()]

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perms,
            'groups': groups,
            'unicode_to_base64': unicode_to_base64
        }
    def render_admin_panel(self, req, cat, page, path_info):

        add_script(req, 'multiproject/js/jquery-ui.js')
        add_script(req, 'multiproject/js/permissions.js')
        add_stylesheet(req, 'multiproject/css/jquery-ui.css')
        add_stylesheet(req, 'multiproject/css/permissions.css')
        
        project = Project.get(self.env) #
        is_normal_project = self.env.project_identifier != \
                            self.env.config.get('multiproject', 'sys_home_project_name')

        # API instances
        perm_sys = PermissionSystem(self.env)
        group_store = CQDEUserGroupStore(env=self.env)
        org_store = CQDEOrganizationStore.instance()
        if is_normal_project:
            membership = MembershipApi(self.env, Project.get(self.env))
        else:
            membership = None

        if req.method == 'POST':
            action = req.args.get('action')
            if action == 'remove_member':
                self._remove_member(req, group_store)
            elif action == 'add_member':
                add_type = req.args.get('add_type')
                if add_type == 'user':
                    self._add_user(req, group_store, membership)
                elif add_type == 'organization':
                    self._add_organization(req, group_store)
                elif add_type == 'ldap_group':
                    self._add_ldap_group(req, group_store)
                elif add_type == 'login_status':
                    login_status = req.args.get('login_status')
                    if login_status not in ('authenticated', 'anonymous'):
                        raise TracError('Invalid arguments')
                    self._add_user(req, group_store, membership, username=login_status)
                else:
                    raise TracError('Invalid add_type')
            elif action == 'add_permission':
                self._add_perm_to_group(req, group_store, perm_sys)
            elif action == 'remove_permission':
                self._remove_permission(req, group_store, perm_sys)
            elif action == 'create_group':
                self._create_group(req, group_store, perm_sys)
            elif action == 'remove_group':
                self._remove_group(req, group_store)
            elif action == 'add_organization':
                self._add_organization(req, group_store)
            elif action == 'decline_membership':
                self._decline_membership(req, membership)
            elif 'makepublic' in req.args:
                project_api = Projects()
                if conf.allow_public_projects:
                    self._make_public(req, project)
                    project_api.add_public_project_visibility(project.id)
                    # Reload page
                    return req.redirect(req.href(req.path_info))
                else:
                    raise TracError("Public projects are disabled", "Error!")
            elif 'makeprivate' in req.args:
                project_api = Projects()
                self._make_private(req, project)
                project_api.remove_public_project_visibility(project.id)
                # Reload page
                return req.redirect(req.href(req.path_info))
            else:
                raise TracError('Unknown action %s' % action)

        # get membership request list after form posts have been processed
        if is_normal_project:
            membership_requests = set(membership.get_membership_requests())
        else:
            membership_requests = set()

        permissions = set(perm_sys.get_actions())

        # check if project if current configuration and permission state is in such state that
        # permission editions are likely fail
        invalid_state = None

        if is_normal_project:
            is_a_public = project.public
        else:
            is_a_public = ""


        try:
            group_store.is_valid_group_members()
        except InvalidPermissionsState, e:
            add_warning(req, _('Application permission configuration conflicts with project permissions. '
                               'Before you can fully edit permissions or users you will need to either remove '
                               'offending permissions or set correct application configuration. Page reload'
                               'is required to update this warning.'))
            add_warning(req, e.message)
Beispiel #18
0
class TagSystemTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub(default_data=True,
                                   enable=['trac.*', 'tractags.*'])
        self.env.path = tempfile.mkdtemp()
        self.perms = PermissionSystem(self.env)
        self.req = Mock()

        self.actions = ['TAGS_ADMIN', 'TAGS_MODIFY', 'TAGS_VIEW']
        self.tag_s = TagSystem(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)

    def tearDown(self):
        self.db.close()
        # Really close db connections.
        self.env.shutdown()
        shutil.rmtree(self.env.path)

    # Helpers

    def _revert_tractags_schema_init(self):
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE IF EXISTS tags")
        cursor.execute("DELETE FROM system WHERE name='tags_version'")
        cursor.execute(
            "DELETE FROM permission WHERE action %s" % self.db.like(),
            ('TAGS_%', ))

    # Tests

    def test_available_actions(self):
        for action in self.actions:
            self.failIf(action not in self.perms.get_actions())

    def test_available_providers(self):
        # Standard implementations of DefaultTagProvider should be registered.
        seen = []
        for provider in [
                TicketTagProvider(self.env),
                WikiTagProvider(self.env)
        ]:
            self.failIf(provider not in self.tag_s.tag_providers)
            # Ensure unique provider references, a possible bug in Trac-0.11.
            self.failIf(provider in seen)
            seen.append(provider)

    def test_set_tags_no_perms(self):
        resource = Resource('wiki', 'WikiStart')
        tags = ['tag1']
        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
        self.assertRaises(PermissionError, self.tag_s.set_tags, self.req,
                          resource, tags)

    def test_set_tags(self):
        resource = Resource('wiki', 'WikiStart')
        tags = ['tag1']
        self.req.perm = PermissionCache(self.env, username='******')
        # Shouldn't raise an error with appropriate permission.
        self.tag_s.set_tags(self.req, resource, tags)

    def test_query_no_args(self):
        # Regression test for query without argument,
        #   reported as th:ticket:7857.

        # Mock an anonymous request.
        self.req.perm = PermissionCache(self.env)
        self.assertEquals(
            [(res, tags)
             for res, tags in self.tag_s.query(self.req, query='')], [])