test_xss_linter.py 60.6 KB
Newer Older
1
# -*- coding: utf-8 -*-
Robert Raposa committed
2
"""
3
Tests for xss_linter.py
Robert Raposa committed
4
"""
5
import re
Robert Raposa committed
6
import textwrap
7
from StringIO import StringIO
Robert Raposa committed
8 9
from unittest import TestCase

10 11 12
import mock
from ddt import data, ddt

13
from scripts.xss_linter import (
14 15 16 17 18 19 20 21 22 23
    FileResults,
    JavaScriptLinter,
    MakoTemplateLinter,
    ParseString,
    PythonLinter,
    Rules,
    StringLines,
    SummaryResults,
    UnderscoreTemplateLinter,
    _lint
Robert Raposa committed
24 25 26
)


Robert Raposa committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
@ddt
class TestStringLines(TestCase):
    """
    Test StringLines class.
    """
    @data(
        {'string': 'test', 'index': 0, 'line_start_index': 0, 'line_end_index': 4},
        {'string': 'test', 'index': 2, 'line_start_index': 0, 'line_end_index': 4},
        {'string': 'test', 'index': 3, 'line_start_index': 0, 'line_end_index': 4},
        {'string': '\ntest', 'index': 0, 'line_start_index': 0, 'line_end_index': 1},
        {'string': '\ntest', 'index': 2, 'line_start_index': 1, 'line_end_index': 5},
        {'string': '\ntest\n', 'index': 0, 'line_start_index': 0, 'line_end_index': 1},
        {'string': '\ntest\n', 'index': 2, 'line_start_index': 1, 'line_end_index': 6},
        {'string': '\ntest\n', 'index': 6, 'line_start_index': 6, 'line_end_index': 6},
    )
    def test_string_lines_start_end_index(self, data):
        """
        Test StringLines index_to_line_start_index and index_to_line_end_index.
        """
        lines = StringLines(data['string'])
        self.assertEqual(lines.index_to_line_start_index(data['index']), data['line_start_index'])
        self.assertEqual(lines.index_to_line_end_index(data['index']), data['line_end_index'])

    @data(
        {'string': 'test', 'line_number': 1, 'line': 'test'},
        {'string': '\ntest', 'line_number': 1, 'line': ''},
        {'string': '\ntest', 'line_number': 2, 'line': 'test'},
        {'string': '\ntest\n', 'line_number': 1, 'line': ''},
        {'string': '\ntest\n', 'line_number': 2, 'line': 'test'},
        {'string': '\ntest\n', 'line_number': 3, 'line': ''},
    )
    def test_string_lines_start_end_index(self, data):
        """
        Test line_number_to_line.
        """
        lines = StringLines(data['string'])
        self.assertEqual(lines.line_number_to_line(data['line_number']), data['line'])


66 67 68 69
class TestLinter(TestCase):
    """
    Test Linter base class
    """
Robert Raposa committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83
    def _validate_data_rules(self, data, results):
        """
        Validates that the appropriate rule violations were triggered.

        Arguments:
            data: A dict containing the 'rule' (or rules) to be tests.
            results: The results, containing violations to be validated.

        """
        rules = []
        if isinstance(data['rule'], list):
            rules = data['rule']
        elif data['rule'] is not None:
            rules.append(data['rule'])
84
        results.violations.sort(key=lambda violation: violation.sort_key())
85 86 87 88 89 90 91

        # Print violations if the lengths are different.
        if len(results.violations) != len(rules):
            for violation in results.violations:
                print("Found violation: {}".format(violation.rule))

        self.assertEqual(len(results.violations), len(rules))
Robert Raposa committed
92 93
        for violation, rule in zip(results.violations, rules):
            self.assertEqual(violation.rule, rule)
94 95


96
class TestXSSLinter(TestCase):
97 98 99 100
    """
    Test some top-level linter functions
    """

101 102 103 104 105 106 107 108 109
    def setUp(self):
        """
        Setup patches on linters for testing.
        """
        self.patch_is_valid_directory(MakoTemplateLinter)
        self.patch_is_valid_directory(JavaScriptLinter)
        self.patch_is_valid_directory(UnderscoreTemplateLinter)
        self.patch_is_valid_directory(PythonLinter)

110
        patcher = mock.patch('scripts.xss_linter.is_skip_dir', return_value=False)
111 112 113
        patcher.start()
        self.addCleanup(patcher.stop)

114 115 116 117 118 119 120 121 122 123 124 125 126
    def patch_is_valid_directory(self, linter_class):
        """
        Creates a mock patch for _is_valid_directory on a Linter to always
        return true. This avoids nested patch calls.

        Arguments:
            linter_class: The linter class to be patched
        """
        patcher = mock.patch.object(linter_class, '_is_valid_directory', return_value=True)
        patch_start = patcher.start()
        self.addCleanup(patcher.stop)
        return patch_start

127
    def test_lint_defaults(self):
128
        """
129
        Tests the top-level linting with default options.
130 131
        """
        out = StringIO()
132 133 134 135 136 137 138 139 140 141 142 143 144
        summary_results = SummaryResults()

        _lint(
            'scripts/tests/templates',
            template_linters=[MakoTemplateLinter(), UnderscoreTemplateLinter(), JavaScriptLinter(), PythonLinter()],
            options={
                'list_files': False,
                'verbose': False,
                'rule_totals': False,
            },
            summary_results=summary_results,
            out=out,
        )
145 146

        output = out.getvalue()
147
        # Assert violation details are displayed.
148 149 150 151 152
        self.assertIsNotNone(re.search('test\.html.*{}'.format(Rules.mako_missing_default.rule_id), output))
        self.assertIsNotNone(re.search('test\.coffee.*{}'.format(Rules.javascript_concat_html.rule_id), output))
        self.assertIsNotNone(re.search('test\.coffee.*{}'.format(Rules.underscore_not_escaped.rule_id), output))
        self.assertIsNotNone(re.search('test\.js.*{}'.format(Rules.javascript_concat_html.rule_id), output))
        self.assertIsNotNone(re.search('test\.js.*{}'.format(Rules.underscore_not_escaped.rule_id), output))
153 154 155 156 157 158 159 160 161
        lines_with_rule = 0
        lines_without_rule = 0  # Output with verbose setting only.
        for underscore_match in re.finditer('test\.underscore:.*\n', output):
            if re.search(Rules.underscore_not_escaped.rule_id, underscore_match.group()) is not None:
                lines_with_rule += 1
            else:
                lines_without_rule += 1
        self.assertGreaterEqual(lines_with_rule, 1)
        self.assertEquals(lines_without_rule, 0)
162 163
        self.assertIsNone(re.search('test\.py.*{}'.format(Rules.python_parse_error.rule_id), output))
        self.assertIsNotNone(re.search('test\.py.*{}'.format(Rules.python_wrap_html.rule_id), output))
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        # Assert no rule totals.
        self.assertIsNone(re.search('{}:\s*{} violations'.format(Rules.python_parse_error.rule_id, 0), output))
        # Assert final total
        self.assertIsNotNone(re.search('{} violations total'.format(7), output))

    def test_lint_with_verbose(self):
        """
        Tests the top-level linting with verbose option.
        """
        out = StringIO()
        summary_results = SummaryResults()

        _lint(
            'scripts/tests/templates',
            template_linters=[MakoTemplateLinter(), UnderscoreTemplateLinter(), JavaScriptLinter(), PythonLinter()],
            options={
                'list_files': False,
                'verbose': True,
                'rule_totals': False,
            },
            summary_results=summary_results,
            out=out,
        )

        output = out.getvalue()
        lines_with_rule = 0
        lines_without_rule = 0  # Output with verbose setting only.
        for underscore_match in re.finditer('test\.underscore:.*\n', output):
            if re.search(Rules.underscore_not_escaped.rule_id, underscore_match.group()) is not None:
                lines_with_rule += 1
            else:
                lines_without_rule += 1
        self.assertGreaterEqual(lines_with_rule, 1)
        self.assertGreaterEqual(lines_without_rule, 1)
        # Assert no rule totals.
        self.assertIsNone(re.search('{}:\s*{} violations'.format(Rules.python_parse_error.rule_id, 0), output))
        # Assert final total
        self.assertIsNotNone(re.search('{} violations total'.format(7), output))

    def test_lint_with_rule_totals(self):
        """
        Tests the top-level linting with rule totals option.
        """
        out = StringIO()
        summary_results = SummaryResults()

        _lint(
            'scripts/tests/templates',
            template_linters=[MakoTemplateLinter(), UnderscoreTemplateLinter(), JavaScriptLinter(), PythonLinter()],
            options={
                'list_files': False,
                'verbose': False,
                'rule_totals': True,
            },
            summary_results=summary_results,
            out=out,
        )

        output = out.getvalue()
        self.assertIsNotNone(re.search('test\.py.*{}'.format(Rules.python_wrap_html.rule_id), output))

        # Assert totals output.
        self.assertIsNotNone(re.search('{}:\s*{} violations'.format(Rules.python_parse_error.rule_id, 0), output))
        self.assertIsNotNone(re.search('{}:\s*{} violations'.format(Rules.python_wrap_html.rule_id, 1), output))
        self.assertIsNotNone(re.search('{} violations total'.format(7), output))

    def test_lint_with_list_files(self):
        """
        Tests the top-level linting with list files option.
        """
        out = StringIO()
        summary_results = SummaryResults()

        _lint(
            'scripts/tests/templates',
            template_linters=[MakoTemplateLinter(), UnderscoreTemplateLinter(), JavaScriptLinter(), PythonLinter()],
            options={
                'list_files': True,
                'verbose': False,
                'rule_totals': False,
            },
            summary_results=summary_results,
            out=out,
        )

        output = out.getvalue()
        # Assert file with rule is not output.
        self.assertIsNone(re.search('test\.py.*{}'.format(Rules.python_wrap_html.rule_id), output))
        # Assert file is output.
        self.assertIsNotNone(re.search('test\.py', output))

        # Assert no totals.
        self.assertIsNone(re.search('{}:\s*{} violations'.format(Rules.python_parse_error.rule_id, 0), output))
        self.assertIsNone(re.search('{} violations total'.format(7), output))
258 259


Robert Raposa committed
260
@ddt
261
class TestMakoTemplateLinter(TestLinter):
Robert Raposa committed
262 263 264 265 266 267 268 269
    """
    Test MakoTemplateLinter
    """

    @data(
        {'directory': 'lms/templates', 'expected': True},
        {'directory': 'lms/templates/support', 'expected': True},
        {'directory': 'lms/templates/support', 'expected': True},
270
        {'directory': 'test_root/staticfiles/templates', 'expected': False},
Robert Raposa committed
271 272 273
        {'directory': './test_root/staticfiles/templates', 'expected': False},
        {'directory': './some/random/path', 'expected': False},
    )
274
    def test_is_valid_directory(self, data):
Robert Raposa committed
275
        """
276
        Test _is_valid_directory correctly determines mako directories
Robert Raposa committed
277 278 279
        """
        linter = MakoTemplateLinter()

280
        self.assertEqual(linter._is_valid_directory(data['directory']), data['expected'])
Robert Raposa committed
281

282 283 284 285 286 287 288 289 290 291 292
    @data(
        {
            'template': '\n <%page expression_filter="h"/>',
            'rule': None
        },
        {
            'template':
                '\n <%page args="section_data" expression_filter="h" /> ',
            'rule': None
        },
        {
Robert Raposa committed
293 294 295 296
            'template': '\n ## <%page expression_filter="h"/>',
            'rule': Rules.mako_missing_default
        },
        {
297 298 299 300 301 302
            'template':
                '\n <%page expression_filter="h" /> '
                '\n <%page args="section_data"/>',
            'rule': Rules.mako_multiple_page_tags
        },
        {
Robert Raposa committed
303 304 305 306 307 308
            'template':
                '\n <%page expression_filter="h" /> '
                '\n ## <%page args="section_data"/>',
            'rule': None
        },
        {
309 310 311 312 313 314 315 316 317 318 319 320 321 322
            'template': '\n <%page args="section_data" /> ',
            'rule': Rules.mako_missing_default
        },
        {
            'template':
                '\n <%page args="section_data"/> <some-other-tag expression_filter="h" /> ',
            'rule': Rules.mako_missing_default
        },
        {
            'template': '\n',
            'rule': Rules.mako_missing_default
        },
    )
    def test_check_page_default(self, data):
Robert Raposa committed
323
        """
324
        Test _check_mako_file_is_safe with different page defaults
Robert Raposa committed
325 326 327 328
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

329
        linter._check_mako_file_is_safe(data['template'], results)
Robert Raposa committed
330

Robert Raposa committed
331 332 333
        num_violations = 0 if data['rule'] is None else 1
        self.assertEqual(len(results.violations), num_violations)
        if num_violations > 0:
334
            self.assertEqual(results.violations[0].rule, data['rule'])
Robert Raposa committed
335

336 337 338 339
    @data(
        {'expression': '${x}', 'rule': None},
        {'expression': '${{unbalanced}', 'rule': Rules.mako_unparseable_expression},
        {'expression': '${x | n}', 'rule': Rules.mako_invalid_html_filter},
Robert Raposa committed
340
        {'expression': '${x | n, decode.utf8}', 'rule': None},
341
        {'expression': '${x | h}', 'rule': Rules.mako_unwanted_html_filter},
Robert Raposa committed
342
        {'expression': '  ## ${commented_out | h}', 'rule': None},
343 344 345
        {'expression': '${x | n, dump_js_escaped_json}', 'rule': Rules.mako_invalid_html_filter},
    )
    def test_check_mako_expressions_in_html(self, data):
Robert Raposa committed
346 347 348 349 350 351 352 353
        """
        Test _check_mako_file_is_safe in html context provides appropriate violations
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
354 355
            {expression}
        """.format(expression=data['expression']))
Robert Raposa committed
356 357 358

        linter._check_mako_file_is_safe(mako_template, results)

Robert Raposa committed
359
        self._validate_data_rules(data, results)
Robert Raposa committed
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    def test_check_mako_expression_display_name(self):
        """
        Test _check_mako_file_is_safe with display_name_with_default_escaped
        fails.
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            ${course.display_name_with_default_escaped}
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
Robert Raposa committed
377
        self.assertEqual(results.violations[0].rule, Rules.python_deprecated_display_name)
378

379 380
    @data(
        {
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            # Python blocks between <% ... %> use the same Python linting as
            # Mako expressions between ${ ... }. This single test verifies
            # that these blocks are linted. The individual linting rules are
            # tested in the Mako expression tests that follow.
            'expression':
                textwrap.dedent("""
                    <%
                        a_link_start = '<a class="link-courseURL" rel="external" href="'
                        a_link_end = '">' + _("your course summary page") + '</a>'
                        a_link = a_link_start + lms_link_for_about_page + a_link_end
                        text = _("Introductions, prerequisites, FAQs that are used on %s (formatted in HTML)") % a_link
                    %>
                """),
            'rule': [Rules.python_wrap_html, Rules.python_concat_html, Rules.python_wrap_html]
        },
        {
397 398 399 400 401 402 403
            'expression':
                textwrap.dedent("""
                    ${"Mixed {span_start}text{span_end}".format(
                        span_start=HTML("<span>"),
                        span_end=HTML("</span>"),
                    )}
                """),
404
            'rule': Rules.python_requires_html_or_text
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        },
        {
            'expression':
                textwrap.dedent("""
                    ${Text("Mixed {span_start}text{span_end}").format(
                        span_start=HTML("<span>"),
                        span_end=HTML("</span>"),
                    )}
                """),
            'rule': None
        },
        {
            'expression':
                textwrap.dedent("""
                    ${"Mixed {span_start}{text}{span_end}".format(
                        span_start=HTML("<span>"),
                        text=Text("This should still break."),
                        span_end=HTML("</span>"),
                    )}
                """),
425
            'rule': Rules.python_requires_html_or_text
426 427 428 429 430 431 432 433 434
        },
        {
            'expression':
                textwrap.dedent("""
                    ${Text("Mixed {link_start}text{link_end}".format(
                        link_start=HTML("<a href='{}'>").format(url),
                        link_end=HTML("</a>"),
                    ))}
                """),
435
            'rule': [Rules.python_close_before_format, Rules.python_requires_html_or_text]
436 437 438 439 440 441 442 443 444
        },
        {
            'expression':
                textwrap.dedent("""
                    ${Text("Mixed {link_start}text{link_end}").format(
                        link_start=HTML("<a href='{}'>".format(url)),
                        link_end=HTML("</a>"),
                    )}
                """),
Robert Raposa committed
445
            'rule': Rules.python_close_before_format
446 447
        },
        {
448 449 450 451 452 453 454
            'expression':
                textwrap.dedent("""
                    ${"Mixed {span_start}text{span_end}".format(
                        span_start="<span>",
                        span_end="</span>",
                    )}
                """),
455
            'rule': [Rules.python_wrap_html, Rules.python_wrap_html]
456 457
        },
        {
Robert Raposa committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
            'expression':
                textwrap.dedent("""
                    ${Text(_("String with multiple lines "
                        "{link_start}unenroll{link_end} "
                        "and final line")).format(
                            link_start=HTML(
                                '<a id="link__over_multiple_lines" '
                                'data-course-id="{course_id}" '
                                'href="#test-modal">'
                            ).format(
                                course_id=course_overview.id
                            ),
                            link_end=HTML('</a>'),
                    )}
                """),
            'rule': None
        },
        {
476
            'expression': "${'<span></span>'}",
Robert Raposa committed
477
            'rule': Rules.python_wrap_html
478 479
        },
        {
Robert Raposa committed
480
            'expression': "${'Embedded HTML <strong></strong>'}",
Robert Raposa committed
481
            'rule': Rules.python_wrap_html
Robert Raposa committed
482 483
        },
        {
484
            'expression': "${ HTML('<span></span>') }",
485 486 487
            'rule': None
        },
        {
Robert Raposa committed
488 489 490 491
            'expression': "${HTML(render_entry(map['entries'], child))}",
            'rule': None
        },
        {
492 493 494 495 496 497
            'expression': "${ '<span></span>' + 'some other text' }",
            'rule': [Rules.python_concat_html, Rules.python_wrap_html]
        },
        {
            'expression': "${ HTML('<span>missing closing parentheses.</span>' }",
            'rule': Rules.python_parse_error
498
        },
499 500 501 502 503 504 505 506
        {
            'expression': "${'Rock &amp; Roll'}",
            'rule': Rules.mako_html_entities
        },
        {
            'expression': "${'Rock &#38; Roll'}",
            'rule': Rules.mako_html_entities
        },
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    )
    def test_check_mako_with_text_and_html(self, data):
        """
        Test _check_mako_file_is_safe tests for proper use of Text() and Html().
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            {expression}
        """.format(expression=data['expression']))

        linter._check_mako_file_is_safe(mako_template, results)

Robert Raposa committed
522
        self._validate_data_rules(data, results)
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    def test_check_mako_entity_with_no_default(self):
        """
        Test _check_mako_file_is_safe does not fail on entities when
        safe-by-default is not set.
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = "${'Rock &#38; Roll'}"

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
        self.assertEqual(results.violations[0].rule, Rules.mako_missing_default)

539 540 541 542 543 544 545 546 547 548 549 550
    def test_check_mako_expression_default_disabled(self):
        """
        Test _check_mako_file_is_safe with disable pragma for safe-by-default
        works to designate that this is not a Mako file
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            # This is anything but a Mako file.

            # pragma can appear anywhere in file
551
            # xss-lint: disable=mako-missing-default
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
        self.assertTrue(results.violations[0].is_disabled)

    def test_check_mako_expression_disabled(self):
        """
        Test _check_mako_file_is_safe with disable pragma results in no
        violation
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
569
            ## xss-lint: disable=mako-unwanted-html-filter
570 571 572 573 574 575 576 577 578 579 580
            ${x | h}
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
        self.assertTrue(results.violations[0].is_disabled)

    @data(
        {'template': '{% extends "wiki/base.html" %}'},
        {'template': '{{ message }}'},
581
        {'template': '{# comment #}'},
582 583 584 585 586 587 588 589 590 591 592 593 594
    )
    def test_check_mako_on_django_template(self, data):
        """
        Test _check_mako_file_is_safe with disable pragma results in no
        violation
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        linter._check_mako_file_is_safe(data['template'], results)

        self.assertEqual(len(results.violations), 0)

Robert Raposa committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    def test_check_mako_expressions_in_html_without_default(self):
        """
        Test _check_mako_file_is_safe in html context without the page level
        default h filter suppresses expression level violation
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            ${x | h}
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
        self.assertEqual(results.violations[0].rule, Rules.mako_missing_default)

612 613 614 615 616 617
    @data(
        {'expression': '${x}', 'rule': Rules.mako_invalid_js_filter},
        {'expression': '${{unbalanced}', 'rule': Rules.mako_unparseable_expression},
        {'expression': '${x | n}', 'rule': Rules.mako_invalid_js_filter},
        {'expression': '${x | h}', 'rule': Rules.mako_invalid_js_filter},
        {'expression': '${x | n, dump_js_escaped_json}', 'rule': None},
Robert Raposa committed
618
        {'expression': '${x | n, decode.utf8}', 'rule': None},
619 620
    )
    def test_check_mako_expressions_in_javascript(self, data):
Robert Raposa committed
621 622 623 624 625 626 627 628 629
        """
        Test _check_mako_file_is_safe in JavaScript script context provides
        appropriate violations
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
630
            ## switch to JavaScript context
Robert Raposa committed
631
            <script>
632
                {expression}
Robert Raposa committed
633
            </script>
634 635
            ## switch back to HTML context
            ${{x}}
636
        """.format(expression=data['expression']))
Robert Raposa committed
637 638 639

        linter._check_mako_file_is_safe(mako_template, results)

Robert Raposa committed
640
        self._validate_data_rules(data, results)
Robert Raposa committed
641

642 643
    @data(
        {'expression': '${x}', 'rule': Rules.mako_invalid_js_filter},
Robert Raposa committed
644
        {'expression': '"${x | n, js_escaped_string}"', 'rule': None},
645
    )
646
    def test_check_mako_expressions_in_require_module(self, data):
Robert Raposa committed
647 648 649 650 651 652 653 654 655
        """
        Test _check_mako_file_is_safe in JavaScript require context provides
        appropriate violations
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
656
            ## switch to JavaScript context (after next line)
657 658
            <%static:require_module module_name="${{x}}" class_name="TestFactory">
                {expression}
Robert Raposa committed
659
            </%static:require_module>
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
            ## switch back to HTML context
            ${{x}}
        """.format(expression=data['expression']))

        linter._check_mako_file_is_safe(mako_template, results)

        self._validate_data_rules(data, results)

    @data(
        {'expression': '${x}', 'rule': Rules.mako_invalid_js_filter},
        {'expression': '"${x | n, js_escaped_string}"', 'rule': None},
    )
    def test_check_mako_expressions_in_require_js(self, data):
        """
        Test _check_mako_file_is_safe in JavaScript require js context provides
        appropriate violations
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            # switch to JavaScript context
            <%block name="requirejs">
                {expression}
            </%block>
            ## switch back to HTML context
            ${{x}}
688
        """.format(expression=data['expression']))
Robert Raposa committed
689 690 691

        linter._check_mako_file_is_safe(mako_template, results)

Robert Raposa committed
692
        self._validate_data_rules(data, results)
Robert Raposa committed
693 694

    @data(
695 696 697 698 699 700 701 702
        {'media_type': 'text/javascript', 'rule': None},
        {'media_type': 'text/ecmascript', 'rule': None},
        {'media_type': 'application/ecmascript', 'rule': None},
        {'media_type': 'application/javascript', 'rule': None},
        {'media_type': 'text/x-mathjax-config', 'rule': None},
        {'media_type': 'json/xblock-args', 'rule': None},
        {'media_type': 'text/template', 'rule': Rules.mako_invalid_html_filter},
        {'media_type': 'unknown/type', 'rule': Rules.mako_unknown_context},
Robert Raposa committed
703 704 705 706 707 708 709 710 711 712
    )
    def test_check_mako_expressions_in_script_type(self, data):
        """
        Test _check_mako_file_is_safe in script tag with different media types
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
713
            # switch to JavaScript context
Robert Raposa committed
714 715 716
            <script type="{}">
                ${{x | n, dump_js_escaped_json}}
            </script>
717 718
            ## switch back to HTML context
            ${{x}}
Robert Raposa committed
719 720 721 722
        """).format(data['media_type'])

        linter._check_mako_file_is_safe(mako_template, results)

723
        self._validate_data_rules(data, results)
Robert Raposa committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

    def test_check_mako_expressions_in_mixed_contexts(self):
        """
        Test _check_mako_file_is_safe in mixed contexts provides
        appropriate violations
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            ${x | h}
            <script type="text/javascript">
                ${x | h}
            </script>
            ${x | h}
            <%static:require_module module_name="${x}" class_name="TestFactory">
                ${x | h}
            </%static:require_module>
            ${x | h}
744 745 746 747
            <%static:studiofrontend page="${x}" lang="en">
                ${x | h}
            </%static:studiofrontend>
            ${x | h}
Robert Raposa committed
748 749 750 751
        """)

        linter._check_mako_file_is_safe(mako_template, results)

752
        self.assertEqual(len(results.violations), 7)
Robert Raposa committed
753 754 755 756 757
        self.assertEqual(results.violations[0].rule, Rules.mako_unwanted_html_filter)
        self.assertEqual(results.violations[1].rule, Rules.mako_invalid_js_filter)
        self.assertEqual(results.violations[2].rule, Rules.mako_unwanted_html_filter)
        self.assertEqual(results.violations[3].rule, Rules.mako_invalid_js_filter)
        self.assertEqual(results.violations[4].rule, Rules.mako_unwanted_html_filter)
758 759
        self.assertEqual(results.violations[5].rule, Rules.mako_invalid_js_filter)
        self.assertEqual(results.violations[6].rule, Rules.mako_unwanted_html_filter)
Robert Raposa committed
760

Robert Raposa committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    def test_check_mako_expressions_javascript_strings(self):
        """
        Test _check_mako_file_is_safe javascript string specific rules.
        - mako_js_missing_quotes
        - mako_js_html_string
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            <script type="text/javascript">
                var valid1 = '${x | n, js_escaped_string} ${y | n, js_escaped_string}'
                var valid2 = '${x | n, js_escaped_string} ${y | n, js_escaped_string}'
                var valid3 = 'string' + ' ${x | n, js_escaped_string} '
                var valid4 = "${Text(_('Some mixed text{begin_span}with html{end_span}')).format(
                    begin_span=HTML('<span>'),
                    end_span=HTML('</span>'),
                ) | n, js_escaped_string}"
                var valid5 = " " + "${Text(_('Please {link_start}send us e-mail{link_end}.')).format(
                    link_start=HTML('<a href="#" id="feedback_email">'),
                    link_end=HTML('</a>'),
                ) | n, js_escaped_string}";
                var invalid1 = ${x | n, js_escaped_string};
                var invalid2 = '<strong>${x | n, js_escaped_string}</strong>'
                var invalid3 = '<strong>${x | n, dump_js_escaped_json}</strong>'
            </script>
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 3)
        self.assertEqual(results.violations[0].rule, Rules.mako_js_missing_quotes)
        self.assertEqual(results.violations[1].rule, Rules.mako_js_html_string)
        self.assertEqual(results.violations[2].rule, Rules.mako_js_html_string)

    def test_check_javascript_in_mako_javascript_context(self):
        """
        Test _check_mako_file_is_safe with JavaScript error in JavaScript
        context.
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

        mako_template = textwrap.dedent("""
            <%page expression_filter="h"/>
            <script type="text/javascript">
                var message = '<p>' + msg + '</p>';
            </script>
        """)

        linter._check_mako_file_is_safe(mako_template, results)

        self.assertEqual(len(results.violations), 1)
        self.assertEqual(results.violations[0].rule, Rules.javascript_concat_html)
        self.assertEqual(results.violations[0].start_line, 4)

818 819 820 821 822 823 824 825 826 827 828 829 830 831
    @data(
        {'template': "\n${x | n}", 'parseable': True},
        {
            'template': textwrap.dedent(
                """
                    <div>${(
                        'tabbed-multi-line-expression'
                    ) | n}</div>
                """),
            'parseable': True
        },
        {'template': "${{unparseable}", 'parseable': False},
    )
    def test_expression_detailed_results(self, data):
Robert Raposa committed
832 833 834 835 836 837 838
        """
        Test _check_mako_file_is_safe provides detailed results, including line
        numbers, columns, and line
        """
        linter = MakoTemplateLinter()
        results = FileResults('')

839
        linter._check_mako_file_is_safe(data['template'], results)
Robert Raposa committed
840

841
        self.assertEqual(len(results.violations), 2)
Robert Raposa committed
842 843
        self.assertEqual(results.violations[0].rule, Rules.mako_missing_default)

844 845 846 847 848 849
        violation = results.violations[1]
        lines = list(data['template'].splitlines())
        self.assertTrue("${" in lines[violation.start_line - 1])
        self.assertTrue(lines[violation.start_line - 1].startswith("${", violation.start_column - 1))
        if data['parseable']:
            self.assertTrue("}" in lines[violation.end_line - 1])
850
            self.assertTrue(lines[violation.end_line - 1].startswith("}", violation.end_column - len("}") - 1))
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
        else:
            self.assertEqual(violation.start_line, violation.end_line)
            self.assertEqual(violation.end_column, "?")
        self.assertEqual(len(violation.lines), violation.end_line - violation.start_line + 1)
        for line_index in range(0, len(violation.lines)):
            self.assertEqual(violation.lines[line_index], lines[line_index + violation.start_line - 1])

    @data(
        {'template': "${x}"},
        {'template': "\n ${x}"},
        {'template': "${x} "},
        {'template': "${{test-balanced-delims}} "},
        {'template': "${'{unbalanced in string'}"},
        {'template': "${'unbalanced in string}'}"},
        {'template': "${(\n    'tabbed-multi-line-expression'\n  )}"},
    )
    def test_find_mako_expressions(self, data):
        """
        Test _find_mako_expressions for parseable expressions
Robert Raposa committed
870 871 872
        """
        linter = MakoTemplateLinter()

873
        expressions = linter._find_mako_expressions(data['template'])
Robert Raposa committed
874

875
        self.assertEqual(len(expressions), 1)
Robert Raposa committed
876 877
        start_index = expressions[0].start_index
        end_index = expressions[0].end_index
878
        self.assertEqual(data['template'][start_index:end_index], data['template'].strip())
Robert Raposa committed
879
        self.assertEqual(expressions[0].expression, data['template'].strip())
Robert Raposa committed
880

881 882 883 884
    @data(
        {'template': " ${{unparseable} ${}", 'start_index': 1},
        {'template': " ${'unparseable} ${}", 'start_index': 1},
    )
885
    def test_find_unparseable_mako_expressions(self, data):
886 887 888 889
        """
        Test _find_mako_expressions for unparseable expressions
        """
        linter = MakoTemplateLinter()
Robert Raposa committed
890

891 892
        expressions = linter._find_mako_expressions(data['template'])
        self.assertTrue(2 <= len(expressions))
Robert Raposa committed
893 894
        self.assertEqual(expressions[0].start_index, data['start_index'])
        self.assertIsNone(expressions[0].expression)
Robert Raposa committed
895

896 897 898 899 900 901
    @data(
        {
            'template': '${""}',
            'result': {'start_index': 2, 'end_index': 4, 'quote_length': 1}
        },
        {
902 903 904 905
            'template': "${''}",
            'result': {'start_index': 2, 'end_index': 4, 'quote_length': 1}
        },
        {
906 907 908 909 910 911 912 913 914 915 916
            'template': "${'Hello'}",
            'result': {'start_index': 2, 'end_index': 9, 'quote_length': 1}
        },
        {
            'template': '${""" triple """}',
            'result': {'start_index': 2, 'end_index': 16, 'quote_length': 3}
        },
        {
            'template': r""" ${" \" \\"} """,
            'result': {'start_index': 3, 'end_index': 11, 'quote_length': 1}
        },
Robert Raposa committed
917 918 919 920
        {
            'template': "${'broken string}",
            'result': {'start_index': 2, 'end_index': None, 'quote_length': None}
        },
921 922 923 924 925 926 927
    )
    def test_parse_string(self, data):
        """
        Test _parse_string helper
        """
        linter = MakoTemplateLinter()

928 929 930 931 932 933 934 935
        parse_string = ParseString(data['template'], data['result']['start_index'], len(data['template']))
        string_dict = {
            'start_index': parse_string.start_index,
            'end_index': parse_string.end_index,
            'quote_length': parse_string.quote_length,
        }

        self.assertDictEqual(string_dict, data['result'])
Robert Raposa committed
936 937 938 939 940
        if parse_string.end_index is not None:
            self.assertEqual(data['template'][parse_string.start_index:parse_string.end_index], parse_string.string)
            start_inner_index = parse_string.start_index + parse_string.quote_length
            end_inner_index = parse_string.end_index - parse_string.quote_length
            self.assertEqual(data['template'][start_inner_index:end_inner_index], parse_string.string_inner)
941

942 943

@ddt
944
class TestUnderscoreTemplateLinter(TestLinter):
945 946 947 948 949 950
    """
    Test UnderscoreTemplateLinter
    """

    def test_check_underscore_file_is_safe(self):
        """
951
        Test check_underscore_file_is_safe with safe template
952 953 954 955 956 957 958 959 960 961 962 963
        """
        linter = UnderscoreTemplateLinter()
        results = FileResults('')

        template = textwrap.dedent("""
            <%- gettext('Single Line') %>

            <%-
                gettext('Multiple Lines')
            %>
        """)

964
        linter.check_underscore_file_is_safe(template, results)
965 966 967 968 969

        self.assertEqual(len(results.violations), 0)

    def test_check_underscore_file_is_not_safe(self):
        """
970
        Test check_underscore_file_is_safe with unsafe template
971 972 973 974 975 976 977 978 979 980 981 982
        """
        linter = UnderscoreTemplateLinter()
        results = FileResults('')

        template = textwrap.dedent("""
            <%= gettext('Single Line') %>

            <%=
                gettext('Multiple Lines')
            %>
        """)

983
        linter.check_underscore_file_is_safe(template, results)
984 985 986 987 988 989 990 991

        self.assertEqual(len(results.violations), 2)
        self.assertEqual(results.violations[0].rule, Rules.underscore_not_escaped)
        self.assertEqual(results.violations[1].rule, Rules.underscore_not_escaped)

    @data(
        {
            'template':
992
                '<% // xss-lint:   disable=underscore-not-escaped   %>\n'
993 994 995 996 997
                '<%= message %>',
            'is_disabled': [True],
        },
        {
            'template':
998
                '<% // xss-lint: disable=another-rule,underscore-not-escaped %>\n'
999 1000 1001 1002 1003
                '<%= message %>',
            'is_disabled': [True],
        },
        {
            'template':
1004
                '<% // xss-lint: disable=another-rule %>\n'
1005 1006 1007 1008 1009
                '<%= message %>',
            'is_disabled': [False],
        },
        {
            'template':
1010
                '<% // xss-lint: disable=underscore-not-escaped %>\n'
1011 1012 1013 1014 1015 1016 1017 1018 1019
                '<%= message %>\n'
                '<%= message %>',
            'is_disabled': [True, False],
        },
        {
            'template':
                '// This test does not use proper Underscore.js Template syntax\n'
                '// But, it is just testing that a maximum of 5 non-whitespace\n'
                '// are used to designate start of line for disabling the next line.\n'
1020
                ' 1 2 3 4 5 xss-lint: disable=underscore-not-escaped %>\n'
1021
                '<%= message %>\n'
1022
                ' 1 2 3 4 5 6 xss-lint: disable=underscore-not-escaped %>\n'
1023 1024 1025 1026 1027
                '<%= message %>',
            'is_disabled': [True, False],
        },
        {
            'template':
1028
                '<%= message %><% // xss-lint: disable=underscore-not-escaped %>\n'
1029 1030 1031 1032 1033 1034
                '<%= message %>',
            'is_disabled': [True, False],
        },
        {
            'template':
                '<%= message %>\n'
1035
                '<% // xss-lint: disable=underscore-not-escaped %>',
1036 1037 1038 1039 1040
            'is_disabled': [False],
        },
    )
    def test_check_underscore_file_disable_rule(self, data):
        """
1041
        Test check_underscore_file_is_safe with various disabled pragmas
1042 1043 1044 1045
        """
        linter = UnderscoreTemplateLinter()
        results = FileResults('')

1046
        linter.check_underscore_file_is_safe(data['template'], results)
1047 1048 1049 1050 1051 1052 1053 1054

        violation_count = len(data['is_disabled'])
        self.assertEqual(len(results.violations), violation_count)
        for index in range(0, violation_count - 1):
            self.assertEqual(results.violations[index].is_disabled, data['is_disabled'][index])

    def test_check_underscore_file_disables_one_violation(self):
        """
1055
        Test check_underscore_file_is_safe with disabled before a line only
1056 1057 1058 1059 1060 1061
        disables for the violation following
        """
        linter = UnderscoreTemplateLinter()
        results = FileResults('')

        template = textwrap.dedent("""
1062
            <% // xss-lint: disable=underscore-not-escaped %>
1063 1064 1065 1066
            <%= message %>
            <%= message %>
        """)

1067
        linter.check_underscore_file_is_safe(template, results)
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

        self.assertEqual(len(results.violations), 2)
        self.assertEqual(results.violations[0].is_disabled, True)
        self.assertEqual(results.violations[1].is_disabled, False)

    @data(
        {'template': '<%= HtmlUtils.ensureHtml(message) %>'},
        {'template': '<%= _.escape(message) %>'},
    )
    def test_check_underscore_no_escape_allowed(self, data):
        """
1079
        Test check_underscore_file_is_safe with expressions that are allowed
1080 1081 1082 1083 1084
        without escaping because the internal calls properly escape.
        """
        linter = UnderscoreTemplateLinter()
        results = FileResults('')

1085
        linter.check_underscore_file_is_safe(data['template'], results)
1086 1087

        self.assertEqual(len(results.violations), 0)
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097


@ddt
class TestJavaScriptLinter(TestLinter):
    """
    Test JavaScriptLinter
    """
    @data(
        {'template': 'var m = "Plain text " + message + "plain text"', 'rule': None},
        {'template': 'var m = "檌檒濦 " + message + "plain text"', 'rule': None},
1098 1099 1100 1101 1102 1103
        {
            'template':
                ("""$email_header.append($('<input>', type: "button", name: "copy-email-body-text","""
                 """ value: gettext("Copy Email To Editor"), id: 'copy_email_' + email_id))"""),
            'rule': None
        },
1104
        {'template': 'var m = "<p>" + message + "</p>"', 'rule': Rules.javascript_concat_html},
1105 1106 1107 1108
        {
            'template': r'var m = "<p>\"escaped quote\"" + message + "\"escaped quote\"</p>"',
            'rule': Rules.javascript_concat_html
        },
Robert Raposa committed
1109
        {'template': '  // var m = "<p>" + commentedOutMessage + "</p>"', 'rule': None},
1110
        {'template': 'var m = " <p> " + message + " </p> "', 'rule': Rules.javascript_concat_html},
Robert Raposa committed
1111
        {'template': 'var m = " <p> " + message + " broken string', 'rule': Rules.javascript_concat_html},
1112 1113 1114
    )
    def test_concat_with_html(self, data):
        """
Robert Raposa committed
1115
        Test check_javascript_file_is_safe with concatenating strings and HTML
1116 1117 1118 1119
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1120
        linter.check_javascript_file_is_safe(data['template'], results)
Robert Raposa committed
1121
        self._validate_data_rules(data, results)
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

    @data(
        {'template': 'test.append( test.render().el )', 'rule': None},
        {'template': 'test.append(test.render().el)', 'rule': None},
        {'template': 'test.append(test.render().$el)', 'rule': None},
        {'template': 'test.append(testEl)', 'rule': None},
        {'template': 'test.append($test)', 'rule': None},
        # plain text is ok because any & will be escaped, and it stops false
        # negatives on some other objects with an append() method
        {'template': 'test.append("plain text")', 'rule': None},
        {'template': 'test.append("<div/>")', 'rule': Rules.javascript_jquery_append},
        {'template': 'graph.svg.append("g")', 'rule': None},
        {'template': 'test.append( $( "<div>" ) )', 'rule': None},
        {'template': 'test.append($("<div>"))', 'rule': None},
        {'template': 'test.append($("<div/>"))', 'rule': None},
        {'template': 'test.append(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'HtmlUtils.append($el, someHtml)', 'rule': None},
        {'template': 'test.append("fail on concat" + test.render().el)', 'rule': Rules.javascript_jquery_append},
        {'template': 'test.append("fail on concat" + testEl)', 'rule': Rules.javascript_jquery_append},
        {'template': 'test.append(message)', 'rule': Rules.javascript_jquery_append},
    )
    def test_jquery_append(self, data):
        """
Robert Raposa committed
1145
        Test check_javascript_file_is_safe with JQuery append()
1146 1147 1148 1149
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1150
        linter.check_javascript_file_is_safe(data['template'], results)
1151

Robert Raposa committed
1152
        self._validate_data_rules(data, results)
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

    @data(
        {'template': 'test.prepend( test.render().el )', 'rule': None},
        {'template': 'test.prepend(test.render().el)', 'rule': None},
        {'template': 'test.prepend(test.render().$el)', 'rule': None},
        {'template': 'test.prepend(testEl)', 'rule': None},
        {'template': 'test.prepend($test)', 'rule': None},
        {'template': 'test.prepend("text")', 'rule': None},
        {'template': 'test.prepend( $( "<div>" ) )', 'rule': None},
        {'template': 'test.prepend($("<div>"))', 'rule': None},
        {'template': 'test.prepend($("<div/>"))', 'rule': None},
        {'template': 'test.prepend(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'HtmlUtils.prepend($el, someHtml)', 'rule': None},
Robert Raposa committed
1166
        {'template': 'test.prepend("broken string)', 'rule': Rules.javascript_jquery_prepend},
1167 1168 1169 1170 1171 1172
        {'template': 'test.prepend("fail on concat" + test.render().el)', 'rule': Rules.javascript_jquery_prepend},
        {'template': 'test.prepend("fail on concat" + testEl)', 'rule': Rules.javascript_jquery_prepend},
        {'template': 'test.prepend(message)', 'rule': Rules.javascript_jquery_prepend},
    )
    def test_jquery_prepend(self, data):
        """
Robert Raposa committed
1173
        Test check_javascript_file_is_safe with JQuery prepend()
1174 1175 1176 1177
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1178
        linter.check_javascript_file_is_safe(data['template'], results)
1179

Robert Raposa committed
1180
        self._validate_data_rules(data, results)
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

    @data(
        {'template': 'test.unwrap(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.wrap(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.wrapAll(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.wrapInner(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.after(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.before(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.replaceAll(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.replaceWith(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'test.replaceWith(edx.HtmlUtils.HTML(htmlString).toString())', 'rule': None},
        {'template': 'test.unwrap(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.wrap(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.wrapAll(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.wrapInner(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.after(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.before(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.replaceAll(anything)', 'rule': Rules.javascript_jquery_insertion},
        {'template': 'test.replaceWith(anything)', 'rule': Rules.javascript_jquery_insertion},
    )
    def test_jquery_insertion(self, data):
        """
Robert Raposa committed
1203
        Test check_javascript_file_is_safe with JQuery insertion functions
1204 1205 1206 1207 1208 1209
        other than append(), prepend() and html() that take content as an
        argument (e.g. before(), after()).
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1210
        linter.check_javascript_file_is_safe(data['template'], results)
1211

Robert Raposa committed
1212
        self._validate_data_rules(data, results)
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

    @data(
        {'template': '  element.parentNode.appendTo(target);', 'rule': None},
        {'template': '  test.render().el.appendTo(target);', 'rule': None},
        {'template': '  test.render().$el.appendTo(target);', 'rule': None},
        {'template': '  test.$element.appendTo(target);', 'rule': None},
        {'template': '  test.testEl.appendTo(target);', 'rule': None},
        {'template': '$element.appendTo(target);', 'rule': None},
        {'template': 'el.appendTo(target);', 'rule': None},
        {'template': 'testEl.appendTo(target);', 'rule': None},
        {'template': 'testEl.prependTo(target);', 'rule': None},
        {'template': 'testEl.insertAfter(target);', 'rule': None},
        {'template': 'testEl.insertBefore(target);', 'rule': None},
        {'template': 'anycall().appendTo(target)', 'rule': Rules.javascript_jquery_insert_into_target},
        {'template': 'anything.appendTo(target)', 'rule': Rules.javascript_jquery_insert_into_target},
        {'template': 'anything.prependTo(target)', 'rule': Rules.javascript_jquery_insert_into_target},
        {'template': 'anything.insertAfter(target)', 'rule': Rules.javascript_jquery_insert_into_target},
        {'template': 'anything.insertBefore(target)', 'rule': Rules.javascript_jquery_insert_into_target},
    )
    def test_jquery_insert_to_target(self, data):
        """
Robert Raposa committed
1234
        Test check_javascript_file_is_safe with JQuery insert to target
1235 1236 1237 1238 1239 1240
        functions that take a target as an argument, like appendTo() and
        prependTo().
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1241
        linter.check_javascript_file_is_safe(data['template'], results)
1242

Robert Raposa committed
1243
        self._validate_data_rules(data, results)
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

    @data(
        {'template': 'test.html()', 'rule': None},
        {'template': 'test.html( )', 'rule': None},
        {'template': "test.html( '' )", 'rule': None},
        {'template': "test.html('')", 'rule': None},
        {'template': 'test.html("")', 'rule': None},
        {'template': 'test.html(HtmlUtils.ensureHtml(htmlSnippet).toString())', 'rule': None},
        {'template': 'HtmlUtils.setHtml($el, someHtml)', 'rule': None},
        {'template': 'test.html("any string")', 'rule': Rules.javascript_jquery_html},
Robert Raposa committed
1254
        {'template': 'test.html("broken string)', 'rule': Rules.javascript_jquery_html},
1255 1256 1257 1258 1259
        {'template': 'test.html("檌檒濦")', 'rule': Rules.javascript_jquery_html},
        {'template': 'test.html(anything)', 'rule': Rules.javascript_jquery_html},
    )
    def test_jquery_html(self, data):
        """
Robert Raposa committed
1260
        Test check_javascript_file_is_safe with JQuery html()
1261 1262 1263 1264
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1265
        linter.check_javascript_file_is_safe(data['template'], results)
Robert Raposa committed
1266
        self._validate_data_rules(data, results)
1267 1268 1269 1270 1271 1272 1273 1274

    @data(
        {'template': 'StringUtils.interpolate()', 'rule': None},
        {'template': 'HtmlUtils.interpolateHtml()', 'rule': None},
        {'template': 'interpolate(anything)', 'rule': Rules.javascript_interpolate},
    )
    def test_javascript_interpolate(self, data):
        """
Robert Raposa committed
1275
        Test check_javascript_file_is_safe with interpolate()
1276 1277 1278 1279
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1280
        linter.check_javascript_file_is_safe(data['template'], results)
1281

Robert Raposa committed
1282
        self._validate_data_rules(data, results)
1283 1284

    @data(
Robert Raposa committed
1285 1286
        {'template': '_.escape(message)', 'rule': None},
        {'template': 'anything.escape(message)', 'rule': Rules.javascript_escape},
1287 1288 1289
    )
    def test_javascript_interpolate(self, data):
        """
Robert Raposa committed
1290
        Test check_javascript_file_is_safe with interpolate()
1291 1292 1293 1294
        """
        linter = JavaScriptLinter()
        results = FileResults('')

Robert Raposa committed
1295
        linter.check_javascript_file_is_safe(data['template'], results)
1296

Robert Raposa committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        self._validate_data_rules(data, results)


@ddt
class TestPythonLinter(TestLinter):
    """
    Test PythonLinter
    """
    @data(
        {'template': 'm = "Plain text " + message + "plain text"', 'rule': None},
        {'template': 'm = "檌檒濦 " + message + "plain text"', 'rule': None},
        {'template': '  # m = "<p>" + commentedOutMessage + "</p>"', 'rule': None},
1309 1310 1311
        {'template': 'm = "<p>" + message + "</p>"', 'rule': [Rules.python_concat_html, Rules.python_concat_html]},
        {'template': 'm = " <p> " + message + " </p> "', 'rule': [Rules.python_concat_html, Rules.python_concat_html]},
        {'template': 'm = " <p> " + message + " broken string', 'rule': Rules.python_parse_error},
Robert Raposa committed
1312 1313 1314 1315 1316 1317 1318 1319 1320
    )
    def test_concat_with_html(self, data):
        """
        Test check_python_file_is_safe with concatenating strings and HTML
        """
        linter = PythonLinter()
        results = FileResults('')

        linter.check_python_file_is_safe(data['template'], results)
1321

Robert Raposa committed
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        self._validate_data_rules(data, results)

    def test_check_python_expression_display_name(self):
        """
        Test _check_python_file_is_safe with display_name_with_default_escaped
        fails.
        """
        linter = PythonLinter()
        results = FileResults('')

        python_file = textwrap.dedent("""
            context = {
                'display_name': self.display_name_with_default_escaped,
            }
        """)

        linter.check_python_file_is_safe(python_file, results)

        self.assertEqual(len(results.violations), 1)
        self.assertEqual(results.violations[0].rule, Rules.python_deprecated_display_name)

    def test_check_custom_escaping(self):
        """
        Test _check_python_file_is_safe fails when custom escapins is used.
        """
        linter = PythonLinter()
        results = FileResults('')

        python_file = textwrap.dedent("""
            msg = mmlans.replace('<', '&lt;')
        """)

        linter.check_python_file_is_safe(python_file, results)

        self.assertEqual(len(results.violations), 1)
        self.assertEqual(results.violations[0].rule, Rules.python_custom_escape)

    @data(
        {
            'python':
                textwrap.dedent("""
1363
                    msg = Text("Mixed {span_start}text{span_end}").format(
Robert Raposa committed
1364 1365 1366 1367
                        span_start=HTML("<span>"),
                        span_end=HTML("</span>"),
                    )
                """),
1368
            'rule': None
Robert Raposa committed
1369 1370 1371 1372
        },
        {
            'python':
                textwrap.dedent("""
1373
                    msg = "Mixed {span_start}text{span_end}".format(
Robert Raposa committed
1374 1375 1376 1377
                        span_start=HTML("<span>"),
                        span_end=HTML("</span>"),
                    )
                """),
1378
            'rule': Rules.python_requires_html_or_text
Robert Raposa committed
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
        },
        {
            'python':
                textwrap.dedent("""
                    msg = "Mixed {span_start}{text}{span_end}".format(
                        span_start=HTML("<span>"),
                        text=Text("This should still break."),
                        span_end=HTML("</span>"),
                    )
                """),
            'rule': Rules.python_requires_html_or_text
        },
        {
            'python':
                textwrap.dedent("""
                    msg = Text("Mixed {link_start}text{link_end}".format(
                        link_start=HTML("<a href='{}'>").format(url),
                        link_end=HTML("</a>"),
                    ))
                """),
            'rule': [Rules.python_close_before_format, Rules.python_requires_html_or_text]
        },
        {
            'python':
                textwrap.dedent("""
                    msg = Text("Mixed {link_start}text{link_end}").format(
                        link_start=HTML("<a href='{}'>".format(url)),
                        link_end=HTML("</a>"),
                    )
                """),
            'rule': Rules.python_close_before_format
        },
        {
            'python':
                textwrap.dedent("""
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
                    msg = Text("Mixed {link_start}text{link_end}".format(
                        link_start=HTML("<a href='{}'>".format(HTML('<b>'))),
                        link_end=HTML("</a>"),
                    ))
                """),
            'rule':
                [
                    Rules.python_close_before_format,
                    Rules.python_requires_html_or_text,
                    Rules.python_close_before_format,
                    Rules.python_requires_html_or_text
                ]
        },
        {
            'python':
                textwrap.dedent("""
Robert Raposa committed
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
                    msg = "Mixed {span_start}text{span_end}".format(
                        span_start="<span>",
                        span_end="</span>",
                    )
                """),
            'rule': [Rules.python_wrap_html, Rules.python_wrap_html]
        },
        {
            'python':
                textwrap.dedent("""
                    msg = Text(_("String with multiple lines "
                        "{link_start}unenroll{link_end} "
                        "and final line")).format(
                            link_start=HTML(
                                '<a id="link__over_multiple_lines" '
                                'data-course-id="{course_id}" '
                                'href="#test-modal">'
                            ).format(
1448
                                # Line comment with ' to throw off parser
Robert Raposa committed
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
                                course_id=course_overview.id
                            ),
                            link_end=HTML('</a>'),
                    )
                """),
            'rule': None
        },
        {
            'python': "msg = '<span></span>'",
            'rule': None
        },
        {
            'python': "msg = HTML('<span></span>')",
            'rule': None
        },
        {
            'python': r"""msg = '<a href="{}"'.format(url)""",
1466
            'rule': Rules.python_wrap_html
Robert Raposa committed
1467 1468 1469
        },
        {
            'python': r"""msg = '{}</p>'.format(message)""",
1470 1471 1472 1473 1474
            'rule': Rules.python_wrap_html
        },
        {
            'python': r"""r'regex with {} and named group(?P<id>\d+)?$'.format(test)""",
            'rule': None
Robert Raposa committed
1475 1476 1477 1478 1479 1480
        },
        {
            'python': r"""msg = '<a href="%s"' % url""",
            'rule': Rules.python_interpolate_html
        },
        {
1481 1482 1483 1484 1485 1486 1487 1488 1489
            'python':
                textwrap.dedent("""
                    def __repr__(self):
                        # Assume repr implementations are safe, and not HTML
                        return '<CCXCon {}>'.format(self.title)
                """),
            'rule': None
        },
        {
Robert Raposa committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
            'python': r"""msg = '%s</p>' % message""",
            'rule': Rules.python_interpolate_html
        },
        {
            'python': "msg = HTML('<span></span>'",
            'rule': Rules.python_parse_error
        },
    )
    def test_check_python_with_text_and_html(self, data):
        """
        Test _check_python_file_is_safe tests for proper use of Text() and
        Html().

        """
        linter = PythonLinter()
        results = FileResults('')

        file_content = textwrap.dedent(data['python'])

        linter.check_python_file_is_safe(file_content, results)

        self._validate_data_rules(data, results)

    def test_check_python_with_text_and_html_mixed(self):
        """
        Test _check_python_file_is_safe tests for proper use of Text() and
        Html() for a Python file with a mix of rules.

        """
        linter = PythonLinter()
        results = FileResults('')

        file_content = textwrap.dedent("""
            msg1 = '<a href="{}"'.format(url)
1524
            msg2 = "Mixed {link_start}text{link_end}".format(
Robert Raposa committed
1525
                link_start=HTML("<a href='{}'>".format(url)),
1526
                link_end="</a>",
Robert Raposa committed
1527
            )
1528
            msg3 = '<a href="%s"' % url
Robert Raposa committed
1529 1530 1531 1532
        """)

        linter.check_python_file_is_safe(file_content, results)

1533 1534 1535 1536 1537 1538
        results.violations.sort(key=lambda violation: violation.sort_key())

        self.assertEqual(len(results.violations), 5)
        self.assertEqual(results.violations[0].rule, Rules.python_wrap_html)
        self.assertEqual(results.violations[1].rule, Rules.python_requires_html_or_text)
        self.assertEqual(results.violations[2].rule, Rules.python_close_before_format)
Robert Raposa committed
1539
        self.assertEqual(results.violations[3].rule, Rules.python_wrap_html)
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
        self.assertEqual(results.violations[4].rule, Rules.python_interpolate_html)

    @data(
        {
            'python':
                """
                    response_str = textwrap.dedent('''
                        <div>
                            <h3 class="result">{response}</h3>
                        </div>
                    ''').format(response=response_text)
                """,
            'rule': Rules.python_wrap_html,
            'start_line': 2,
        },
        {
            'python':
                """
                def function(self):
                    '''
                    Function comment.
                    '''
                    response_str = textwrap.dedent('''
                        <div>
                            <h3 class="result">{response}</h3>
                        </div>
                    ''').format(response=response_text)
                """,
            'rule': Rules.python_wrap_html,
            'start_line': 6,
        },
        {
            'python':
                """
                def function(self):
                    '''
                    Function comment.
                    '''
                    response_str = '''<h3 class="result">{response}</h3>'''.format(response=response_text)
                """,
            'rule': Rules.python_wrap_html,
            'start_line': 6,
        },
        {
            'python':
                """
                def function(self):
                    '''
                    Function comment.
                    '''
                    response_str = textwrap.dedent('''
                        <div>
                            \"\"\" Do we care about a nested triple quote? \"\"\"
                            <h3 class="result">{response}</h3>
                        </div>
                    ''').format(response=response_text)
                """,
            'rule': Rules.python_wrap_html,
            'start_line': 6,
        },
    )
    def test_check_python_with_triple_quotes(self, data):
        """
        Test _check_python_file_is_safe with triple quotes.

        """
        linter = PythonLinter()
        results = FileResults('')

        file_content = textwrap.dedent(data['python'])

        linter.check_python_file_is_safe(file_content, results)

        self._validate_data_rules(data, results)
        self.assertEqual(results.violations[0].start_line, data['start_line'])