papegaaij commented on code in PR #1880:
URL: https://github.com/apache/wicket/pull/1880#discussion_r4540165606
##########
wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js:
##########
@@ -229,6 +229,79 @@
}
};
+ /**
+ * Trusted Types
+ *
+ * A page with the Content-Security-Policy "require-trusted-types-for
'script'" accepts no
+ * strings at DOM sinks such as innerHTML. Wicket trusts the markup and
the scripts of an Ajax
+ * response, so the policy 'wicket' passes them on unchanged. They stay
strings where the
+ * browser has no Trusted Types or the page does not allow the policy.
+ */
+ Wicket.TrustedTypes = (function () {
+ const identity = function (value) {
+ return value;
+ };
+ let policy;
+
+ const getPolicy = function () {
+ if (!policy) {
+ policy = { createHTML: identity, createScript:
identity, createScriptURL: identity };
+ if (window.trustedTypes &&
window.trustedTypes.createPolicy) {
+ try {
+ policy =
window.trustedTypes.createPolicy('wicket', policy);
Review Comment:
This runs in every browser that supports Trusted Types, including when the
application did not call `requireTrustedTypes()`. With the option disabled,
that has visible effects:
- With jQuery 4, `toMarkup` passes a `TrustedHTML` object to jQuery, which
hands it to `jQuery.htmlPrefilter`. Any override of that hook that does string
operations throws. jquery-migrate 4.0.2, which Wicket ships, is one example.
Its `self-closed-tags` patch is off by default, but applications that still
have `<div/>`-style markup enable it, and it calls `html.replace(...)`
(`jquery-migrate-4.0.2.js:1017`). Every Ajax update then fails with
`html.replace is not a function`.
- An application that enforces Trusted Types through its own header with a
`default` policy now has Wicket's markup bypass that policy.
- An application whose header restricts policy names without allowing
`wicket` gets an error logged on every page, and with a report-only header a
violation report on every page.
Could the policy be created, and values wrapped, only when the application
enabled the option? For instance, the server could render a flag when the CSP
contains `trusted-types wicket`. With the flag off, `html()`, `script()` and
`scriptURL()` should return their input unchanged, and the `text xml` converter
should not be installed. The same applies to `wicket-ajax.js`.
##########
wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js:
##########
@@ -1467,7 +1543,7 @@
// jQuery 1.9+ expects '<' as the very
first character in text
const cleanedText = text.trim();
- const $newElement = jQuery(cleanedText);
+ const $newElement =
jQuery(toMarkup(cleanedText));
Review Comment:
With the option enabled, this has to work for markup that contains
`<script>` elements, inline or external. Right now jQuery evaluates them from a
string and the update fails, and this is the default engine.
One way to solve this: parse the markup the way `wicket-ajax.js` does, with
a `template` element and `reviveScripts`, and insert the nodes with the DOM API
instead of through jQuery's manipulation methods, which evaluate scripts
themselves. Removed elements would still need jQuery's data and event cleanup.
That would also make `toMarkup` and its trailing-text handling unnecessary. The
same applies to `add` below.
##########
wicket-user-guide/src/main/asciidoc/security/security_6.adoc:
##########
@@ -61,6 +61,17 @@ _CSPHeaderConfiguration_ defines several methods to tune the
Content Security Po
"https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css");
----
+No preset requires
https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API[Trusted
Types]. With _CSPHeaderConfiguration.requireTrustedTypes()_ the directives
_require-trusted-types-for 'script'_ and _trusted-types wicket_ are added,
which make the browser reject strings at DOM sinks such as _innerHTML_.
Wicket's own JavaScript passes the markup and the scripts of an Ajax response
through a policy named _wicket_ that leaves them unchanged, so the response of
your server stays trusted as before. Other scripts on the page need a policy of
their own, whose name has to be added to the _trusted-types_ directive:
+
+[source,java]
+----
+ getCspSettings().blocking()
+ .requireTrustedTypes()
+ .add(CSPDirective.TRUSTED_TYPES, "myPolicy");
+----
+
+Ajax call listeners and dynamic extra parameters that reach _Wicket.Ajax_ as
strings instead of functions are not executed under these directives. With the
default jQuery based Ajax implementation jQuery 4 is required, and a _script_
element inside the markup of a component makes the Ajax update of that
component fail, because jQuery evaluates such elements from a string. The
jQuery-free implementation (_WicketAjaxResourceReference_) executes them.
Review Comment:
With the option enabled, the only limitation we want to keep is the `eval`
of the autocomplete's `onselect` expression in `wicket-autocomplete.js`, so
this paragraph should name only that one. It can also note that application
JavaScript passing handlers to `Wicket.Ajax` as strings won't run. The `script`
element limitation should go away with the engine change.
##########
wicket-core/src/test/js/trusted-types.js:
##########
@@ -0,0 +1,249 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*global QUnit: true, MultiSelector: true */
+
+Wicket.Event.add(window, 'domready', function() {
+ "use strict";
+
+ const { module, test } = QUnit;
+
+ QUnit.config.testTimeout = 3000;
+
+ let logError, errors;
+
+ // builds a node of an Ajax response without a parser, which would need
a TrustedHTML itself
+ const xmlElement = function (tagName, attributes, text) {
+ const xml = document.implementation.createDocument(null,
'head', null);
+ const element = xml.createElement(tagName);
+ for (const name in attributes) {
+ element.setAttribute(name, attributes[name]);
+ }
+ if (text) {
+ element.appendChild(xml.createTextNode(text));
+ }
+ return element;
+ };
+
+ /*
+ * The page requires Trusted Types for every script sink and allows the
policy 'wicket' only,
+ * so a string that reaches a sink fails the test with a TypeError.
+ */
+ module('Trusted Types', {
+ beforeEach: function () {
+ errors = [];
+ logError = Wicket.Log.error;
+ Wicket.Log.error = function () {
+
errors.push(Array.prototype.join.call(arguments, ' '));
+ };
+ },
+ afterEach: function (assert) {
+ Wicket.Log.error = logError;
+ assert.deepEqual(errors, [], 'No error is logged');
+ }
+ });
+
+ test('the page enforces Trusted Types', assert => {
+ assert.throws(function () {
+ document.createElement('div').innerHTML =
'<b>string</b>';
+ }, TypeError);
+ });
+
+ test('Wicket.Xml.parse', assert => {
+ const xml =
Wicket.Xml.parse('<ajax-response><evaluate>1</evaluate></ajax-response>');
+
+ assert.equal(xml.documentElement.tagName, 'ajax-response');
+ });
+
+ test('strings are passed on when the page does not allow the policy',
assert => {
+ const done = assert.async();
+ const frame = document.createElement('iframe');
+ Wicket.$('qunit-fixture').appendChild(frame);
+ const frameWindow = frame.contentWindow;
+ // the frame inherits the policy of the page, which allows the
name 'wicket' only once
+ const taken = frameWindow.trustedTypes.createPolicy('wicket', {
+ createScriptURL: function (url) {
+ return url;
+ }
+ });
+ const sources =
Array.prototype.map.call(document.querySelectorAll('script[src*="jquery"],
script[src*="wicket-ajax"]'), function (script) {
+ return script.src;
+ });
+
+ const load = function () {
+ if (sources.length > 0) {
+ const script =
frameWindow.document.createElement('script');
+ script.src =
taken.createScriptURL(sources.shift());
+ script.onload = load;
+ frameWindow.document.head.appendChild(script);
+ return;
+ }
+ const frameErrors = [];
+ frameWindow.Wicket.Log.error = function (message) {
+ frameErrors.push(message);
+ };
+
+ assert.throws(function () {
+
frameWindow.Wicket.Xml.parse('<ajax-response/>');
+ }, frameWindow.TypeError);
+ assert.deepEqual(frameErrors, ["Wicket.TrustedTypes:
Cannot create the policy 'wicket'"]);
+ done();
+ };
+ load();
+ });
+
+ test('Wicket.DOM.replace', assert => {
+ Wicket.DOM.replace(Wicket.$('componentToReplace'), '<span
id="componentToReplace">new <b>body</b></span>');
+ Wicket.DOM.replace(Wicket.$('rowToReplace'), '<tr
id="rowToReplace"><td>new cell</td></tr>');
+
+
assert.equal(Wicket.$('componentToReplace').tagName.toLowerCase(), 'span');
+ assert.equal(Wicket.$('componentToReplace').innerHTML, 'new
<b>body</b>');
+ assert.equal(Wicket.$('rowToReplace').cells[0].textContent,
'new cell');
+ });
+
+ test('Wicket.DOM.replace - markup followed by text', assert => {
+ Wicket.DOM.replace(Wicket.$('withTextAfter'), '<span
id="withTextAfter">new body</span> text');
+
+ assert.equal(Wicket.$('withTextAfter').tagName.toLowerCase(),
'span');
+ assert.equal(Wicket.$('withTextAfter').textContent, 'new body');
+ });
+
+ // jQuery 4.0.0 evaluates the scripts of the markup it inserts itself,
from a string
+ test.if('Wicket.DOM.replace - inline and external scripts in the
markup', typeof(jQuery) === 'undefined', assert => {
Review Comment:
Once the jQuery engine handles scripts in markup, this test should run for
both engines.
##########
wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/MultiFileUploadField.js:
##########
@@ -176,43 +182,25 @@ function MultiSelector( eprefix, list_target, max,
useMultipleAttr, del_label ){
if (inputElement.files && inputElement.files.length > 0)
{
var files = inputElement.files;
- var retVal = "";
+ var retVal = [];
Review Comment:
This changes the result of `getOnlyFileNames()` from a string to an array,
and `getOnlyFileName()` below no longer escapes. Both are overridable functions
of `MultiSelector`, so applications that never enable Trusted Types will see
the change. Could you keep both functions as they are, deprecated if you like,
and add a new function that returns the unescaped names as an array for
`addListRow` to use? Building text nodes is the right approach; it's only the
existing contract that should stay.
##########
wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js:
##########
@@ -229,6 +229,79 @@
}
};
+ /**
+ * Trusted Types
+ *
+ * A page with the Content-Security-Policy "require-trusted-types-for
'script'" accepts no
+ * strings at DOM sinks such as innerHTML. Wicket trusts the markup and
the scripts of an Ajax
+ * response, so the policy 'wicket' passes them on unchanged. They stay
strings where the
+ * browser has no Trusted Types or the page does not allow the policy.
+ */
+ Wicket.TrustedTypes = (function () {
Review Comment:
Smaller point: `html()`, `script()` and `scriptURL()` turn any string into a
trusted value, and any script on the page can call them. For an application
that enables the option, this weakens what Trusted Types offers, because the
set of code that can create trusted values is no longer small and auditable.
Wicket trusts the markup and scripts the server sends, so routing the Ajax
response through this policy is fine. Please at least document on this object
that it must only be given markup and scripts that come from the server. The
guide should also say that, with the option enabled, application code must not
pass untrusted strings to `Wicket.DOM.replace`, `Wicket.DOM.add` or
`Wicket.Xml.parse`.
##########
wicket-core/src/main/java/org/apache/wicket/csp/CSPHeaderConfiguration.java:
##########
@@ -169,6 +178,22 @@ public CSPHeaderConfiguration reportBackAt(String
mountPath)
return add(REPORT_URI, new RelativeURICSPValue(mountPath));
}
+ /**
+ * Adds {@code require-trusted-types-for 'script'; trusted-types
wicket} to the CSP, which makes
+ * the browser reject strings at script injection sinks such as {@code
innerHTML}. Wicket's own
+ * JavaScript passes the markup and scripts of an Ajax response through
the
+ * {@value #TRUSTED_TYPES_POLICY} policy unchanged, so the response of
the server stays
+ * trusted as before. Other scripts on the page have to use a policy of
their own, to be allowed
+ * with {@link #add(CSPDirective, String...)}. No preset includes these
directives.
+ *
+ * @return {@code this} for chaining
+ * @since 12.0.0
+ */
+ public CSPHeaderConfiguration requireTrustedTypes()
+ {
+ return add(REQUIRE_TRUSTED_TYPES_FOR,
"'script'").add(TRUSTED_TYPES, TRUSTED_TYPES_POLICY);
Review Comment:
Calling this twice throws an `IllegalArgumentException`, because
`require-trusted-types-for` accepts only one value. If both a library and the
application call it, the application fails at startup. Could it be idempotent,
skipping values that are already present?
##########
wicket-core/src/main/java/org/apache/wicket/csp/CSPDirective.java:
##########
@@ -123,8 +124,82 @@ public void checkValueForDirective(CSPRenderable value,
throw new IllegalArgumentException("Illegal URI
for report-uri directive", urise);
}
}
+ },
+ /**
+ * Makes the browser reject strings at script injection sinks such as
{@code innerHTML}. The
+ * only value is {@code 'script'}.
+ *
+ * @since 12.0.0
+ * @see <a
href="https://www.w3.org/TR/trusted-types/">https://www.w3.org/TR/trusted-types/</a>
+ */
+ REQUIRE_TRUSTED_TYPES_FOR("require-trusted-types-for")
+ {
+ /**
+ * Only allow {@code 'script'}, and only once.
+ */
+ @Override
+ public void checkValueForDirective(CSPRenderable value,
+ List<CSPRenderable> existingDirectiveValues)
+ {
+ if (!existingDirectiveValues.isEmpty())
+ {
+ throw new IllegalArgumentException(
+ "A require-trusted-types-for directive
can only contain one value, it already "
+ + "contains " +
existingDirectiveValues);
+ }
+ if (!(value instanceof FixedCSPValue) ||
!"'script'".equals(value.toString()))
+ {
+ throw new IllegalArgumentException(
+ "A require-trusted-types-for directive
can only contain 'script', not "
+ + value);
+ }
+ }
+ },
+ /**
+ * Restricts the names of the Trusted Types policies a page may create.
The values are policy
+ * names, {@code 'allow-duplicates'}, {@code *} or a single {@code
'none'}.
+ *
+ * @since 12.0.0
+ * @see <a
href="https://www.w3.org/TR/trusted-types/">https://www.w3.org/TR/trusted-types/</a>
+ */
+ TRUSTED_TYPES("trusted-types")
+ {
+ /**
+ * Only allow policy names and the keywords of the directive,
and block {@code 'none'}
+ * next to other values.
+ */
+ @Override
+ public void checkValueForDirective(CSPRenderable value,
+ List<CSPRenderable> existingDirectiveValues)
+ {
+ if (!(value instanceof FixedCSPValue)
Review Comment:
`add(TRUSTED_TYPES, CSPDirectiveSrcValue.NONE)` is rejected here, and only
the string `"'none'"` is accepted; `trustedTypesDoesNotSupportOtherValues` even
asserts that. Every other directive uses `CSPDirectiveSrcValue.NONE` for
`'none'`, so please accept it here too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]