Changeset - 7aff9a999536
[Not reviewed]
stable
0 7 0
Thomas De Schampheleire - 7 years ago 2019-04-29 21:33:45
thomas.de_schampheleire@nokia.com
templates, controllers: replace webhelpers.html.literal() with webhelpers.html.HTML() where possible

Usage of webhelpers.literal (h.literal) can be a problem when variables are
not correctly escaped. Luckily, this function can be avoided in several
cases.

Several users of the construct:
h.literal(_('..A..') % (..B..))

can be simplified if (..B..) just contains a call to h.link_to. In this
case, there is actually no need to use h.literal, because the object
returned by link_to is already a literal. It is sufficient to use
webhelpers.html.HTML() like so:
h.HTML(_('..A..')) % (..B..)

which is better because it will escape the '..A..' part instead of passing
it literally.

The need to wrap the '..A..' part in HTML() is to make sure the (escaped)
end result is not a plain string but a 'literal' to avoid double escaping
later.

See also the documentation:
https://docs.pylonsproject.org/projects/webhelpers/en/latest/modules/html/builder.html
"
When literal is used in a mixed expression containing both literals and
ordinary strings, it tries hard to escape the strings and return a
literal. However, this depends on which value has “control” of the
expression. literal seems to be able to take control with all
combinations of the + operator, but with % and join it must be on the
left side of the expression. So these all work:

"A" + literal("B")
literal(", ").join(["A", literal("B")])
literal("%s %s") % (16, literal("kg"))

But these return an ordinary string which is prone to double-escaping later:

"\n".join([literal('<span class="foo">Foo!</span>'), literal('Bar!')])
"%s %s" % (literal("16"), literal("&lt;em&gt;kg&lt;/em&gt;"))
"

This same escaping with 'HTML()' was already done by default in mako
templates for constructs like ${_("something")} that do not contain format
specifiers. When the translated string _does_ contain format specifiers, we
want to use the same escaping, but we have to do it explicit and earlier so
the escaping happens already when strings are inserted into the template
string.
7 files changed with 14 insertions and 14 deletions:
0 comments (0 inline, 0 general)
kallithea/controllers/admin/repos.py
Show inline comments
 
@@ -192,28 +192,28 @@ class ReposController(BaseRepoController
 
        repo = Repository.get_by_repo_name(repo_name)
 
        if repo and repo.repo_state == Repository.STATE_CREATED:
 
            if repo.clone_uri:
 
                h.flash(_('Created repository %s from %s')
 
                        % (repo.repo_name, repo.clone_uri_hidden), category='success')
 
            else:
 
                repo_url = h.link_to(repo.repo_name,
 
                                     h.url('summary_home',
 
                                           repo_name=repo.repo_name))
 
                fork = repo.fork
 
                if fork is not None:
 
                    fork_name = fork.repo_name
 
                    h.flash(h.literal(_('Forked repository %s as %s')
 
                            % (fork_name, repo_url)), category='success')
 
                    h.flash(h.HTML(_('Forked repository %s as %s'))
 
                            % (fork_name, repo_url), category='success')
 
                else:
 
                    h.flash(h.literal(_('Created repository %s') % repo_url),
 
                    h.flash(h.HTML(_('Created repository %s')) % repo_url,
 
                            category='success')
 
            return {'result': True}
 
        return {'result': False}
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def update(self, repo_name):
 
        c.repo_info = self._load_repo()
 
        self.__load_defaults(c.repo_info)
 
        c.active = 'settings'
 
        c.repo_fields = RepositoryField.query() \
 
            .filter(RepositoryField.repository == c.repo_info).all()
 

	
kallithea/controllers/admin/settings.py
Show inline comments
 
@@ -162,32 +162,32 @@ class SettingsController(BaseController)
 
            install_git_hooks = request.POST.get('hooks', False)
 
            overwrite_git_hooks = request.POST.get('hooks_overwrite', False)
 
            invalidate_cache = request.POST.get('invalidate', False)
 
            log.debug('rescanning repo location with destroy obsolete=%s, '
 
                      'install git hooks=%s and '
 
                      'overwrite git hooks=%s' % (rm_obsolete, install_git_hooks, overwrite_git_hooks))
 

	
 
            filesystem_repos = ScmModel().repo_scan()
 
            added, removed = repo2db_mapper(filesystem_repos, rm_obsolete,
 
                                            install_git_hooks=install_git_hooks,
 
                                            user=request.authuser.username,
 
                                            overwrite_git_hooks=overwrite_git_hooks)
 
            added_msg = ', '.join(
 
            added_msg = h.HTML(', ').join(
 
                h.link_to(safe_unicode(repo_name), h.url('summary_home', repo_name=repo_name)) for repo_name in added
 
            ) or '-'
 
            removed_msg = ', '.join(
 
                h.escape(safe_unicode(repo_name)) for repo_name in removed
 
            removed_msg = h.HTML(', ').join(
 
                safe_unicode(repo_name) for repo_name in removed
 
            ) or '-'
 
            h.flash(h.literal(_('Repositories successfully rescanned. Added: %s. Removed: %s.') %
 
                    (added_msg, removed_msg)), category='success')
 
            h.flash(h.HTML(_('Repositories successfully rescanned. Added: %s. Removed: %s.')) %
 
                    (added_msg, removed_msg), category='success')
 

	
 
            if invalidate_cache:
 
                log.debug('invalidating all repositories cache')
 
                i = 0
 
                for repo in Repository.query():
 
                    try:
 
                        ScmModel().mark_for_invalidation(repo.repo_name)
 
                        i += 1
 
                    except VCSError as e:
 
                        log.warning('VCS error invalidating %s: %s', repo.repo_name, e)
 
                h.flash(_('Invalidated %s repositories') % i, category='success')
 

	
kallithea/controllers/admin/user_groups.py
Show inline comments
 
@@ -131,25 +131,25 @@ class UserGroupsController(BaseControlle
 
        users_group_form = UserGroupForm()()
 
        try:
 
            form_result = users_group_form.to_python(dict(request.POST))
 
            ug = UserGroupModel().create(name=form_result['users_group_name'],
 
                                         description=form_result['user_group_description'],
 
                                         owner=request.authuser.user_id,
 
                                         active=form_result['users_group_active'])
 

	
 
            gr = form_result['users_group_name']
 
            action_logger(request.authuser,
 
                          'admin_created_users_group:%s' % gr,
 
                          None, request.ip_addr)
 
            h.flash(h.literal(_('Created user group %s') % h.link_to(h.escape(gr), url('edit_users_group', id=ug.users_group_id))),
 
            h.flash(h.HTML(_('Created user group %s')) % h.link_to(gr, url('edit_users_group', id=ug.users_group_id)),
 
                category='success')
 
            Session().commit()
 
        except formencode.Invalid as errors:
 
            return htmlfill.render(
 
                render('admin/user_groups/user_group_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8",
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
kallithea/templates/admin/gists/edit.html
Show inline comments
 
@@ -23,25 +23,25 @@
 
</%block>
 

	
 
<%def name="main()">
 
<div class="panel panel-primary">
 
    <div class="panel-heading clearfix">
 
        ${self.breadcrumbs()}
 
    </div>
 

	
 
    <div class="panel-body">
 
        <div id="edit_error" style="display: none" class="flash_msg">
 
            <div class="alert alert-dismissable alert-warning">
 
              <button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="icon-cancel-circled"></i></button>
 
              ${h.literal(_('Gist was updated since you started editing. Copy your changes and click %(here)s to reload new version.')
 
              ${(h.HTML(_('Gist was updated since you started editing. Copy your changes and click %(here)s to reload new version.'))
 
                             % {'here': h.link_to(_('here'),h.url('edit_gist', gist_id=c.gist.gist_access_id))})}
 
            </div>
 
            <script>
 
            if (typeof jQuery != 'undefined') {
 
                $(".alert").alert();
 
            }
 
            </script>
 
        </div>
 

	
 
        <div id="files_data">
 
          ${h.form(h.url('edit_gist', gist_id=c.gist.gist_access_id), method='post', id='eform')}
 
            <div>
kallithea/templates/admin/permissions/permissions_globals.html
Show inline comments
 
${h.form(url('admin_permissions'), method='post')}
 
    <div class="form">
 
            <div class="form-group">
 
                <label class="control-label" for="anonymous">${_('Anonymous access')}:</label>
 
                <div class="form-inline">
 
                    <label>
 
                        ${h.checkbox('anonymous',True)}
 
                        <span>${_('Allow anonymous access')}</span>
 
                    </label>
 
                    <span class="help-block">${h.literal(_('Allow access to Kallithea without needing to log in. Anonymous users use %s user permissions.') % (h.link_to('*default*',h.url('admin_permissions_perms'))))}</span>
 
                    <span class="help-block">${h.HTML(_('Allow access to Kallithea without needing to log in. Anonymous users use %s user permissions.')) % (h.link_to('*default*',h.url('admin_permissions_perms')))}</span>
 
                </div>
 
            </div>
 
            <div class="form-group">
 
                <label class="control-label" for="default_repo_perm">${_('Repository')}:</label>
 
                <div class="form-inline">
 
                    ${h.select('default_repo_perm','',c.repo_perms_choices,class_='form-control')}
 
                    <label>
 
                        ${h.checkbox('overwrite_default_repo','true')}
 
                        <span data-toggle="tooltip" title="${_('All default permissions on each repository will be reset to chosen permission, note that all custom default permission on repositories will be lost')}">
 
                            ${_('Apply to all existing repositories')}
 
                        </span>
 
                    </label>
kallithea/templates/admin/users/user_edit_ips.html
Show inline comments
 
<table class="table">
 
    %if c.default_user_ip_map and c.inherit_default_ips:
 
        %for ip in c.default_user_ip_map:
 
          <tr>
 
            <td><div class="ip">${ip.ip_addr}</div></td>
 
            <td><div class="ip">${h.ip_range(ip.ip_addr)}</div></td>
 
            <td>${h.literal(_('Inherited from %s') % h.link_to('*default*',h.url('admin_permissions_ips')))}</td>
 
            <td>${h.HTML(_('Inherited from %s')) % h.link_to('*default*',h.url('admin_permissions_ips'))}</td>
 
          </tr>
 
        %endfor
 
    %endif
 

	
 
    %if c.user_ip_map:
 
        %for ip in c.user_ip_map:
 
          <tr>
 
            <td><div class="ip">${ip.ip_addr}</div></td>
 
            <td><div class="ip">${h.ip_range(ip.ip_addr)}</div></td>
 
            <td>
 
                ${h.form(url('edit_user_ips_delete', id=c.user.user_id))}
 
                    ${h.hidden('del_ip_id',ip.ip_id)}
kallithea/templates/base/default_perms_box.html
Show inline comments
 
@@ -3,26 +3,26 @@
 
##    <%namespace name="dpb" file="/base/default_perms_box.html"/>
 
##    ${dpb.default_perms_box(<url_to_form>)}
 

	
 

	
 
<%def name="default_perms_box(form_url)">
 
${h.form(form_url)}
 
    <div class="form">
 
            <div class="form-group">
 
                <label class="control-label" for="inherit_default_permissions">${_('Inherit defaults')}:</label>
 
                <div>
 
                    ${h.checkbox('inherit_default_permissions',value=True)}
 
                    <span class="help-block">
 
                        ${h.literal(_('Select to inherit global settings, IP whitelist and permissions from the %s.')
 
                                    % h.link_to(_('default permissions'), url('admin_permissions')))}
 
                        ${(h.HTML(_('Select to inherit global settings, IP whitelist and permissions from the %s.'))
 
                                % h.link_to(_('default permissions'), url('admin_permissions')))}
 
                    </span>
 
                </div>
 
            </div>
 

	
 
            <div id="inherit_overlay">
 
            <div class="form-group">
 
                <label class="control-label" for="create_repo_perm">${_('Create repositories')}:</label>
 
                <div>
 
                    ${h.checkbox('create_repo_perm',value=True)}
 
                    <span class="help-block">
 
                        ${_('Select this option to allow repository creation for this user')}
 
                    </span>
0 comments (0 inline, 0 general)