Exemple #1
0
    def test_templates_need_update_true(self):
        """Templates need to be updated."""
        self.env.config.set('notification', 'ticket_subject_template',
                            '$prefix #$ticket.id: $summary')
        self.env.config.set('notification', 'batch_subject_template',
                            '$prefix Batch modify: $tickets_descr')
        self.env.config.save()

        db45.do_upgrade(self.env, None, None)

        self.assertIn(('INFO', 'Replaced value of [notification] '
                       'ticket_subject_template: $prefix #$ticket.id: '
                       '$summary -> ${prefix} #${ticket.id}: ${summary}'),
                      self.env.log_messages)
        self.assertIn(('INFO', 'Replaced value of [notification] '
                       'batch_subject_template: $prefix Batch modify: '
                       '$tickets_descr -> ${prefix} Batch modify: '
                       '${tickets_descr}'), self.env.log_messages)
        parser = UnicodeConfigParser()
        parser.read(self.env.config.filename)
        self.assertEqual('${prefix} #${ticket.id}: ${summary}',
                         parser.get('notification', 'ticket_subject_template'))
        self.assertEqual('${prefix} Batch modify: ${tickets_descr}',
                         parser.get('notification', 'batch_subject_template'))
        self.assertTrue(self._backup_file_exists())
    def parse_authz(self):
        self.log.debug("Parsing authz security policy %s", self.authz_file)

        self.authz = UnicodeConfigParser()
        try:
            self.authz.read(self.authz_file)
        except ParsingError as e:
            self.log.error("Error parsing authz permission policy file: %s",
                           to_unicode(e))
            raise ConfigurationError()
        groups = {}
        if self.authz.has_section('groups'):
            for group, users in self.authz.items('groups'):
                groups[group] = to_list(users)

        self.groups_by_user = {}

        def add_items(group, items):
            for item in items:
                if item.startswith('@'):
                    add_items(group, groups[item[1:]])
                else:
                    self.groups_by_user.setdefault(item, set()).add(group)

        for group, users in groups.iteritems():
            add_items('@' + group, users)

        self.authz_mtime = os.path.getmtime(self.authz_file)
Exemple #3
0
    def enable_authz_permpolicy(self, authz_content, filename=None):
        """Enables the Authz permissions policy. The `authz_content` will
        be written to `filename`, and may be specified in a triple-quoted
        string.::

           [wiki:WikiStart@*]
           * = WIKI_VIEW
           [wiki:PrivatePage@*]
           john = WIKI_VIEW
           * = !WIKI_VIEW

        `authz_content` may also be a dictionary of dictionaries specifying
        the sections and key/value pairs of each section, however this form
        should only be used when the order of the entries in the file is not
        important, as the order cannot be known.::

           {
            'wiki:WikiStart@*': {'*': 'WIKI_VIEW'},
            'wiki:PrivatePage@*': {'john': 'WIKI_VIEW', '*': '!WIKI_VIEW'},
           }

        The `filename` parameter is optional, and if omitted a filename will
        be generated by computing a hash of `authz_content`, prefixed with
        "authz-".
        """
        if filename is None:
            filename = 'authz-' + \
                       hashlib.md5(str(authz_content)).hexdigest()[:9]
        env = self.get_trac_environment()
        authz_file = os.path.join(env.conf_dir, filename)
        if os.path.exists(authz_file):
            wait_for_file_mtime_change(authz_file)
        if isinstance(authz_content, basestring):
            authz_content = [
                line.strip() + '\n'
                for line in authz_content.strip().splitlines()
            ]
            authz_content = ['# -*- coding: utf-8 -*-\n'] + authz_content
            create_file(authz_file, authz_content)
        else:
            parser = UnicodeConfigParser()
            for section, options in authz_content.items():
                parser.add_section(section)
                for key, value in options.items():
                    parser.set(section, key, value)
            with open(authz_file, 'w') as f:
                parser.write(f)
        permission_policies = env.config.get('trac', 'permission_policies')
        env.config.set('trac', 'permission_policies',
                       'AuthzPolicy, ' + permission_policies)
        env.config.set('authz_policy', 'authz_file', authz_file)
        env.config.set('components', 'tracopt.perm.authz_policy.*', 'enabled')
        env.config.save()
Exemple #4
0
    def parse_authz(self):
        self.log.debug("Parsing authz security policy %s", self.authz_file)

        if not self.authz_file:
            self.log.error("The `[authz_policy] authz_file` configuration "
                           "option in trac.ini is empty or not defined.")
            raise ConfigurationError()
        try:
            authz_mtime = os.path.getmtime(self.authz_file)
        except OSError as e:
            self.log.error("Error parsing authz permission policy file: %s",
                           exception_to_unicode(e))
            raise ConfigurationError()

        self.authz = UnicodeConfigParser(ignorecase_option=False)
        try:
            self.authz.read(self.authz_file)
        except configparser.ParsingError as e:
            self.log.error("Error parsing authz permission policy file: %s",
                           exception_to_unicode(e))
            raise ConfigurationError()
        groups = {}
        if self.authz.has_section('groups'):
            for group, users in self.authz.items('groups'):
                groups[group] = to_list(users)

        self.groups_by_user = {}

        def add_items(group, items):
            for item in items:
                if item.startswith('@'):
                    add_items(group, groups[item[1:]])
                else:
                    self.groups_by_user.setdefault(item, set()).add(group)

        for group, users in groups.items():
            add_items('@' + group, users)

        all_actions = set(PermissionSystem(self.env).get_actions())
        authz_basename = os.path.basename(self.authz_file)
        for section in self.authz.sections():
            if section == 'groups':
                continue
            for user, actions in self.authz.items(section):
                for action in to_list(actions):
                    if action.startswith('!'):
                        action = action[1:]
                    if action not in all_actions:
                        self.log.warning(
                            "The action %s in the [%s] section "
                            "of %s is not a valid action.", action, section,
                            authz_basename)
        self.authz_mtime = authz_mtime
Exemple #5
0
 def setUp(self):
     self.tempdir = mkdtemp()
     self.filename = os.path.join(self.tempdir, 'config.ini')
     _write(self.filename, [
         u'[ä]', u'öption = ÿ',
         u'[ä]', u'optīon = 1.1',
         u'[č]', u'ôption = ž',
         u'[č]', u'optïon = 1',
         u'[ė]', u'optioñ = true',
     ])
     self.parser = UnicodeConfigParser()
     self._read()
Exemple #6
0
def parse(authz_file, modules):
    """Parse a Subversion authorization file.

    Return a dict of modules, each containing a dict of paths, each containing
    a dict mapping users to permissions. Only modules contained in `modules`
    are retained.
    """
    parser = UnicodeConfigParser(ignorecase_option=False)
    parser.read(authz_file)

    groups = {}
    aliases = {}
    sections = {}
    for section in parser.sections():
        if section == 'groups':
            for name, value in parser.items(section):
                groups.setdefault(name, set()).update(to_list(value))
        elif section == 'aliases':
            for name, value in parser.items(section):
                aliases[name] = value.strip()
        else:
            for name, value in parser.items(section):
                parts = section.split(':', 1)
                module, path = parts[0] if len(parts) > 1 else '', parts[-1]
                if module in modules:
                    sections.setdefault((module, path), []) \
                            .append((name, value))

    def resolve(subject, done):
        if subject.startswith('@'):
            done.add(subject)
            for members in groups[subject[1:]] - done:
                for each in resolve(members, done):
                    yield each
        elif subject.startswith('&'):
            yield aliases[subject[1:]]
        else:
            yield subject

    authz = {}
    for (module, path), items in sections.iteritems():
        section = authz.setdefault(module, {}).setdefault(path, {})
        for subject, perms in items:
            readable = 'r' in perms
            # Ordering isn't significant; any entry could grant permission
            section.update((user, readable)
                           for user in resolve(subject, set())
                           if not section.get(user))
    return authz