Skip to content

Commit 1ab2794

Browse files
committed
Security/Underscorejs: bug fix - don't error when variable is escaped
Prevent triggering a warning when the variable being printed is escaped using `_.escape()`. Includes unit tests. Fixes 345
1 parent d3ce1d0 commit 1ab2794

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

WordPressVIPMinimum/Sniffs/Security/UnderscorejsSniff.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ public function process_token( $stackPtr ) {
106106
$match_count = preg_match_all( self::UNESCAPED_INTERPOLATE_REGEX, $content, $matches );
107107
if ( $match_count > 0 ) {
108108
foreach ( $matches[0] as $match ) {
109+
if ( strpos( $match, '_.escape(' ) !== false ) {
110+
continue;
111+
}
112+
109113
// Underscore.js unescaped output.
110114
$message = 'Found Underscore.js unescaped output notation: "%s".';
111115
$data = [ $match ];

WordPressVIPMinimum/Tests/Security/UnderscorejsUnitTest.inc

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,36 @@ function test_interpolate_match_precision() {
7373
</script>
7474
<?php
7575
}
76+
77+
// Recognize escaping.
78+
function dont_trigger_when_escaped() {
79+
$script = <<<EOD
80+
var html = _.template('<li><%= _.escape(name) %></li>', { name: 'John Smith' }); // OK.
81+
82+
var html = _.template(
83+
"<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" + // OK.
84+
"as the \"<%= _.escape(o.text) %>\" and the same<br />" + // OK.
85+
"as the \"<%- o.text %>\"</pre>", // OK.
86+
{
87+
text: "<b>some text</b> and \n it's a line break"
88+
},
89+
{
90+
variable: "o"
91+
}
92+
);
93+
EOD;
94+
95+
echo $script;
96+
}
97+
98+
function display_foo {
99+
?>
100+
<script id="template" type="text/template">
101+
<li class="dashboard-post-item" dashboard-id="<%= _.escape( id ) %>"><!-- OK -->
102+
<div class="image-wrapper">
103+
<img src="<%= _.escape( image_url ) %>" class="dashboard-image"><!-- OK -->
104+
</div>
105+
</li>
106+
</script>
107+
<?php
108+
}

WordPressVIPMinimum/Tests/Security/UnderscorejsUnitTest.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,18 @@ var p = function(f, d) {
2424
}
2525

2626
y.interpolate.bezier = b; // OK.
27+
28+
// Recognize escaping.
29+
var html = _.template('<li><%= _.escape(name) %></li>', { name: 'John Smith' }); // OK.
30+
31+
var html = _.template(
32+
"<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" + // OK.
33+
"as the \"<%= _.escape(o.text) %>\" and the same<br />" + // OK.
34+
"as the \"<%- o.text %>\"</pre>", // OK.
35+
{
36+
text: "<b>some text</b> and \n it's a line break"
37+
},
38+
{
39+
variable: "o"
40+
}
41+
);

0 commit comments

Comments
 (0)