Skip to content

Commit de5398a

Browse files
authored
Core:Manipulation: Add basic TrustedHTML support
This ensures HTML wrapped in TrustedHTML can be used as an input to jQuery manipulation methods in a way that doesn't violate the `require-trusted-types-for` Content Security Policy directive. This commit builds on previous work needed for trusted types support, including gh-4642 and gh-4724. One restriction is that while any TrustedHTML wrapper should work as input for jQuery methods like `.html()` or `.append()`, for passing directly to the `jQuery` factory the string must start with `<` and end with `>`; no trailing or leading whitespaces are allowed. This is necessary as we cannot parse out a part of the input for further construction; that would violate the CSP rule - and that's what's done to HTML input not matching these constraints. No trusted types API is used explicitly in source; the majority of the work is ensuring we don't pass the input converted to string to APIs that would eventually assign it to `innerHTML`. This extra cautiousness is caused by the API being Blink-only, at least for now. The ban on passing strings to `innerHTML` means support tests relying on such assignments are impossible. We don't currently have such tests on the `main` branch but we used to have many of them in the 3.x & older lines. If there's a need to re-add such a test, we'll need an escape hatch to skip them for apps needing CSP-enforced TrustedHTML. See https://web.dev/trusted-types/ for more information about TrustedHTML. Fixes gh-4409 Closes gh-4927 Ref gh-4642 Ref gh-4724
1 parent 1019074 commit de5398a

12 files changed

+170
-46
lines changed

src/core.js

+1-15
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ import hasOwn from "./var/hasOwn.js";
1010
import fnToString from "./var/fnToString.js";
1111
import ObjectFunctionString from "./var/ObjectFunctionString.js";
1212
import support from "./var/support.js";
13-
import isWindow from "./var/isWindow.js";
13+
import isArrayLike from "./core/isArrayLike.js";
1414
import DOMEval from "./core/DOMEval.js";
15-
import toType from "./core/toType.js";
1615

1716
var version = "@VERSION",
1817

@@ -398,17 +397,4 @@ jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symb
398397
class2type[ "[object " + name + "]" ] = name.toLowerCase();
399398
} );
400399

401-
function isArrayLike( obj ) {
402-
403-
var length = !!obj && obj.length,
404-
type = toType( obj );
405-
406-
if ( typeof obj === "function" || isWindow( obj ) ) {
407-
return false;
408-
}
409-
410-
return type === "array" || length === 0 ||
411-
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
412-
}
413-
414400
export default jQuery;

src/core/init.js

+30-24
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import jQuery from "../core.js";
33
import document from "../var/document.js";
44
import rsingleTag from "./var/rsingleTag.js";
5+
import isObviousHtml from "./isObviousHtml.js";
56

67
import "../traversing/findFilter.js";
78

@@ -26,20 +27,41 @@ var rootjQuery,
2627
// so migrate can support jQuery.sub (gh-2101)
2728
root = root || rootjQuery;
2829

29-
// Handle HTML strings
30-
if ( typeof selector === "string" ) {
31-
if ( selector[ 0 ] === "<" &&
32-
selector[ selector.length - 1 ] === ">" &&
33-
selector.length >= 3 ) {
30+
// HANDLE: $(DOMElement)
31+
if ( selector.nodeType ) {
32+
this[ 0 ] = selector;
33+
this.length = 1;
34+
return this;
35+
36+
// HANDLE: $(function)
37+
// Shortcut for document ready
38+
} else if ( typeof selector === "function" ) {
39+
return root.ready !== undefined ?
40+
root.ready( selector ) :
41+
42+
// Execute immediately if ready is not present
43+
selector( jQuery );
44+
45+
} else {
3446

35-
// Assume that strings that start and end with <> are HTML and skip the regex check
47+
// Handle obvious HTML strings
48+
match = selector + "";
49+
if ( isObviousHtml( match ) ) {
50+
51+
// Assume that strings that start and end with <> are HTML and skip
52+
// the regex check. This also handles browser-supported HTML wrappers
53+
// like TrustedHTML.
3654
match = [ null, selector, null ];
3755

38-
} else {
56+
// Handle HTML strings or selectors
57+
} else if ( typeof selector === "string" ) {
3958
match = rquickExpr.exec( selector );
59+
} else {
60+
return jQuery.makeArray( selector, this );
4061
}
4162

4263
// Match html or make sure no context is specified for #id
64+
// Note: match[1] may be a string or a TrustedHTML wrapper
4365
if ( match && ( match[ 1 ] || !context ) ) {
4466

4567
// HANDLE: $(html) -> $(array)
@@ -84,7 +106,7 @@ var rootjQuery,
84106
return this;
85107
}
86108

87-
// HANDLE: $(expr, $(...))
109+
// HANDLE: $(expr) & $(expr, $(...))
88110
} else if ( !context || context.jquery ) {
89111
return ( context || root ).find( selector );
90112

@@ -93,24 +115,8 @@ var rootjQuery,
93115
} else {
94116
return this.constructor( context ).find( selector );
95117
}
96-
97-
// HANDLE: $(DOMElement)
98-
} else if ( selector.nodeType ) {
99-
this[ 0 ] = selector;
100-
this.length = 1;
101-
return this;
102-
103-
// HANDLE: $(function)
104-
// Shortcut for document ready
105-
} else if ( typeof selector === "function" ) {
106-
return root.ready !== undefined ?
107-
root.ready( selector ) :
108-
109-
// Execute immediately if ready is not present
110-
selector( jQuery );
111118
}
112119

113-
return jQuery.makeArray( selector, this );
114120
};
115121

116122
// Give the init function the jQuery prototype for later instantiation

src/core/isArrayLike.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import toType from "./toType.js";
2+
import isWindow from "../var/isWindow.js";
3+
4+
function isArrayLike( obj ) {
5+
6+
var length = !!obj && obj.length,
7+
type = toType( obj );
8+
9+
if ( typeof obj === "function" || isWindow( obj ) ) {
10+
return false;
11+
}
12+
13+
return type === "array" || length === 0 ||
14+
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
15+
}
16+
17+
export default isArrayLike;

src/core/isObviousHtml.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
function isObviousHtml( input ) {
2+
return input[ 0 ] === "<" &&
3+
input[ input.length - 1 ] === ">" &&
4+
input.length >= 3;
5+
}
6+
7+
export default isObviousHtml;

src/core/parseHTML.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import jQuery from "../core.js";
22
import document from "../var/document.js";
33
import rsingleTag from "./var/rsingleTag.js";
44
import buildFragment from "../manipulation/buildFragment.js";
5+
import isObviousHtml from "./isObviousHtml.js";
56

6-
// Argument "data" should be string of html
7+
// Argument "data" should be string of html or a TrustedHTML wrapper of obvious HTML
78
// context (optional): If specified, the fragment will be created in this context,
89
// defaults to document
910
// keepScripts (optional): If true, will include scripts passed in the html string
1011
jQuery.parseHTML = function( data, context, keepScripts ) {
11-
if ( typeof data !== "string" ) {
12+
if ( typeof data !== "string" && !isObviousHtml( data + "" ) ) {
1213
return [];
1314
}
1415
if ( typeof context === "boolean" ) {

src/manipulation/buildFragment.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import rscriptType from "./var/rscriptType.js";
77
import wrapMap from "./wrapMap.js";
88
import getAll from "./getAll.js";
99
import setGlobalEval from "./setGlobalEval.js";
10+
import isArrayLike from "../core/isArrayLike.js";
1011

1112
var rhtml = /<|&#?\w+;/;
1213

@@ -23,7 +24,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) {
2324
if ( elem || elem === 0 ) {
2425

2526
// Add nodes directly
26-
if ( toType( elem ) === "object" ) {
27+
if ( toType( elem ) === "object" && ( elem.nodeType || isArrayLike( elem ) ) ) {
2728
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
2829

2930
// Convert non-html into a text node

test/.eslintrc.json

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"require": false,
1515
"Promise": false,
1616
"Symbol": false,
17+
"trustedTypes": false,
1718
"QUnit": false,
1819
"ajaxTest": false,
1920
"testIframe": false,

test/data/csp.include.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<head>
44
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
55
<title>CSP Test Page</title>
6-
<script src="../jquery.js"></script>
6+
<script src="../../dist/jquery.min.js"></script>
77
<script src="iframeTest.js"></script>
88
<script src="support/csp.js"></script>
99
<script src="support/getComputedSupport.js"></script>

test/data/mock.php

+8-2
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ protected function testHTML( $req ) {
215215
}
216216

217217
protected function cspFrame( $req ) {
218-
header( "Content-Security-Policy: default-src 'self'; report-uri ./mock.php?action=cspLog" );
218+
header( "Content-Security-Policy: default-src 'self'; require-trusted-types-for 'script'; report-uri ./mock.php?action=cspLog" );
219219
header( 'Content-type: text/html' );
220220
echo file_get_contents( __DIR__ . '/csp.include.html' );
221221
}
@@ -228,7 +228,7 @@ protected function cspNonce( $req ) {
228228
}
229229

230230
protected function cspAjaxScript( $req ) {
231-
header( "Content-Security-Policy: script-src 'self'; report-uri /base/test/data/mock.php?action=cspLog" );
231+
header( "Content-Security-Policy: script-src 'self'; report-uri ./mock.php?action=cspLog" );
232232
header( 'Content-type: text/html' );
233233
echo file_get_contents( __DIR__ . '/csp-ajax-script.html' );
234234
}
@@ -241,6 +241,12 @@ protected function cspClean( $req ) {
241241
file_put_contents( $this->cspFile, '' );
242242
}
243243

244+
protected function trustedHtml( $req ) {
245+
header( "Content-Security-Policy: require-trusted-types-for 'script'; report-uri ./mock.php?action=cspLog" );
246+
header( 'Content-type: text/html' );
247+
echo file_get_contents( __DIR__ . '/trusted-html.html' );
248+
}
249+
244250
protected function errorWithScript( $req ) {
245251
header( 'HTTP/1.0 404 Not Found' );
246252
if ( isset( $req->query['withScriptContentType'] ) ) {

test/data/trusted-html.html

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset=utf-8 />
5+
<title>body</title>
6+
</head>
7+
<body>
8+
<div id="qunit-fixture"></div>
9+
<script src="../../dist/jquery.min.js"></script>
10+
<script src="iframeTest.js"></script>
11+
<script>
12+
var i, input, elem, tags, policy,
13+
results = [],
14+
inputs = [
15+
[ "<div></div>", "<div class='test'></div>", [ "div" ] ],
16+
[ "<div></div>", "<div class='test'></div><span class='test'></span>",
17+
[ "div", "span" ] ],
18+
[ "<table></table>", "<td class='test'></td>", [ "td" ] ],
19+
[ "<select></select>", "<option class='test'></option>", [ "option" ] ]
20+
];
21+
22+
function runTests( messagePrefix, getHtmlWrapper ) {
23+
for ( i = 0; i < inputs.length; i++ ) {
24+
input = inputs[ i ];
25+
elem = jQuery( getHtmlWrapper( input[ 0 ] ) );
26+
elem.append( getHtmlWrapper( input[ 1 ] ) );
27+
tags = elem.find( ".test" ).toArray().map( function( node ) {
28+
return node.nodeName.toLowerCase();
29+
} );
30+
results.push( {
31+
actual: tags,
32+
expected: input[ 2 ],
33+
message: messagePrefix + ": " + input[ 2 ].join( ", " )
34+
} );
35+
}
36+
37+
elem = jQuery( getHtmlWrapper( "<div></div>" ) );
38+
elem.append( getHtmlWrapper( "text content" ) );
39+
results.push( {
40+
actual: elem.html(),
41+
expected: "text content",
42+
message: messagePrefix + ": text content properly appended"
43+
} );
44+
}
45+
46+
if ( typeof trustedTypes !== "undefined" ) {
47+
policy = trustedTypes.createPolicy( "jquery-test-policy", {
48+
createHTML: function( html ) {
49+
return html;
50+
}
51+
} );
52+
53+
runTests( "TrustedHTML", function wrapInTrustedHtml( input ) {
54+
return policy.createHTML( input );
55+
} );
56+
} else {
57+
58+
// No TrustedHTML support so let's at least run tests with object wrappers
59+
// with a proper `toString` function. This also shows that jQuery support
60+
// of TrustedHTML is generic and would work with similar APIs out of the box
61+
// as well. Ideally, we'd run these tests in browsers with TrustedHTML support
62+
// as well but due to the CSP TrustedHTML enforcement these tests would fail.
63+
runTests( "Object wrapper", function( input ) {
64+
return {
65+
toString: function toString() {
66+
return input;
67+
}
68+
};
69+
} );
70+
}
71+
72+
startIframeTest( results );
73+
</script>
74+
</body>
75+
</html>

test/middleware-mockserver.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ var mocks = {
222222
cspFrame: function( req, resp ) {
223223
resp.writeHead( 200, {
224224
"Content-Type": "text/html",
225-
"Content-Security-Policy": "default-src 'self'; report-uri /base/test/data/mock.php?action=cspLog"
225+
"Content-Security-Policy": "default-src 'self'; require-trusted-types-for 'script'; report-uri /base/test/data/mock.php?action=cspLog"
226226
} );
227227
var body = fs.readFileSync( __dirname + "/data/csp.include.html" ).toString();
228228
resp.end( body );
@@ -256,6 +256,14 @@ var mocks = {
256256
resp.writeHead( 200 );
257257
resp.end();
258258
},
259+
trustedHtml: function( req, resp ) {
260+
resp.writeHead( 200, {
261+
"Content-Type": "text/html",
262+
"Content-Security-Policy": "require-trusted-types-for 'script'; report-uri /base/test/data/mock.php?action=cspLog"
263+
} );
264+
var body = fs.readFileSync( __dirname + "/data/trusted-html.html" ).toString();
265+
resp.end( body );
266+
},
259267
errorWithScript: function( req, resp ) {
260268
if ( req.query.withScriptContentType ) {
261269
resp.writeHead( 404, { "Content-Type": "application/javascript" } );

test/unit/manipulation.js

+16
Original file line numberDiff line numberDiff line change
@@ -3008,3 +3008,19 @@ QUnit.test( "Works with invalid attempts to close the table wrapper", function(
30083008
assert.strictEqual( elem[ 0 ].nodeName.toLowerCase(), "td", "First element is td" );
30093009
assert.strictEqual( elem[ 1 ].nodeName.toLowerCase(), "td", "Second element is td" );
30103010
} );
3011+
3012+
// Test trustedTypes support in browsers where they're supported (currently Chrome 83+).
3013+
// Browsers with no TrustedHTML support still run tests on object wrappers with
3014+
// a proper `toString` function.
3015+
testIframe(
3016+
"Basic TrustedHTML support (gh-4409)",
3017+
"mock.php?action=trustedHtml",
3018+
function( assert, jQuery, window, document, test ) {
3019+
3020+
assert.expect( 5 );
3021+
3022+
test.forEach( function( result ) {
3023+
assert.deepEqual( result.actual, result.expected, result.message );
3024+
} );
3025+
}
3026+
);

0 commit comments

Comments
 (0)