Adding mapbox-gl branch
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
|
||||
/**
|
||||
* @fileoverview SafeHtml factory methods for creating object and embed tags
|
||||
* for loading Flash files.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.flash');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.html.SafeHtml');
|
||||
|
||||
|
||||
/**
|
||||
* Attributes and param tag name attributes not allowed to be overriden
|
||||
* when calling createObject() and createObjectForOldIe().
|
||||
*
|
||||
* While values that should be specified as params are probably not
|
||||
* recognized as attributes, we block them anyway just to be sure.
|
||||
* @const {!Array<string>}
|
||||
* @private
|
||||
*/
|
||||
goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_ = [
|
||||
'classid', // Used on old IE.
|
||||
'data', // Used in <object> to specify a URL.
|
||||
'movie', // Used on old IE.
|
||||
'type', // Used in <object> on for non-IE/modern IE.
|
||||
'typemustmatch' // Always set to a fixed value.
|
||||
];
|
||||
|
||||
|
||||
goog.html.flash.createEmbed = function(src, opt_attributes) {
|
||||
var fixedAttributes = {
|
||||
'src': src,
|
||||
'type': 'application/x-shockwave-flash',
|
||||
'pluginspage': 'https://www.macromedia.com/go/getflashplayer'
|
||||
};
|
||||
var defaultAttributes = {
|
||||
'allownetworking': 'none',
|
||||
'allowscriptaccess': 'never'
|
||||
};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, defaultAttributes, opt_attributes);
|
||||
return goog.html.SafeHtml.
|
||||
createSafeHtmlTagSecurityPrivateDoNotAccessOrElse('embed', attributes);
|
||||
};
|
||||
|
||||
|
||||
goog.html.flash.createObject = function(
|
||||
data, opt_params, opt_attributes) {
|
||||
goog.html.flash.verifyKeysNotInMaps(
|
||||
goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_,
|
||||
opt_attributes,
|
||||
opt_params);
|
||||
|
||||
var paramTags = goog.html.flash.combineParams(
|
||||
{
|
||||
'allownetworking': 'none',
|
||||
'allowscriptaccess': 'never'
|
||||
},
|
||||
opt_params);
|
||||
var fixedAttributes = {
|
||||
'data': data,
|
||||
'type': 'application/x-shockwave-flash',
|
||||
'typemustmatch': ''
|
||||
};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, {}, opt_attributes);
|
||||
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'object', attributes, paramTags);
|
||||
};
|
||||
|
||||
|
||||
goog.html.flash.createObjectForOldIe = function(
|
||||
movie, opt_params, opt_attributes) {
|
||||
goog.html.flash.verifyKeysNotInMaps(
|
||||
goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_,
|
||||
opt_attributes,
|
||||
opt_params);
|
||||
|
||||
var paramTags = goog.html.flash.combineParams(
|
||||
{
|
||||
'allownetworking': 'none',
|
||||
'allowscriptaccess': 'never',
|
||||
'movie': movie
|
||||
},
|
||||
opt_params);
|
||||
var fixedAttributes =
|
||||
{'classid': 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, {}, opt_attributes);
|
||||
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'object', attributes, paramTags);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {!Object<string, string|!goog.string.TypedString>} defaultParams
|
||||
* @param {!Object<string, string>=}
|
||||
* opt_params Optional params passed to create*().
|
||||
* @return {!Array<!goog.html.SafeHtml>} Combined params.
|
||||
* @throws {Error} If opt_attributes contains an attribute with the same name
|
||||
* as an attribute in fixedAttributes.
|
||||
* @package
|
||||
*/
|
||||
goog.html.flash.combineParams = function(defaultParams, opt_params) {
|
||||
var combinedParams = {};
|
||||
var name;
|
||||
|
||||
for (name in defaultParams) {
|
||||
goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');
|
||||
combinedParams[name] = defaultParams[name];
|
||||
}
|
||||
for (name in opt_params) {
|
||||
var nameLower = name.toLowerCase();
|
||||
if (nameLower in defaultParams) {
|
||||
delete combinedParams[nameLower];
|
||||
}
|
||||
combinedParams[name] = opt_params[name];
|
||||
}
|
||||
|
||||
var paramTags = [];
|
||||
for (name in combinedParams) {
|
||||
paramTags.push(
|
||||
goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'param', {'name': name, 'value': combinedParams[name]}));
|
||||
|
||||
}
|
||||
return paramTags;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks that keys are not present as keys in maps.
|
||||
* @param {!Array<string>} keys Keys that must not be present, lower-case.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Optional attributes passed to create*().
|
||||
* @param {!Object<string, string>=} opt_params Optional params passed to
|
||||
* createObject*().
|
||||
* @throws {Error} If any of keys exist as a key, ignoring case, in
|
||||
* opt_attributes or opt_params.
|
||||
* @package
|
||||
*/
|
||||
goog.html.flash.verifyKeysNotInMaps = function(
|
||||
keys, opt_attributes, opt_params) {
|
||||
var verifyNotInMap = function(keys, map, type) {
|
||||
for (var keyMap in map) {
|
||||
var keyMapLower = keyMap.toLowerCase();
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var keyToCheck = keys[i];
|
||||
goog.asserts.assert(keyToCheck.toLowerCase() == keyToCheck);
|
||||
if (keyMapLower == keyToCheck) {
|
||||
throw Error('Cannot override "' + keyToCheck + '" ' + type +
|
||||
', got "' + keyMap + '" with value "' + map[keyMap] + '"');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
verifyNotInMap(keys, opt_attributes, 'attribute');
|
||||
verifyNotInMap(keys, opt_params, 'param');
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html.flash</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.flashTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,111 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.flash.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.flashTest');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.flash');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.flashTest');
|
||||
|
||||
|
||||
function testCreateEmbed() {
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted&'));
|
||||
assertSameHtml(
|
||||
'<embed ' +
|
||||
'src="https://google.com/trusted&" ' +
|
||||
'type="application/x-shockwave-flash" ' +
|
||||
'pluginspage="https://www.macromedia.com/go/getflashplayer" ' +
|
||||
'allownetworking="none" ' +
|
||||
'allowScriptAccess="always<" ' +
|
||||
'class="test<">',
|
||||
goog.html.flash.createEmbed(
|
||||
trustedResourceUrl,
|
||||
{'allowScriptAccess': 'always<', 'class': 'test<'}));
|
||||
|
||||
// Cannot override attributes, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.flash.createEmbed(
|
||||
trustedResourceUrl, {'Type': 'cannotdothis'});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testCreateObject() {
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted&'));
|
||||
assertSameHtml(
|
||||
'<object data="https://google.com/trusted&" ' +
|
||||
'type="application/x-shockwave-flash" typemustmatch="" ' +
|
||||
'class="test<">' +
|
||||
'<param name="allownetworking" value="none">' +
|
||||
'<param name="allowScriptAccess" value="always<">' +
|
||||
'</object>',
|
||||
goog.html.flash.createObject(
|
||||
trustedResourceUrl,
|
||||
{'allowScriptAccess': 'always<'}, {'class': 'test<'}));
|
||||
|
||||
// Cannot override params, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.flash.createObject(
|
||||
trustedResourceUrl, {'datA': 'cantdothis'});
|
||||
});
|
||||
|
||||
// Cannot override attributes, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.flash.createObject(
|
||||
trustedResourceUrl, {}, {'datA': 'cantdothis'});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testCreateObjectForOldIe() {
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted&'));
|
||||
assertSameHtml(
|
||||
'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' +
|
||||
'class="test<">' +
|
||||
'<param name="allownetworking" value="none">' +
|
||||
'<param name="movie" value="https://google.com/trusted&">' +
|
||||
'<param name="allowScriptAccess" value="always<">' +
|
||||
'</object>',
|
||||
goog.html.flash.createObjectForOldIe(
|
||||
trustedResourceUrl,
|
||||
{'allowScriptAccess': 'always<'}, {'class': 'test<'}));
|
||||
|
||||
// Cannot override params, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.flash.createObjectForOldIe(
|
||||
trustedResourceUrl, {'datA': 'cantdothis'});
|
||||
});
|
||||
|
||||
// Cannot override attributes, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.flash.createObjectForOldIe(
|
||||
trustedResourceUrl, {}, {'datA': 'cantdothis'});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function assertSameHtml(expected, html) {
|
||||
assertEquals(expected, goog.html.SafeHtml.unwrap(html));
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Conversions from plain string to goog.html types for use in
|
||||
* legacy APIs that do not use goog.html types.
|
||||
*
|
||||
* This file provides conversions to create values of goog.html types from plain
|
||||
* strings. These conversions are intended for use in legacy APIs that consume
|
||||
* HTML in the form of plain string types, but whose implementations use
|
||||
* goog.html types internally (and expose such types in an augmented, HTML-type-
|
||||
* safe API).
|
||||
*
|
||||
* IMPORTANT: No new code should use the conversion functions in this file.
|
||||
*
|
||||
* The conversion functions in this file are guarded with global flag
|
||||
* (goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS). If set to false, it
|
||||
* effectively "locks in" an entire application to only use HTML-type-safe APIs.
|
||||
*
|
||||
* Intended use of the functions in this file are as follows:
|
||||
*
|
||||
* Many Closure and application-specific classes expose methods that consume
|
||||
* values that in the class' implementation are forwarded to DOM APIs that can
|
||||
* result in security vulnerabilities. For example, goog.ui.Dialog's setContent
|
||||
* method consumes a string that is assigned to an element's innerHTML property;
|
||||
* if this string contains untrusted (attacker-controlled) data, this can result
|
||||
* in a cross-site-scripting vulnerability.
|
||||
*
|
||||
* Widgets such as goog.ui.Dialog are being augmented to expose safe APIs
|
||||
* expressed in terms of goog.html types. For instance, goog.ui.Dialog has a
|
||||
* method setSafeHtmlContent that consumes an object of type goog.html.SafeHtml,
|
||||
* a type whose contract guarantees that its value is safe to use in HTML
|
||||
* context, i.e. can be safely assigned to .innerHTML. An application that only
|
||||
* uses this API is forced to only supply values of this type, i.e. values that
|
||||
* are safe.
|
||||
*
|
||||
* However, the legacy method setContent cannot (for the time being) be removed
|
||||
* from goog.ui.Dialog, due to a large number of existing callers. The
|
||||
* implementation of goog.ui.Dialog has been refactored to use
|
||||
* goog.html.SafeHtml throughout. This in turn requires that the value consumed
|
||||
* by its setContent method is converted to goog.html.SafeHtml in an unchecked
|
||||
* conversion. The conversion function is provided by this file:
|
||||
* goog.html.legacyconversions.safeHtmlFromString.
|
||||
*
|
||||
* Note that the semantics of the conversions in goog.html.legacyconversions are
|
||||
* very different from the ones provided by goog.html.uncheckedconversions: The
|
||||
* latter are for use in code where it has been established through manual
|
||||
* security review that the value produced by a piece of code must always
|
||||
* satisfy the SafeHtml contract (e.g., the output of a secure HTML sanitizer).
|
||||
* In uses of goog.html.legacyconversions, this guarantee is not given -- the
|
||||
* value in question originates in unreviewed legacy code and there is no
|
||||
* guarantee that it satisfies the SafeHtml contract.
|
||||
*
|
||||
* To establish correctness with confidence, application code should be
|
||||
* refactored to use SafeHtml instead of plain string to represent HTML markup,
|
||||
* and to use goog.html-typed APIs (e.g., goog.ui.Dialog#setSafeHtmlContent
|
||||
* instead of goog.ui.Dialog#setContent).
|
||||
*
|
||||
* To prevent introduction of new vulnerabilities, application owners can
|
||||
* effectively disable unsafe legacy APIs by compiling with the define
|
||||
* goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS set to false. When
|
||||
* set, this define causes the conversion methods in this file to
|
||||
* unconditionally throw an exception.
|
||||
*
|
||||
* Note that new code should always be compiled with
|
||||
* ALLOW_LEGACY_CONVERSIONS=false. At some future point, the default for this
|
||||
* define may change to false.
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.html.legacyconversions');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether conversion from string to goog.html types for
|
||||
* legacy API purposes is permitted.
|
||||
*
|
||||
* If false, the conversion functions in this file unconditionally throw an
|
||||
* exception.
|
||||
*/
|
||||
goog.define('goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS', true);
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" from string to SafeHtml for legacy API
|
||||
* purposes.
|
||||
*
|
||||
* Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false,
|
||||
* and instead this function unconditionally throws an exception.
|
||||
*
|
||||
* @param {string} html A string to be converted to SafeHtml.
|
||||
* @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml
|
||||
* object.
|
||||
*/
|
||||
goog.html.legacyconversions.safeHtmlFromString = function(html) {
|
||||
goog.html.legacyconversions.throwIfConversionDisallowed_();
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
html, null /* dir */);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" from string to TrustedResourceUrl for
|
||||
* legacy API purposes.
|
||||
*
|
||||
* Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false,
|
||||
* and instead this function unconditionally throws an exception.
|
||||
*
|
||||
* @param {string} url A string to be converted to TrustedResourceUrl.
|
||||
* @return {!goog.html.TrustedResourceUrl} The value of url, wrapped in a
|
||||
* TrustedResourceUrl object.
|
||||
*/
|
||||
goog.html.legacyconversions.trustedResourceUrlFromString = function(url) {
|
||||
goog.html.legacyconversions.throwIfConversionDisallowed_();
|
||||
return goog.html.TrustedResourceUrl.
|
||||
createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" from string to SafeUrl for legacy API
|
||||
* purposes.
|
||||
*
|
||||
* Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false,
|
||||
* and instead this function unconditionally throws an exception.
|
||||
*
|
||||
* @param {string} url A string to be converted to SafeUrl.
|
||||
* @return {!goog.html.SafeUrl} The value of url, wrapped in a SafeUrl
|
||||
* object.
|
||||
*/
|
||||
goog.html.legacyconversions.safeUrlFromString = function(url) {
|
||||
goog.html.legacyconversions.throwIfConversionDisallowed_();
|
||||
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @private {function(): undefined}
|
||||
*/
|
||||
goog.html.legacyconversions.reportCallback_ = goog.nullFunction;
|
||||
|
||||
|
||||
/**
|
||||
* Sets a function that will be called every time a legacy conversion is
|
||||
* performed. The function is called with no parameters but it can use
|
||||
* goog.debug.getStacktrace to get a stacktrace.
|
||||
*
|
||||
* @param {function(): undefined} callback Error callback as defined above.
|
||||
*/
|
||||
goog.html.legacyconversions.setReportCallback = function(callback) {
|
||||
goog.html.legacyconversions.reportCallback_ = callback;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks whether legacy conversion is allowed. Throws an exception if not.
|
||||
* @private
|
||||
*/
|
||||
goog.html.legacyconversions.throwIfConversionDisallowed_ = function() {
|
||||
if (!goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS) {
|
||||
throw Error(
|
||||
'Error: Legacy conversion from string to goog.html types is disabled');
|
||||
}
|
||||
goog.html.legacyconversions.reportCallback_();
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2006 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.legacyconversionsTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.legacyconversions.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.legacyconversionsTest');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.legacyconversions');
|
||||
goog.require('goog.testing.PropertyReplacer');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.legacyconversionsTest');
|
||||
|
||||
|
||||
/** @type {!goog.testing.PropertyReplacer} */
|
||||
var stubs = new goog.testing.PropertyReplacer();
|
||||
|
||||
|
||||
function setUp() {
|
||||
// Reset goog.html.legacyconveresions global defines for each test case.
|
||||
stubs.set(goog.html.legacyconversions, 'ALLOW_LEGACY_CONVERSIONS', true);
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlFromString_allowedIfNotGloballyDisabled() {
|
||||
var helloWorld = 'Hello <em>World</em>';
|
||||
var safeHtml = goog.html.legacyconversions.safeHtmlFromString(helloWorld);
|
||||
assertEquals(helloWorld, goog.html.SafeHtml.unwrap(safeHtml));
|
||||
assertNull(safeHtml.getDirection());
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlFromString_guardedByGlobalFlag() {
|
||||
stubs.set(goog.html.legacyconversions, 'ALLOW_LEGACY_CONVERSIONS', false);
|
||||
assertEquals(
|
||||
'Error: Legacy conversion from string to goog.html types is disabled',
|
||||
assertThrows(function() {
|
||||
goog.html.legacyconversions.safeHtmlFromString(
|
||||
'Possibly untrusted <html>');
|
||||
}).message);
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlFromString_reports() {
|
||||
var reported = false;
|
||||
goog.html.legacyconversions.setReportCallback(function() {
|
||||
reported = true;
|
||||
});
|
||||
goog.html.legacyconversions.safeHtmlFromString('<html>');
|
||||
assertTrue('Expected legacy conversion to be reported.', reported);
|
||||
|
||||
reported = false;
|
||||
stubs.set(goog.html.legacyconversions, 'ALLOW_LEGACY_CONVERSIONS', false);
|
||||
try {
|
||||
goog.html.legacyconversions.safeHtmlFromString('<html>');
|
||||
} catch (expected) {
|
||||
}
|
||||
assertFalse('Expected legacy conversion to not be reported.', reported);
|
||||
|
||||
stubs.set(goog.html.legacyconversions, 'ALLOW_LEGACY_CONVERSIONS', true);
|
||||
goog.html.legacyconversions.setReportCallback(goog.nullFunction);
|
||||
goog.html.legacyconversions.safeHtmlFromString('<html>');
|
||||
assertFalse('Expected legacy conversion to not be reported.', reported);
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlFromString() {
|
||||
var url = 'https://www.google.com';
|
||||
var safeUrl = goog.html.legacyconversions.safeUrlFromString(url);
|
||||
assertEquals(url, goog.html.SafeUrl.unwrap(safeUrl));
|
||||
}
|
||||
|
||||
|
||||
function testTrustedResourceUrlFromString() {
|
||||
var url = 'https://www.google.com/script.js';
|
||||
var trustedResourceUrl =
|
||||
goog.html.legacyconversions.trustedResourceUrlFromString(url);
|
||||
assertEquals(url, goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl));
|
||||
}
|
||||
@@ -0,0 +1,729 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
|
||||
/**
|
||||
* @fileoverview The SafeHtml type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.SafeHtml');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.dom.tags');
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.i18n.bidi.DirectionalString');
|
||||
goog.require('goog.object');
|
||||
goog.require('goog.string');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A string that is safe to use in HTML context in DOM APIs and HTML documents.
|
||||
*
|
||||
* A SafeHtml is a string-like object that carries the security type contract
|
||||
* that its value as a string will not cause untrusted script execution when
|
||||
* evaluated as HTML in a browser.
|
||||
*
|
||||
* Values of this type are guaranteed to be safe to use in HTML contexts,
|
||||
* such as, assignment to the innerHTML DOM property, or interpolation into
|
||||
* a HTML template in HTML PC_DATA context, in the sense that the use will not
|
||||
* result in a Cross-Site-Scripting vulnerability.
|
||||
*
|
||||
* Instances of this type must be created via the factory methods
|
||||
* ({@code goog.html.SafeHtml.create}, {@code goog.html.SafeHtml.htmlEscape}),
|
||||
* etc and not by invoking its constructor. The constructor intentionally
|
||||
* takes no parameters and the type is immutable; hence only a default instance
|
||||
* corresponding to the empty string can be obtained via constructor invocation.
|
||||
*
|
||||
* @see goog.html.SafeHtml#create
|
||||
* @see goog.html.SafeHtml#htmlEscape
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.i18n.bidi.DirectionalString}
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.SafeHtml = function() {
|
||||
/**
|
||||
* The contained value of this SafeHtml. The field has a purposely ugly
|
||||
* name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.SafeHtml#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
|
||||
/**
|
||||
* This SafeHtml's directionality, or null if unknown.
|
||||
* @private {?goog.i18n.bidi.Dir}
|
||||
*/
|
||||
this.dir_ = null;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true;
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.html.SafeHtml.prototype.getDirection = function() {
|
||||
return this.dir_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeHtml.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Returns this SafeHtml's value a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code SafeHtml}, use {@code goog.html.SafeHtml.unwrap} instead of
|
||||
* this method. If in doubt, assume that it's security relevant. In particular,
|
||||
* note that goog.html functions which return a goog.html type do not guarantee
|
||||
* that the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
|
||||
* // instanceof goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* @see goog.html.SafeHtml#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeHtml.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a SafeHtml, use
|
||||
* {@code goog.html.SafeHtml.unwrap}.
|
||||
*
|
||||
* @see goog.html.SafeHtml#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeHtml.prototype.toString = function() {
|
||||
return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +
|
||||
'}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a SafeHtml
|
||||
* object, and returns its value.
|
||||
* @param {!goog.html.SafeHtml} safeHtml The object to extract from.
|
||||
* @return {string} The SafeHtml object's contained string, unless the run-time
|
||||
* type check fails. In that case, {@code unwrap} returns an innocuous
|
||||
* string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.SafeHtml.unwrap = function(safeHtml) {
|
||||
// Perform additional run-time type-checking to ensure that safeHtml is indeed
|
||||
// an instance of the expected type. This provides some additional protection
|
||||
// against security bugs due to application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (safeHtml instanceof goog.html.SafeHtml &&
|
||||
safeHtml.constructor === goog.html.SafeHtml &&
|
||||
safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail('expected object of type SafeHtml, got \'' +
|
||||
safeHtml + '\'');
|
||||
return 'type_error:SafeHtml';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Shorthand for union of types that can sensibly be converted to strings
|
||||
* or might already be SafeHtml (as SafeHtml is a goog.string.TypedString).
|
||||
* @private
|
||||
* @typedef {string|number|boolean|!goog.string.TypedString|
|
||||
* !goog.i18n.bidi.DirectionalString}
|
||||
*/
|
||||
goog.html.SafeHtml.TextOrHtml_;
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML-escaped text as a SafeHtml object.
|
||||
*
|
||||
* If text is of a type that implements
|
||||
* {@code goog.i18n.bidi.DirectionalString}, the directionality of the new
|
||||
* {@code SafeHtml} object is set to {@code text}'s directionality, if known.
|
||||
* Otherwise, the directionality of the resulting SafeHtml is unknown (i.e.,
|
||||
* {@code null}).
|
||||
*
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
|
||||
* the parameter is of type SafeHtml it is returned directly (no escaping
|
||||
* is done).
|
||||
* @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
|
||||
*/
|
||||
goog.html.SafeHtml.htmlEscape = function(textOrHtml) {
|
||||
if (textOrHtml instanceof goog.html.SafeHtml) {
|
||||
return textOrHtml;
|
||||
}
|
||||
var dir = null;
|
||||
if (textOrHtml.implementsGoogI18nBidiDirectionalString) {
|
||||
dir = textOrHtml.getDirection();
|
||||
}
|
||||
var textAsString;
|
||||
if (textOrHtml.implementsGoogStringTypedString) {
|
||||
textAsString = textOrHtml.getTypedStringValue();
|
||||
} else {
|
||||
textAsString = String(textOrHtml);
|
||||
}
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
goog.string.htmlEscape(textAsString), dir);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML-escaped text as a SafeHtml object, with newlines changed to
|
||||
* <br>.
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
|
||||
* the parameter is of type SafeHtml it is returned directly (no escaping
|
||||
* is done).
|
||||
* @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
|
||||
*/
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) {
|
||||
if (textOrHtml instanceof goog.html.SafeHtml) {
|
||||
return textOrHtml;
|
||||
}
|
||||
var html = goog.html.SafeHtml.htmlEscape(textOrHtml);
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
goog.string.newLineToBr(goog.html.SafeHtml.unwrap(html)),
|
||||
html.getDirection());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML-escaped text as a SafeHtml object, with newlines changed to
|
||||
* <br> and escaping whitespace to preserve spatial formatting. Character
|
||||
* entity #160 is used to make it safer for XML.
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
|
||||
* the parameter is of type SafeHtml it is returned directly (no escaping
|
||||
* is done).
|
||||
* @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
|
||||
*/
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function(
|
||||
textOrHtml) {
|
||||
if (textOrHtml instanceof goog.html.SafeHtml) {
|
||||
return textOrHtml;
|
||||
}
|
||||
var html = goog.html.SafeHtml.htmlEscape(textOrHtml);
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
goog.string.whitespaceEscape(goog.html.SafeHtml.unwrap(html)),
|
||||
html.getDirection());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Coerces an arbitrary object into a SafeHtml object.
|
||||
*
|
||||
* If {@code textOrHtml} is already of type {@code goog.html.SafeHtml}, the same
|
||||
* object is returned. Otherwise, {@code textOrHtml} is coerced to string, and
|
||||
* HTML-escaped. If {@code textOrHtml} is of a type that implements
|
||||
* {@code goog.i18n.bidi.DirectionalString}, its directionality, if known, is
|
||||
* preserved.
|
||||
*
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to
|
||||
* coerce.
|
||||
* @return {!goog.html.SafeHtml} The resulting SafeHtml object.
|
||||
* @deprecated Use goog.html.SafeHtml.htmlEscape.
|
||||
*/
|
||||
goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape;
|
||||
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/;
|
||||
|
||||
|
||||
/**
|
||||
* Set of attributes containing URL as defined at
|
||||
* http://www.w3.org/TR/html5/index.html#attributes-1.
|
||||
* @private @const {!Object<string,boolean>}
|
||||
*/
|
||||
goog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet('action', 'cite',
|
||||
'data', 'formaction', 'href', 'manifest', 'poster', 'src');
|
||||
|
||||
|
||||
/**
|
||||
* Tags which are unsupported via create(). They might be supported via a
|
||||
* tag-specific create method. These are tags which might require a
|
||||
* TrustedResourceUrl in one of their attributes or a restricted type for
|
||||
* their content.
|
||||
* @private @const {!Object<string,boolean>}
|
||||
*/
|
||||
goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet(
|
||||
'embed', 'iframe', 'link', 'object', 'script', 'style', 'template');
|
||||
|
||||
|
||||
/**
|
||||
* @typedef {string|number|goog.string.TypedString|
|
||||
* goog.html.SafeStyle.PropertyMap}
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeHtml.AttributeValue_;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml content consisting of a tag with optional attributes and
|
||||
* optional content.
|
||||
*
|
||||
* For convenience tag names and attribute names are accepted as regular
|
||||
* strings, instead of goog.string.Const. Nevertheless, you should not pass
|
||||
* user-controlled values to these parameters. Note that these parameters are
|
||||
* syntactically validated at runtime, and invalid values will result in
|
||||
* an exception.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* goog.html.SafeHtml.create('br');
|
||||
* goog.html.SafeHtml.create('div', {'class': 'a'});
|
||||
* goog.html.SafeHtml.create('p', {}, 'a');
|
||||
* goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br'));
|
||||
*
|
||||
* goog.html.SafeHtml.create('span', {
|
||||
* 'style': {'margin': '0'}
|
||||
* });
|
||||
*
|
||||
* To guarantee SafeHtml's type contract is upheld there are restrictions on
|
||||
* attribute values and tag names.
|
||||
*
|
||||
* - For attributes which contain script code (on*), a goog.string.Const is
|
||||
* required.
|
||||
* - For attributes which contain style (style), a goog.html.SafeStyle or a
|
||||
* goog.html.SafeStyle.PropertyMap is required.
|
||||
* - For attributes which are interpreted as URLs (e.g. src, href) a
|
||||
* goog.html.SafeUrl or goog.string.Const is required.
|
||||
* - For tags which can load code, more specific goog.html.SafeHtml.create*()
|
||||
* functions must be used. Tags which can load code and are not supported by
|
||||
* this function are embed, iframe, link, object, script, style, and template.
|
||||
*
|
||||
* @param {string} tagName The name of the tag. Only tag names consisting of
|
||||
* [a-zA-Z0-9-] are allowed. Tag names documented above are disallowed.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Mapping from attribute names to their values. Only
|
||||
* attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
|
||||
* undefined causes the attribute to be omitted.
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to
|
||||
* HTML-escape and put inside the tag. This must be empty for void tags
|
||||
* like <br>. Array elements are concatenated.
|
||||
* @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
|
||||
* @throws {Error} If invalid tag name, attribute name, or attribute value is
|
||||
* provided.
|
||||
* @throws {goog.asserts.AssertionError} If content for void tag is provided.
|
||||
*/
|
||||
goog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) {
|
||||
if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) {
|
||||
throw Error('Invalid tag name <' + tagName + '>.');
|
||||
}
|
||||
if (tagName.toLowerCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) {
|
||||
throw Error('Tag name <' + tagName + '> is not allowed for SafeHtml.');
|
||||
}
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
tagName, opt_attributes, opt_content);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml representing an iframe tag.
|
||||
*
|
||||
* By default the sandbox attribute is set to an empty value, which is the most
|
||||
* secure option, as it confers the iframe the least privileges. If this
|
||||
* is too restrictive then granting individual privileges is the preferable
|
||||
* option. Unsetting the attribute entirely is the least secure option and
|
||||
* should never be done unless it's stricly necessary.
|
||||
*
|
||||
* @param {goog.html.TrustedResourceUrl=} opt_src The value of the src
|
||||
* attribute. If null or undefined src will not be set.
|
||||
* @param {goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute.
|
||||
* If null or undefined srcdoc will not be set.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Mapping from attribute names to their values. Only
|
||||
* attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
|
||||
* undefined causes the attribute to be omitted.
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to
|
||||
* HTML-escape and put inside the tag. Array elements are concatenated.
|
||||
* @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
|
||||
* @throws {Error} If invalid tag name, attribute name, or attribute value is
|
||||
* provided. If opt_attributes contains the src or srcdoc attributes.
|
||||
*/
|
||||
goog.html.SafeHtml.createIframe = function(
|
||||
opt_src, opt_srcdoc, opt_attributes, opt_content) {
|
||||
var fixedAttributes = {};
|
||||
fixedAttributes['src'] = opt_src || null;
|
||||
fixedAttributes['srcdoc'] = opt_srcdoc || null;
|
||||
var defaultAttributes = {'sandbox': ''};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, defaultAttributes, opt_attributes);
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'iframe', attributes, opt_content);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml representing a style tag. The type attribute is set
|
||||
* to "text/css".
|
||||
* @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}
|
||||
* styleSheet Content to put inside the tag. Array elements are
|
||||
* concatenated.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Mapping from attribute names to their values. Only
|
||||
* attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
|
||||
* undefined causes the attribute to be omitted.
|
||||
* @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
|
||||
* @throws {Error} If invalid attribute name or attribute value is provided. If
|
||||
* opt_attributes contains the type attribute.
|
||||
*/
|
||||
goog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) {
|
||||
var fixedAttributes = {'type': 'text/css'};
|
||||
var defaultAttributes = {};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, defaultAttributes, opt_attributes);
|
||||
|
||||
var content = '';
|
||||
styleSheet = goog.array.concat(styleSheet);
|
||||
for (var i = 0; i < styleSheet.length; i++) {
|
||||
content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]);
|
||||
}
|
||||
// Convert to SafeHtml so that it's not HTML-escaped.
|
||||
var htmlContent = goog.html.SafeHtml
|
||||
.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
content, goog.i18n.bidi.Dir.NEUTRAL);
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'style', attributes, htmlContent);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string} tagName The tag name.
|
||||
* @param {string} name The attribute name.
|
||||
* @param {!goog.html.SafeHtml.AttributeValue_} value The attribute value.
|
||||
* @return {string} A "name=value" string.
|
||||
* @throws {Error} If attribute value is unsafe for the given tag and attribute.
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) {
|
||||
// If it's goog.string.Const, allow any valid attribute name.
|
||||
if (value instanceof goog.string.Const) {
|
||||
value = goog.string.Const.unwrap(value);
|
||||
} else if (name.toLowerCase() == 'style') {
|
||||
value = goog.html.SafeHtml.getStyleValue_(value);
|
||||
} else if (/^on/i.test(name)) {
|
||||
// TODO(jakubvrana): Disallow more attributes with a special meaning.
|
||||
throw Error('Attribute "' + name +
|
||||
'" requires goog.string.Const value, "' + value + '" given.');
|
||||
// URL attributes handled differently accroding to tag.
|
||||
} else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) {
|
||||
if (value instanceof goog.html.TrustedResourceUrl) {
|
||||
value = goog.html.TrustedResourceUrl.unwrap(value);
|
||||
} else if (value instanceof goog.html.SafeUrl) {
|
||||
value = goog.html.SafeUrl.unwrap(value);
|
||||
} else {
|
||||
// TODO(user): Allow strings and sanitize them automatically,
|
||||
// so that it's consistent with accepting a map directly for "style".
|
||||
throw Error('Attribute "' + name + '" on tag "' + tagName +
|
||||
'" requires goog.html.SafeUrl or goog.string.Const value, "' +
|
||||
value + '" given.');
|
||||
}
|
||||
}
|
||||
|
||||
// Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require
|
||||
// HTML-escaping.
|
||||
if (value.implementsGoogStringTypedString) {
|
||||
// Ok to call getTypedStringValue() since there's no reliance on the type
|
||||
// contract for security here.
|
||||
value = value.getTypedStringValue();
|
||||
}
|
||||
|
||||
goog.asserts.assert(goog.isString(value) || goog.isNumber(value),
|
||||
'String or number value expected, got ' +
|
||||
(typeof value) + ' with value: ' + value);
|
||||
return name + '="' + goog.string.htmlEscape(String(value)) + '"';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets value allowed in "style" attribute.
|
||||
* @param {goog.html.SafeHtml.AttributeValue_} value It could be SafeStyle or a
|
||||
* map which will be passed to goog.html.SafeStyle.create.
|
||||
* @return {string} Unwrapped value.
|
||||
* @throws {Error} If string value is given.
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeHtml.getStyleValue_ = function(value) {
|
||||
if (!goog.isObject(value)) {
|
||||
throw Error('The "style" attribute requires goog.html.SafeStyle or map ' +
|
||||
'of style properties, ' + (typeof value) + ' given: ' + value);
|
||||
}
|
||||
if (!(value instanceof goog.html.SafeStyle)) {
|
||||
// Process the property bag into a style object.
|
||||
value = goog.html.SafeStyle.create(value);
|
||||
}
|
||||
return goog.html.SafeStyle.unwrap(value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml content with known directionality consisting of a tag with
|
||||
* optional attributes and optional content.
|
||||
* @param {!goog.i18n.bidi.Dir} dir Directionality.
|
||||
* @param {string} tagName
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content
|
||||
* @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
|
||||
*/
|
||||
goog.html.SafeHtml.createWithDir = function(dir, tagName, opt_attributes,
|
||||
opt_content) {
|
||||
var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content);
|
||||
html.dir_ = dir;
|
||||
return html;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SafeHtml object by concatenating values.
|
||||
* @param {...(!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Values to concatenate.
|
||||
* @return {!goog.html.SafeHtml}
|
||||
*/
|
||||
goog.html.SafeHtml.concat = function(var_args) {
|
||||
var dir = goog.i18n.bidi.Dir.NEUTRAL;
|
||||
var content = '';
|
||||
|
||||
/**
|
||||
* @param {!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>} argument
|
||||
*/
|
||||
var addArgument = function(argument) {
|
||||
if (goog.isArray(argument)) {
|
||||
goog.array.forEach(argument, addArgument);
|
||||
} else {
|
||||
var html = goog.html.SafeHtml.htmlEscape(argument);
|
||||
content += goog.html.SafeHtml.unwrap(html);
|
||||
var htmlDir = html.getDirection();
|
||||
if (dir == goog.i18n.bidi.Dir.NEUTRAL) {
|
||||
dir = htmlDir;
|
||||
} else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) {
|
||||
dir = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
goog.array.forEach(arguments, addArgument);
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
content, dir);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SafeHtml object with known directionality by concatenating the
|
||||
* values.
|
||||
* @param {!goog.i18n.bidi.Dir} dir Directionality.
|
||||
* @param {...(!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Elements of array
|
||||
* arguments would be processed recursively.
|
||||
* @return {!goog.html.SafeHtml}
|
||||
*/
|
||||
goog.html.SafeHtml.concatWithDir = function(dir, var_args) {
|
||||
var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1));
|
||||
html.dir_ = dir;
|
||||
return html;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the SafeHtml type, used to implement additional run-time
|
||||
* type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create SafeHtml instances.
|
||||
*
|
||||
* @param {string} html The string to initialize the SafeHtml object with.
|
||||
* @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be
|
||||
* constructed, or null if unknown.
|
||||
* @return {!goog.html.SafeHtml} The initialized SafeHtml object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function(
|
||||
html, dir) {
|
||||
var safeHtml = new goog.html.SafeHtml();
|
||||
safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html;
|
||||
safeHtml.dir_ = dir;
|
||||
return safeHtml;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Like create() but does not restrict which tags can be constructed.
|
||||
*
|
||||
* @param {string} tagName Tag name. Set or validated by caller.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes
|
||||
* @param {(!goog.html.SafeHtml.TextOrHtml_|
|
||||
* !Array<!goog.html.SafeHtml.TextOrHtml_>)=} opt_content
|
||||
* @return {!goog.html.SafeHtml}
|
||||
* @throws {Error} If invalid or unsafe attribute name or value is provided.
|
||||
* @throws {goog.asserts.AssertionError} If content for void tag is provided.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse =
|
||||
function(tagName, opt_attributes, opt_content) {
|
||||
var dir = null;
|
||||
var result = '<' + tagName;
|
||||
|
||||
if (opt_attributes) {
|
||||
for (var name in opt_attributes) {
|
||||
if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) {
|
||||
throw Error('Invalid attribute name "' + name + '".');
|
||||
}
|
||||
var value = opt_attributes[name];
|
||||
if (!goog.isDefAndNotNull(value)) {
|
||||
continue;
|
||||
}
|
||||
result += ' ' +
|
||||
goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
var content = opt_content;
|
||||
if (!goog.isDef(content)) {
|
||||
content = [];
|
||||
} else if (!goog.isArray(content)) {
|
||||
content = [content];
|
||||
}
|
||||
|
||||
if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) {
|
||||
goog.asserts.assert(!content.length,
|
||||
'Void tag <' + tagName + '> does not allow content.');
|
||||
result += '>';
|
||||
} else {
|
||||
var html = goog.html.SafeHtml.concat(content);
|
||||
result += '>' + goog.html.SafeHtml.unwrap(html) + '</' + tagName + '>';
|
||||
dir = html.getDirection();
|
||||
}
|
||||
|
||||
var dirAttribute = opt_attributes && opt_attributes['dir'];
|
||||
if (dirAttribute) {
|
||||
if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) {
|
||||
// If the tag has the "dir" attribute specified then its direction is
|
||||
// neutral because it can be safely used in any context.
|
||||
dir = goog.i18n.bidi.Dir.NEUTRAL;
|
||||
} else {
|
||||
dir = null;
|
||||
}
|
||||
}
|
||||
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
result, dir);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {!Object<string, string>} fixedAttributes
|
||||
* @param {!Object<string, string>} defaultAttributes
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Optional attributes passed to create*().
|
||||
* @return {!Object<string, goog.html.SafeHtml.AttributeValue_>}
|
||||
* @throws {Error} If opt_attributes contains an attribute with the same name
|
||||
* as an attribute in fixedAttributes.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeHtml.combineAttributes = function(
|
||||
fixedAttributes, defaultAttributes, opt_attributes) {
|
||||
var combinedAttributes = {};
|
||||
var name;
|
||||
|
||||
for (name in fixedAttributes) {
|
||||
goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');
|
||||
combinedAttributes[name] = fixedAttributes[name];
|
||||
}
|
||||
for (name in defaultAttributes) {
|
||||
goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');
|
||||
combinedAttributes[name] = defaultAttributes[name];
|
||||
}
|
||||
|
||||
for (name in opt_attributes) {
|
||||
var nameLower = name.toLowerCase();
|
||||
if (nameLower in fixedAttributes) {
|
||||
throw Error('Cannot override "' + nameLower + '" attribute, got "' +
|
||||
name + '" with value "' + opt_attributes[name] + '"');
|
||||
}
|
||||
if (nameLower in defaultAttributes) {
|
||||
delete combinedAttributes[nameLower];
|
||||
}
|
||||
combinedAttributes[name] = opt_attributes[name];
|
||||
}
|
||||
|
||||
return combinedAttributes;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A SafeHtml instance corresponding to the empty string.
|
||||
* @const {!goog.html.SafeHtml}
|
||||
*/
|
||||
goog.html.SafeHtml.EMPTY =
|
||||
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
'', goog.i18n.bidi.Dir.NEUTRAL);
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2006 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.safeHtmlTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,387 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.SafeHtml and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.safeHtmlTest');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.testing');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.safeHtmlTest');
|
||||
|
||||
|
||||
|
||||
function testSafeHtml() {
|
||||
// TODO(user): Consider using SafeHtmlBuilder instead of newSafeHtmlForTest,
|
||||
// when available.
|
||||
var safeHtml = goog.html.testing.newSafeHtmlForTest('Hello <em>World</em>');
|
||||
assertSameHtml('Hello <em>World</em>', safeHtml);
|
||||
assertEquals('Hello <em>World</em>', goog.html.SafeHtml.unwrap(safeHtml));
|
||||
assertEquals('SafeHtml{Hello <em>World</em>}', String(safeHtml));
|
||||
assertNull(safeHtml.getDirection());
|
||||
|
||||
safeHtml = goog.html.testing.newSafeHtmlForTest(
|
||||
'World <em>Hello</em>', goog.i18n.bidi.Dir.RTL);
|
||||
assertSameHtml('World <em>Hello</em>', safeHtml);
|
||||
assertEquals('World <em>Hello</em>', goog.html.SafeHtml.unwrap(safeHtml));
|
||||
assertEquals('SafeHtml{World <em>Hello</em>}', String(safeHtml));
|
||||
assertEquals(goog.i18n.bidi.Dir.RTL, safeHtml.getDirection());
|
||||
|
||||
// Interface markers are present.
|
||||
assertTrue(safeHtml.implementsGoogStringTypedString);
|
||||
assertTrue(safeHtml.implementsGoogI18nBidiDirectionalString);
|
||||
|
||||
// Pre-defined constant.
|
||||
assertSameHtml('', goog.html.SafeHtml.EMPTY);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.safeHtmlValueWithSecurityContract__googHtmlSecurityPrivate_ =
|
||||
'<script>evil()</script';
|
||||
evil.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.SafeHtml.unwrap(evil);
|
||||
});
|
||||
assertTrue(exception.message.indexOf('expected object of type SafeHtml') > 0);
|
||||
}
|
||||
|
||||
|
||||
function testHtmlEscape() {
|
||||
// goog.html.SafeHtml passes through unchanged.
|
||||
var safeHtmlIn = goog.html.SafeHtml.htmlEscape('<b>in</b>');
|
||||
assertTrue(safeHtmlIn === goog.html.SafeHtml.htmlEscape(safeHtmlIn));
|
||||
|
||||
// Plain strings are escaped.
|
||||
var safeHtml = goog.html.SafeHtml.htmlEscape('Hello <em>"\'&World</em>');
|
||||
assertSameHtml('Hello <em>"'&World</em>', safeHtml);
|
||||
assertEquals('SafeHtml{Hello <em>"'&World</em>}',
|
||||
String(safeHtml));
|
||||
|
||||
// Creating from a SafeUrl escapes and retains the known direction (which is
|
||||
// fixed to RTL for URLs).
|
||||
var safeUrl = goog.html.SafeUrl.fromConstant(
|
||||
goog.string.Const.from('http://example.com/?foo&bar'));
|
||||
var escapedUrl = goog.html.SafeHtml.htmlEscape(safeUrl);
|
||||
assertSameHtml('http://example.com/?foo&bar', escapedUrl);
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR, escapedUrl.getDirection());
|
||||
|
||||
// Creating SafeHtml from a goog.string.Const escapes as well (i.e., the
|
||||
// value is treated like any other string). To create HTML markup from
|
||||
// program literals, SafeHtmlBuilder should be used.
|
||||
assertSameHtml('this & that',
|
||||
goog.html.SafeHtml.htmlEscape(goog.string.Const.from('this & that')));
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreate() {
|
||||
var br = goog.html.SafeHtml.create('br');
|
||||
|
||||
assertSameHtml('<br>', br);
|
||||
|
||||
assertSameHtml('<span title="""></span>',
|
||||
goog.html.SafeHtml.create('span', {'title': '"'}));
|
||||
|
||||
assertSameHtml('<span><</span>',
|
||||
goog.html.SafeHtml.create('span', {}, '<'));
|
||||
|
||||
assertSameHtml('<span><br></span>',
|
||||
goog.html.SafeHtml.create('span', {}, br));
|
||||
|
||||
assertSameHtml('<span></span>', goog.html.SafeHtml.create('span', {}, []));
|
||||
|
||||
assertSameHtml('<span></span>',
|
||||
goog.html.SafeHtml.create('span', {'title': null, 'class': undefined}));
|
||||
|
||||
assertSameHtml('<span>x<br>y</span>',
|
||||
goog.html.SafeHtml.create('span', {}, ['x', br, 'y']));
|
||||
|
||||
assertSameHtml('<table border="0"></table>',
|
||||
goog.html.SafeHtml.create('table', {'border': 0}));
|
||||
|
||||
var onclick = goog.string.Const.from('alert(/"/)');
|
||||
assertSameHtml('<span onclick="alert(/"/)"></span>',
|
||||
goog.html.SafeHtml.create('span', {'onclick': onclick}));
|
||||
|
||||
var href = goog.html.testing.newSafeUrlForTest('?a&b');
|
||||
assertSameHtml('<a href="?a&b"></a>',
|
||||
goog.html.SafeHtml.create('a', {'href': href}));
|
||||
|
||||
var style = goog.html.testing.newSafeStyleForTest('border: /* " */ 0;');
|
||||
assertSameHtml('<hr style="border: /* " */ 0;">',
|
||||
goog.html.SafeHtml.create('hr', {'style': style}));
|
||||
|
||||
assertEquals(goog.i18n.bidi.Dir.NEUTRAL,
|
||||
goog.html.SafeHtml.create('span').getDirection());
|
||||
assertNull(goog.html.SafeHtml.create('span', {'dir': 'x'}).getDirection());
|
||||
assertEquals(goog.i18n.bidi.Dir.NEUTRAL,
|
||||
goog.html.SafeHtml.create('span', {'dir': 'ltr'}, 'a').getDirection());
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('script');
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('br', {}, 'x');
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('img', {'onerror': ''});
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('img', {'OnError': ''});
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('a', {'href': 'javascript:alert(1)'});
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('a href=""');
|
||||
});
|
||||
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('a', {'title="" href': ''});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreate_styleAttribute() {
|
||||
var style = 'color:red;';
|
||||
var expected = '<hr style="' + style + '">';
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('hr', {'style': style});
|
||||
});
|
||||
assertSameHtml(expected, goog.html.SafeHtml.create('hr', {
|
||||
'style': goog.html.SafeStyle.fromConstant(goog.string.Const.from(style))
|
||||
}));
|
||||
assertSameHtml(expected, goog.html.SafeHtml.create('hr', {
|
||||
'style': {'color': 'red'}
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreate_urlAttributes() {
|
||||
// TrustedResourceUrl is allowed.
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted'));
|
||||
assertSameHtml(
|
||||
'<img src="https://google.com/trusted">',
|
||||
goog.html.SafeHtml.create('img', {'src': trustedResourceUrl}));
|
||||
// SafeUrl is allowed.
|
||||
var safeUrl = goog.html.SafeUrl.sanitize('https://google.com/safe');
|
||||
assertSameHtml(
|
||||
'<imG src="https://google.com/safe">',
|
||||
goog.html.SafeHtml.create('imG', {'src': safeUrl}));
|
||||
// Const is allowed.
|
||||
var constUrl = goog.string.Const.from('https://google.com/const');
|
||||
assertSameHtml(
|
||||
'<a href="https://google.com/const"></a>',
|
||||
goog.html.SafeHtml.create('a', {'href': constUrl}));
|
||||
|
||||
// string is not allowed.
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.create('imG', {'src': 'https://google.com'});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreateIframe() {
|
||||
// Setting src and srcdoc.
|
||||
var url = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted<'));
|
||||
assertSameHtml(
|
||||
'<iframe src="https://google.com/trusted<"></iframe>',
|
||||
goog.html.SafeHtml.createIframe(url, null, {'sandbox': null}));
|
||||
var srcdoc = goog.html.SafeHtml.create('br');
|
||||
assertSameHtml(
|
||||
'<iframe srcdoc="<br>"></iframe>',
|
||||
goog.html.SafeHtml.createIframe(null, srcdoc, {'sandbox': null}));
|
||||
|
||||
// sandbox default and overriding it.
|
||||
assertSameHtml(
|
||||
'<iframe sandbox=""></iframe>',
|
||||
goog.html.SafeHtml.createIframe());
|
||||
assertSameHtml(
|
||||
'<iframe Sandbox="allow-same-origin allow-top-navigation"></iframe>',
|
||||
goog.html.SafeHtml.createIframe(
|
||||
null, null, {'Sandbox': 'allow-same-origin allow-top-navigation'}));
|
||||
|
||||
// Cannot override src and srddoc.
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.createIframe(null, null, {'Src': url});
|
||||
});
|
||||
assertThrows(function() {
|
||||
goog.html.SafeHtml.createIframe(null, null, {'Srcdoc': url});
|
||||
});
|
||||
|
||||
// Can set content.
|
||||
assertSameHtml(
|
||||
'<iframe><</iframe>',
|
||||
goog.html.SafeHtml.createIframe(null, null, {'sandbox': null}, '<'));
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreateStyle() {
|
||||
var styleSheet = goog.html.SafeStyleSheet.fromConstant(
|
||||
goog.string.Const.from('P.special { color:"red" ; }'));
|
||||
var styleHtml = goog.html.SafeHtml.createStyle(styleSheet);
|
||||
assertSameHtml(
|
||||
'<style type="text/css">P.special { color:"red" ; }</style>', styleHtml);
|
||||
|
||||
// Two stylesheets.
|
||||
var otherStyleSheet = goog.html.SafeStyleSheet.fromConstant(
|
||||
goog.string.Const.from('P.regular { color:blue ; }'));
|
||||
styleHtml = goog.html.SafeHtml.createStyle([styleSheet, otherStyleSheet]);
|
||||
assertSameHtml(
|
||||
'<style type="text/css">P.special { color:"red" ; }' +
|
||||
'P.regular { color:blue ; }</style>',
|
||||
styleHtml);
|
||||
|
||||
// Set attribute.
|
||||
styleHtml = goog.html.SafeHtml.createStyle(styleSheet, {'id': 'test'});
|
||||
var styleHtmlString = goog.html.SafeHtml.unwrap(styleHtml);
|
||||
assertTrue(styleHtmlString, styleHtmlString.indexOf('id="test"') != -1);
|
||||
assertTrue(styleHtmlString, styleHtmlString.indexOf('type="text/css"') != -1);
|
||||
|
||||
// Set attribute to null.
|
||||
styleHtml = goog.html.SafeHtml.createStyle(
|
||||
goog.html.SafeStyleSheet.EMPTY, {'id': null});
|
||||
assertSameHtml('<style type="text/css"></style>', styleHtml);
|
||||
|
||||
// Set attribute to invalid value.
|
||||
assertThrows(function() {
|
||||
styleHtml = goog.html.SafeHtml.createStyle(
|
||||
goog.html.SafeStyleSheet.EMPTY, {'invalid.': 'cantdothis'});
|
||||
});
|
||||
|
||||
// Cannot override type attribute.
|
||||
assertThrows(function() {
|
||||
styleHtml = goog.html.SafeHtml.createStyle(
|
||||
goog.html.SafeStyleSheet.EMPTY, {'Type': 'cantdothis'});
|
||||
});
|
||||
|
||||
// Directionality.
|
||||
assertEquals(goog.i18n.bidi.Dir.NEUTRAL, styleHtml.getDirection());
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlCreateWithDir() {
|
||||
var ltr = goog.i18n.bidi.Dir.LTR;
|
||||
|
||||
assertEquals(ltr, goog.html.SafeHtml.createWithDir(ltr, 'br').getDirection());
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlConcat() {
|
||||
var br = goog.html.testing.newSafeHtmlForTest('<br>');
|
||||
|
||||
var html = goog.html.SafeHtml.htmlEscape('Hello');
|
||||
assertSameHtml('Hello<br>', goog.html.SafeHtml.concat(html, br));
|
||||
|
||||
assertSameHtml('', goog.html.SafeHtml.concat());
|
||||
assertSameHtml('', goog.html.SafeHtml.concat([]));
|
||||
|
||||
assertSameHtml('a<br>c', goog.html.SafeHtml.concat('a', br, 'c'));
|
||||
assertSameHtml('a<br>c', goog.html.SafeHtml.concat(['a', br, 'c']));
|
||||
assertSameHtml('a<br>c', goog.html.SafeHtml.concat('a', [br, 'c']));
|
||||
assertSameHtml('a<br>c', goog.html.SafeHtml.concat(['a'], br, ['c']));
|
||||
|
||||
var ltr = goog.html.testing.newSafeHtmlForTest('', goog.i18n.bidi.Dir.LTR);
|
||||
var rtl = goog.html.testing.newSafeHtmlForTest('', goog.i18n.bidi.Dir.RTL);
|
||||
var neutral = goog.html.testing.newSafeHtmlForTest('',
|
||||
goog.i18n.bidi.Dir.NEUTRAL);
|
||||
var unknown = goog.html.testing.newSafeHtmlForTest('');
|
||||
assertEquals(goog.i18n.bidi.Dir.NEUTRAL,
|
||||
goog.html.SafeHtml.concat().getDirection());
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR,
|
||||
goog.html.SafeHtml.concat(ltr, ltr).getDirection());
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR,
|
||||
goog.html.SafeHtml.concat(ltr, neutral, ltr).getDirection());
|
||||
assertNull(goog.html.SafeHtml.concat(ltr, unknown).getDirection());
|
||||
assertNull(goog.html.SafeHtml.concat(ltr, rtl).getDirection());
|
||||
assertNull(goog.html.SafeHtml.concat(ltr, [rtl]).getDirection());
|
||||
}
|
||||
|
||||
|
||||
function testHtmlEscapePreservingNewlines() {
|
||||
// goog.html.SafeHtml passes through unchanged.
|
||||
var safeHtmlIn = goog.html.SafeHtml.htmlEscapePreservingNewlines('<b>in</b>');
|
||||
assertTrue(safeHtmlIn ===
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlines(safeHtmlIn));
|
||||
|
||||
assertSameHtml('a<br>c',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlines('a\nc'));
|
||||
assertSameHtml('<<br>',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlines('<\n'));
|
||||
assertSameHtml('<br>',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlines('\r\n'));
|
||||
assertSameHtml('<br>', goog.html.SafeHtml.htmlEscapePreservingNewlines('\r'));
|
||||
assertSameHtml('', goog.html.SafeHtml.htmlEscapePreservingNewlines(''));
|
||||
}
|
||||
|
||||
|
||||
function testHtmlEscapePreservingNewlinesAndSpaces() {
|
||||
// goog.html.SafeHtml passes through unchanged.
|
||||
var safeHtmlIn = goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
|
||||
'<b>in</b>');
|
||||
assertTrue(safeHtmlIn ===
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(safeHtmlIn));
|
||||
|
||||
assertSameHtml('a<br>c',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces('a\nc'));
|
||||
assertSameHtml('<<br>',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces('<\n'));
|
||||
assertSameHtml(
|
||||
'<br>', goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces('\r\n'));
|
||||
assertSameHtml(
|
||||
'<br>', goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces('\r'));
|
||||
assertSameHtml(
|
||||
'', goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(''));
|
||||
|
||||
assertSameHtml('a  b',
|
||||
goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces('a b'));
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlConcatWithDir() {
|
||||
var ltr = goog.i18n.bidi.Dir.LTR;
|
||||
var rtl = goog.i18n.bidi.Dir.RTL;
|
||||
var br = goog.html.testing.newSafeHtmlForTest('<br>');
|
||||
|
||||
assertEquals(ltr, goog.html.SafeHtml.concatWithDir(ltr).getDirection());
|
||||
assertEquals(ltr, goog.html.SafeHtml.concatWithDir(ltr,
|
||||
goog.html.testing.newSafeHtmlForTest('', rtl)).getDirection());
|
||||
|
||||
assertSameHtml('a<br>c', goog.html.SafeHtml.concatWithDir(ltr, 'a', br, 'c'));
|
||||
}
|
||||
|
||||
|
||||
function assertSameHtml(expected, html) {
|
||||
assertEquals(expected, goog.html.SafeHtml.unwrap(html));
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview The SafeScript type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.SafeScript');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A string-like object which represents JavaScript code and that carries the
|
||||
* security type contract that its value, as a string, will not cause execution
|
||||
* of unconstrained attacker controlled code (XSS) when evaluated as JavaScript
|
||||
* in a browser.
|
||||
*
|
||||
* Instances of this type must be created via the factory method
|
||||
* {@code goog.html.SafeScript.fromConstant} and not by invoking its
|
||||
* constructor. The constructor intentionally takes no parameters and the type
|
||||
* is immutable; hence only a default instance corresponding to the empty string
|
||||
* can be obtained via constructor invocation.
|
||||
*
|
||||
* A SafeScript's string representation can safely be interpolated as the
|
||||
* content of a script element within HTML. The SafeScript string should not be
|
||||
* escaped before interpolation.
|
||||
*
|
||||
* Note that the SafeScript might contain text that is attacker-controlled but
|
||||
* that text should have been interpolated with appropriate escaping,
|
||||
* sanitization and/or validation into the right location in the script, such
|
||||
* that it is highly constrained in its effect (for example, it had to match a
|
||||
* set of whitelisted words).
|
||||
*
|
||||
* A SafeScript can be constructed via security-reviewed unchecked
|
||||
* conversions. In this case producers of SafeScript must ensure themselves that
|
||||
* the SafeScript does not contain unsafe script. Note in particular that
|
||||
* {@code <} is dangerous, even when inside JavaScript strings, and so should
|
||||
* always be forbidden or JavaScript escaped in user controlled input. For
|
||||
* example, if {@code </script><script>evil</script>"} were
|
||||
* interpolated inside a JavaScript string, it would break out of the context
|
||||
* of the original script element and {@code evil} would execute. Also note
|
||||
* that within an HTML script (raw text) element, HTML character references,
|
||||
* such as "<" are not allowed. See
|
||||
* http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements.
|
||||
*
|
||||
* @see goog.html.SafeScript#fromConstant
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.SafeScript = function() {
|
||||
/**
|
||||
* The contained value of this SafeScript. The field has a purposely
|
||||
* ugly name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.SafeScript#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeScript.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the SafeScript type, used to implement additional
|
||||
* run-time type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeScript object from a compile-time constant string.
|
||||
*
|
||||
* @param {!goog.string.Const} script A compile-time-constant string from which
|
||||
* to create a SafeScript.
|
||||
* @return {!goog.html.SafeScript} A SafeScript object initialized to
|
||||
* {@code script}.
|
||||
*/
|
||||
goog.html.SafeScript.fromConstant = function(script) {
|
||||
var scriptString = goog.string.Const.unwrap(script);
|
||||
if (scriptString.length === 0) {
|
||||
return goog.html.SafeScript.EMPTY;
|
||||
}
|
||||
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
|
||||
scriptString);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this SafeScript's value as a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code SafeScript}, use {@code goog.html.SafeScript.unwrap} instead of
|
||||
* this method. If in doubt, assume that it's security relevant. In particular,
|
||||
* note that goog.html functions which return a goog.html type do not guarantee
|
||||
* the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
|
||||
* // instanceof goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* @see goog.html.SafeScript#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeScript.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseSafeScriptWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a SafeScript, use
|
||||
* {@code goog.html.SafeScript.unwrap}.
|
||||
*
|
||||
* @see goog.html.SafeScript#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeScript.prototype.toString = function() {
|
||||
return 'SafeScript{' +
|
||||
this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + '}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a
|
||||
* SafeScript object, and returns its value.
|
||||
*
|
||||
* @param {!goog.html.SafeScript} safeScript The object to extract from.
|
||||
* @return {string} The safeScript object's contained string, unless
|
||||
* the run-time type check fails. In that case, {@code unwrap} returns an
|
||||
* innocuous string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.SafeScript.unwrap = function(safeScript) {
|
||||
// Perform additional Run-time type-checking to ensure that
|
||||
// safeScript is indeed an instance of the expected type. This
|
||||
// provides some additional protection against security bugs due to
|
||||
// application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (safeScript instanceof goog.html.SafeScript &&
|
||||
safeScript.constructor === goog.html.SafeScript &&
|
||||
safeScript.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail(
|
||||
'expected object of type SafeScript, got \'' + safeScript + '\'');
|
||||
return 'type_error:SafeScript';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create SafeScript instances.
|
||||
*
|
||||
* @param {string} script The string to initialize the SafeScript object with.
|
||||
* @return {!goog.html.SafeScript} The initialized SafeScript object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse =
|
||||
function(script) {
|
||||
var safeScript = new goog.html.SafeScript();
|
||||
safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script;
|
||||
return safeScript;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A SafeScript instance corresponding to the empty string.
|
||||
* @const {!goog.html.SafeScript}
|
||||
*/
|
||||
goog.html.SafeScript.EMPTY =
|
||||
goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse('');
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.safeScriptTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.SafeScript and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.safeScriptTest');
|
||||
|
||||
goog.require('goog.html.SafeScript');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.safeScriptTest');
|
||||
|
||||
|
||||
function testSafeScript() {
|
||||
var script = 'var string = \'hello\';';
|
||||
var safeScript =
|
||||
goog.html.SafeScript.fromConstant(goog.string.Const.from(script));
|
||||
var extracted = goog.html.SafeScript.unwrap(safeScript);
|
||||
assertEquals(script, extracted);
|
||||
assertEquals(script, safeScript.getTypedStringValue());
|
||||
assertEquals('SafeScript{' + script + '}', String(safeScript));
|
||||
|
||||
// Interface marker is present.
|
||||
assertTrue(safeScript.implementsGoogStringTypedString);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.safeScriptValueWithSecurityContract__googHtmlSecurityPrivate_ =
|
||||
'var string = \'evil\';';
|
||||
evil.SAFE_STYLE_TYPE_MARKER__GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.SafeScript.unwrap(evil);
|
||||
});
|
||||
assertTrue(
|
||||
exception.message.indexOf('expected object of type SafeScript') > 0);
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_allowsEmptyString() {
|
||||
assertEquals(
|
||||
goog.html.SafeScript.EMPTY,
|
||||
goog.html.SafeScript.fromConstant(goog.string.Const.from('')));
|
||||
}
|
||||
|
||||
|
||||
function testEmpty() {
|
||||
assertEquals('', goog.html.SafeScript.unwrap(goog.html.SafeScript.EMPTY));
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview The SafeStyle type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.SafeStyle');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.string');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A string-like object which represents a sequence of CSS declarations
|
||||
* ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})
|
||||
* and that carries the security type contract that its value, as a string,
|
||||
* will not cause untrusted script execution (XSS) when evaluated as CSS in a
|
||||
* browser.
|
||||
*
|
||||
* Instances of this type must be created via the factory methods
|
||||
* ({@code goog.html.SafeStyle.create} or
|
||||
* {@code goog.html.SafeStyle.fromConstant}) and not by invoking its
|
||||
* constructor. The constructor intentionally takes no parameters and the type
|
||||
* is immutable; hence only a default instance corresponding to the empty string
|
||||
* can be obtained via constructor invocation.
|
||||
*
|
||||
* A SafeStyle's string representation ({@link #getSafeStyleString()}) can
|
||||
* safely:
|
||||
* <ul>
|
||||
* <li>Be interpolated as the entire content of a *quoted* HTML style
|
||||
* attribute, or before already existing properties. The SafeStyle string
|
||||
* *must be HTML-attribute-escaped* (where " and ' are escaped) before
|
||||
* interpolation.
|
||||
* <li>Be interpolated as the entire content of a {}-wrapped block within a
|
||||
* stylesheet, or before already existing properties. The SafeStyle string
|
||||
* should not be escaped before interpolation. SafeStyle's contract also
|
||||
* guarantees that the string will not be able to introduce new properties
|
||||
* or elide existing ones.
|
||||
* <li>Be assigned to the style property of a DOM node. The SafeStyle string
|
||||
* should not be escaped before being assigned to the property.
|
||||
* </ul>
|
||||
*
|
||||
* A SafeStyle may never contain literal angle brackets. Otherwise, it could
|
||||
* be unsafe to place a SafeStyle into a <style> tag (where it can't
|
||||
* be HTML escaped). For example, if the SafeStyle containing
|
||||
* "{@code font: 'foo <style/><script>evil</script>'}" were
|
||||
* interpolated within a <style> tag, this would then break out of the
|
||||
* style context into HTML.
|
||||
*
|
||||
* A SafeStyle may contain literal single or double quotes, and as such the
|
||||
* entire style string must be escaped when used in a style attribute (if
|
||||
* this were not the case, the string could contain a matching quote that
|
||||
* would escape from the style attribute).
|
||||
*
|
||||
* Values of this type must be composable, i.e. for any two values
|
||||
* {@code style1} and {@code style2} of this type,
|
||||
* {@code goog.html.SafeStyle.unwrap(style1) +
|
||||
* goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies
|
||||
* the SafeStyle type constraint. This requirement implies that for any value
|
||||
* {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must
|
||||
* not end in a "property value" or "property name" context. For example,
|
||||
* a value of {@code background:url("} or {@code font-} would not satisfy the
|
||||
* SafeStyle contract. This is because concatenating such strings with a
|
||||
* second value that itself does not contain unsafe CSS can result in an
|
||||
* overall string that does. For example, if {@code javascript:evil())"} is
|
||||
* appended to {@code background:url("}, the resulting string may result in
|
||||
* the execution of a malicious script.
|
||||
*
|
||||
* TODO(user): Consider whether we should implement UTF-8 interchange
|
||||
* validity checks and blacklisting of newlines (including Unicode ones) and
|
||||
* other whitespace characters (\t, \f). Document here if so and also update
|
||||
* SafeStyle.fromConstant().
|
||||
*
|
||||
* The following example values comply with this type's contract:
|
||||
* <ul>
|
||||
* <li><pre>width: 1em;</pre>
|
||||
* <li><pre>height:1em;</pre>
|
||||
* <li><pre>width: 1em;height: 1em;</pre>
|
||||
* <li><pre>background:url('http://url');</pre>
|
||||
* </ul>
|
||||
* In addition, the empty string is safe for use in a CSS attribute.
|
||||
*
|
||||
* The following example values do NOT comply with this type's contract:
|
||||
* <ul>
|
||||
* <li><pre>background: red</pre> (missing a trailing semi-colon)
|
||||
* <li><pre>background:</pre> (missing a value and a trailing semi-colon)
|
||||
* <li><pre>1em</pre> (missing an attribute name, which provides context for
|
||||
* the value)
|
||||
* </ul>
|
||||
*
|
||||
* @see goog.html.SafeStyle#create
|
||||
* @see goog.html.SafeStyle#fromConstant
|
||||
* @see http://www.w3.org/TR/css3-syntax/
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.SafeStyle = function() {
|
||||
/**
|
||||
* The contained value of this SafeStyle. The field has a purposely
|
||||
* ugly name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.SafeStyle#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the SafeStyle type, used to implement additional
|
||||
* run-time type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeStyle object from a compile-time constant string.
|
||||
*
|
||||
* {@code style} should be in the format
|
||||
* {@code name: value; [name: value; ...]} and must not have any < or >
|
||||
* characters in it. This is so that SafeStyle's contract is preserved,
|
||||
* allowing the SafeStyle to correctly be interpreted as a sequence of CSS
|
||||
* declarations and without affecting the syntactic structure of any
|
||||
* surrounding CSS and HTML.
|
||||
*
|
||||
* This method performs basic sanity checks on the format of {@code style}
|
||||
* but does not constrain the format of {@code name} and {@code value}, except
|
||||
* for disallowing tag characters.
|
||||
*
|
||||
* @param {!goog.string.Const} style A compile-time-constant string from which
|
||||
* to create a SafeStyle.
|
||||
* @return {!goog.html.SafeStyle} A SafeStyle object initialized to
|
||||
* {@code style}.
|
||||
*/
|
||||
goog.html.SafeStyle.fromConstant = function(style) {
|
||||
var styleString = goog.string.Const.unwrap(style);
|
||||
if (styleString.length === 0) {
|
||||
return goog.html.SafeStyle.EMPTY;
|
||||
}
|
||||
goog.html.SafeStyle.checkStyle_(styleString);
|
||||
goog.asserts.assert(goog.string.endsWith(styleString, ';'),
|
||||
'Last character of style string is not \';\': ' + styleString);
|
||||
goog.asserts.assert(goog.string.contains(styleString, ':'),
|
||||
'Style string must contain at least one \':\', to ' +
|
||||
'specify a "name: value" pair: ' + styleString);
|
||||
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
|
||||
styleString);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the style definition is valid.
|
||||
* @param {string} style
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeStyle.checkStyle_ = function(style) {
|
||||
goog.asserts.assert(!/[<>]/.test(style),
|
||||
'Forbidden characters in style string: ' + style);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this SafeStyle's value as a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of
|
||||
* this method. If in doubt, assume that it's security relevant. In particular,
|
||||
* note that goog.html functions which return a goog.html type do not guarantee
|
||||
* the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
|
||||
* // instanceof goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* @see goog.html.SafeStyle#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeStyle.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a SafeStyle, use
|
||||
* {@code goog.html.SafeStyle.unwrap}.
|
||||
*
|
||||
* @see goog.html.SafeStyle#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeStyle.prototype.toString = function() {
|
||||
return 'SafeStyle{' +
|
||||
this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a
|
||||
* SafeStyle object, and returns its value.
|
||||
*
|
||||
* @param {!goog.html.SafeStyle} safeStyle The object to extract from.
|
||||
* @return {string} The safeStyle object's contained string, unless
|
||||
* the run-time type check fails. In that case, {@code unwrap} returns an
|
||||
* innocuous string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.SafeStyle.unwrap = function(safeStyle) {
|
||||
// Perform additional Run-time type-checking to ensure that
|
||||
// safeStyle is indeed an instance of the expected type. This
|
||||
// provides some additional protection against security bugs due to
|
||||
// application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (safeStyle instanceof goog.html.SafeStyle &&
|
||||
safeStyle.constructor === goog.html.SafeStyle &&
|
||||
safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail(
|
||||
'expected object of type SafeStyle, got \'' + safeStyle + '\'');
|
||||
return 'type_error:SafeStyle';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create SafeStyle instances.
|
||||
*
|
||||
* @param {string} style The string to initialize the SafeStyle object with.
|
||||
* @return {!goog.html.SafeStyle} The initialized SafeStyle object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse =
|
||||
function(style) {
|
||||
var safeStyle = new goog.html.SafeStyle();
|
||||
safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
|
||||
return safeStyle;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A SafeStyle instance corresponding to the empty string.
|
||||
* @const {!goog.html.SafeStyle}
|
||||
*/
|
||||
goog.html.SafeStyle.EMPTY =
|
||||
goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');
|
||||
|
||||
|
||||
/**
|
||||
* The innocuous string generated by goog.html.SafeUrl.create when passed
|
||||
* an unsafe value.
|
||||
* @const {string}
|
||||
*/
|
||||
goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';
|
||||
|
||||
|
||||
/**
|
||||
* Mapping of property names to their values.
|
||||
* @typedef {!Object<string, goog.string.Const|string>}
|
||||
*/
|
||||
goog.html.SafeStyle.PropertyMap;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SafeStyle object from the properties specified in the map.
|
||||
* @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to
|
||||
* their values, for example {'margin': '1px'}. Names must consist of
|
||||
* [-_a-zA-Z0-9]. Values might be strings consisting of [-.%_!# a-zA-Z0-9].
|
||||
* Other values must be wrapped in goog.string.Const. Null value causes
|
||||
* skipping the property.
|
||||
* @return {!goog.html.SafeStyle}
|
||||
* @throws {Error} If invalid name is provided.
|
||||
* @throws {goog.asserts.AssertionError} If invalid value is provided. With
|
||||
* disabled assertions, invalid value is replaced by
|
||||
* goog.html.SafeStyle.INNOCUOUS_STRING.
|
||||
*/
|
||||
goog.html.SafeStyle.create = function(map) {
|
||||
var style = '';
|
||||
for (var name in map) {
|
||||
if (!/^[-_a-zA-Z0-9]+$/.test(name)) {
|
||||
throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name);
|
||||
}
|
||||
var value = map[name];
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
if (value instanceof goog.string.Const) {
|
||||
value = goog.string.Const.unwrap(value);
|
||||
// These characters can be used to change context and we don't want that
|
||||
// even with const values.
|
||||
goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].');
|
||||
} else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) {
|
||||
goog.asserts.fail(
|
||||
'String value allows only [-.%_!# a-zA-Z0-9], got: ' + value);
|
||||
value = goog.html.SafeStyle.INNOCUOUS_STRING;
|
||||
}
|
||||
style += name + ':' + value + ';';
|
||||
}
|
||||
if (!style) {
|
||||
return goog.html.SafeStyle.EMPTY;
|
||||
}
|
||||
goog.html.SafeStyle.checkStyle_(style);
|
||||
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
|
||||
style);
|
||||
};
|
||||
|
||||
|
||||
// Keep in sync with the error string in create().
|
||||
/**
|
||||
* Regular expression for safe values.
|
||||
* @const {!RegExp}
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeStyle.VALUE_RE_ = /^[-.%_!# a-zA-Z0-9]+$/;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SafeStyle object by concatenating the values.
|
||||
* @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args
|
||||
* SafeStyles to concatenate.
|
||||
* @return {!goog.html.SafeStyle}
|
||||
*/
|
||||
goog.html.SafeStyle.concat = function(var_args) {
|
||||
var style = '';
|
||||
|
||||
/**
|
||||
* @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument
|
||||
*/
|
||||
var addArgument = function(argument) {
|
||||
if (goog.isArray(argument)) {
|
||||
goog.array.forEach(argument, addArgument);
|
||||
} else {
|
||||
style += goog.html.SafeStyle.unwrap(argument);
|
||||
}
|
||||
};
|
||||
|
||||
goog.array.forEach(arguments, addArgument);
|
||||
if (!style) {
|
||||
return goog.html.SafeStyle.EMPTY;
|
||||
}
|
||||
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
|
||||
style);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.safeStyleTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,185 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.SafeStyle and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.safeStyleTest');
|
||||
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.safeStyleTest');
|
||||
|
||||
|
||||
function testSafeStyle() {
|
||||
var style = 'width: 1em;height: 1em;';
|
||||
var safeStyle =
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from(style));
|
||||
var extracted = goog.html.SafeStyle.unwrap(safeStyle);
|
||||
assertEquals(style, extracted);
|
||||
assertEquals(style, safeStyle.getTypedStringValue());
|
||||
assertEquals('SafeStyle{' + style + '}', String(safeStyle));
|
||||
|
||||
// Interface marker is present.
|
||||
assertTrue(safeStyle.implementsGoogStringTypedString);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.safeStyleValueWithSecurityContract__googHtmlSecurityPrivate_ =
|
||||
'width: expression(evil);';
|
||||
evil.SAFE_STYLE_TYPE_MARKER__GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.SafeStyle.unwrap(evil);
|
||||
});
|
||||
assertTrue(
|
||||
exception.message.indexOf('expected object of type SafeStyle') > 0);
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_allowsEmptyString() {
|
||||
assertEquals(
|
||||
goog.html.SafeStyle.EMPTY,
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from('')));
|
||||
}
|
||||
|
||||
function testFromConstant_throwsOnForbiddenCharacters() {
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from('width: x<;'));
|
||||
});
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from('width: x>;'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_throwsIfNoFinalSemicolon() {
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from('width: 1em'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_throwsIfNoColon() {
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.fromConstant(goog.string.Const.from('width= 1em;'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testEmpty() {
|
||||
assertEquals('', goog.html.SafeStyle.unwrap(goog.html.SafeStyle.EMPTY));
|
||||
}
|
||||
|
||||
|
||||
function testCreate() {
|
||||
var style = goog.html.SafeStyle.create({
|
||||
'background': goog.string.Const.from('url(i.png)'),
|
||||
'margin': '0'
|
||||
});
|
||||
assertEquals('background:url(i.png);margin:0;',
|
||||
goog.html.SafeStyle.unwrap(style));
|
||||
}
|
||||
|
||||
|
||||
function testCreate_allowsEmpty() {
|
||||
assertEquals(goog.html.SafeStyle.EMPTY, goog.html.SafeStyle.create({}));
|
||||
}
|
||||
|
||||
|
||||
function testCreate_skipsNull() {
|
||||
var style = goog.html.SafeStyle.create({'background': null});
|
||||
assertEquals(goog.html.SafeStyle.EMPTY, style);
|
||||
}
|
||||
|
||||
|
||||
function testCreate_allowsLengths() {
|
||||
var style = goog.html.SafeStyle.create({'padding': '0 1px .2% 3.4em'});
|
||||
assertEquals('padding:0 1px .2% 3.4em;', goog.html.SafeStyle.unwrap(style));
|
||||
}
|
||||
|
||||
|
||||
function testCreate_throwsOnForbiddenCharacters() {
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.create({'<': '0'});
|
||||
});
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.create({'color': goog.string.Const.from('<')});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testCreate_values() {
|
||||
var valids = [
|
||||
'0',
|
||||
'0 0',
|
||||
'1px',
|
||||
'100%',
|
||||
'2.3px',
|
||||
'.1em',
|
||||
'red',
|
||||
'#f00',
|
||||
'red !important'
|
||||
];
|
||||
for (var i = 0; i < valids.length; i++) {
|
||||
var value = valids[i];
|
||||
assertEquals('background:' + value + ';', goog.html.SafeStyle.unwrap(
|
||||
goog.html.SafeStyle.create({'background': value})));
|
||||
}
|
||||
|
||||
var invalids = [
|
||||
'',
|
||||
'expression(alert(1))',
|
||||
'url(i.png)',
|
||||
goog.string.Const.from('red;')
|
||||
];
|
||||
for (var i = 0; i < invalids.length; i++) {
|
||||
var value = invalids[i];
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyle.create({'background': value});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function testConcat() {
|
||||
var width = goog.html.SafeStyle.fromConstant(
|
||||
goog.string.Const.from('width: 1em;'));
|
||||
var margin = goog.html.SafeStyle.create({'margin': '0'});
|
||||
var padding = goog.html.SafeStyle.create({'padding': '0'});
|
||||
|
||||
var style = goog.html.SafeStyle.concat(width, margin);
|
||||
assertEquals('width: 1em;margin:0;', goog.html.SafeStyle.unwrap(style));
|
||||
|
||||
style = goog.html.SafeStyle.concat([width, margin]);
|
||||
assertEquals('width: 1em;margin:0;', goog.html.SafeStyle.unwrap(style));
|
||||
|
||||
style = goog.html.SafeStyle.concat([width], [padding, margin]);
|
||||
assertEquals('width: 1em;padding:0;margin:0;',
|
||||
goog.html.SafeStyle.unwrap(style));
|
||||
}
|
||||
|
||||
|
||||
function testConcat_allowsEmpty() {
|
||||
var empty = goog.html.SafeStyle.EMPTY;
|
||||
assertEquals(empty, goog.html.SafeStyle.concat());
|
||||
assertEquals(empty, goog.html.SafeStyle.concat([]));
|
||||
assertEquals(empty, goog.html.SafeStyle.concat(empty));
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview The SafeStyleSheet type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.SafeStyleSheet');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.string');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A string-like object which represents a CSS style sheet and that carries the
|
||||
* security type contract that its value, as a string, will not cause untrusted
|
||||
* script execution (XSS) when evaluated as CSS in a browser.
|
||||
*
|
||||
* Instances of this type must be created via the factory method
|
||||
* {@code goog.html.SafeStyleSheet.fromConstant} and not by invoking its
|
||||
* constructor. The constructor intentionally takes no parameters and the type
|
||||
* is immutable; hence only a default instance corresponding to the empty string
|
||||
* can be obtained via constructor invocation.
|
||||
*
|
||||
* A SafeStyleSheet's string representation can safely be interpolated as the
|
||||
* content of a style element within HTML. The SafeStyleSheet string should
|
||||
* not be escaped before interpolation.
|
||||
*
|
||||
* Values of this type must be composable, i.e. for any two values
|
||||
* {@code styleSheet1} and {@code styleSheet2} of this type,
|
||||
* {@code goog.html.SafeStyleSheet.unwrap(styleSheet1) +
|
||||
* goog.html.SafeStyleSheet.unwrap(styleSheet2)} must itself be a value that
|
||||
* satisfies the SafeStyleSheet type constraint. This requirement implies that
|
||||
* for any value {@code styleSheet} of this type,
|
||||
* {@code goog.html.SafeStyleSheet.unwrap(styleSheet1)} must end in
|
||||
* "beginning of rule" context.
|
||||
|
||||
* A SafeStyleSheet can be constructed via security-reviewed unchecked
|
||||
* conversions. In this case producers of SafeStyleSheet must ensure themselves
|
||||
* that the SafeStyleSheet does not contain unsafe script. Note in particular
|
||||
* that {@code <} is dangerous, even when inside CSS strings, and so should
|
||||
* always be forbidden or CSS-escaped in user controlled input. For example, if
|
||||
* {@code </style><script>evil</script>"} were interpolated
|
||||
* inside a CSS string, it would break out of the context of the original
|
||||
* style element and {@code evil} would execute. Also note that within an HTML
|
||||
* style (raw text) element, HTML character references, such as
|
||||
* {@code &lt;}, are not allowed. See
|
||||
* http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements
|
||||
* (similar considerations apply to the style element).
|
||||
*
|
||||
* @see goog.html.SafeStyleSheet#fromConstant
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.SafeStyleSheet = function() {
|
||||
/**
|
||||
* The contained value of this SafeStyleSheet. The field has a purposely
|
||||
* ugly name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.SafeStyleSheet#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the SafeStyleSheet type, used to implement additional
|
||||
* run-time type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SafeStyleSheet object by concatenating values.
|
||||
* @param {...(!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>)}
|
||||
* var_args Values to concatenate.
|
||||
* @return {!goog.html.SafeStyleSheet}
|
||||
*/
|
||||
goog.html.SafeStyleSheet.concat = function(var_args) {
|
||||
var result = '';
|
||||
|
||||
/**
|
||||
* @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}
|
||||
* argument
|
||||
*/
|
||||
var addArgument = function(argument) {
|
||||
if (goog.isArray(argument)) {
|
||||
goog.array.forEach(argument, addArgument);
|
||||
} else {
|
||||
result += goog.html.SafeStyleSheet.unwrap(argument);
|
||||
}
|
||||
};
|
||||
|
||||
goog.array.forEach(arguments, addArgument);
|
||||
return goog.html.SafeStyleSheet
|
||||
.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(result);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeStyleSheet object from a compile-time constant string.
|
||||
*
|
||||
* {@code styleSheet} must not have any < characters in it, so that
|
||||
* the syntactic structure of the surrounding HTML is not affected.
|
||||
*
|
||||
* @param {!goog.string.Const} styleSheet A compile-time-constant string from
|
||||
* which to create a SafeStyleSheet.
|
||||
* @return {!goog.html.SafeStyleSheet} A SafeStyleSheet object initialized to
|
||||
* {@code styleSheet}.
|
||||
*/
|
||||
goog.html.SafeStyleSheet.fromConstant = function(styleSheet) {
|
||||
var styleSheetString = goog.string.Const.unwrap(styleSheet);
|
||||
if (styleSheetString.length === 0) {
|
||||
return goog.html.SafeStyleSheet.EMPTY;
|
||||
}
|
||||
// > is a valid character in CSS selectors and there's no strict need to
|
||||
// block it if we already block <.
|
||||
goog.asserts.assert(!goog.string.contains(styleSheetString, '<'),
|
||||
"Forbidden '<' character in style sheet string: " + styleSheetString);
|
||||
return goog.html.SafeStyleSheet.
|
||||
createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheetString);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this SafeStyleSheet's value as a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code SafeStyleSheet}, use {@code goog.html.SafeStyleSheet.unwrap}
|
||||
* instead of this method. If in doubt, assume that it's security relevant. In
|
||||
* particular, note that goog.html functions which return a goog.html type do
|
||||
* not guarantee the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
|
||||
* // instanceof goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* @see goog.html.SafeStyleSheet#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeStyleSheet.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a SafeStyleSheet, use
|
||||
* {@code goog.html.SafeStyleSheet.unwrap}.
|
||||
*
|
||||
* @see goog.html.SafeStyleSheet#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeStyleSheet.prototype.toString = function() {
|
||||
return 'SafeStyleSheet{' +
|
||||
this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + '}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a
|
||||
* SafeStyleSheet object, and returns its value.
|
||||
*
|
||||
* @param {!goog.html.SafeStyleSheet} safeStyleSheet The object to extract from.
|
||||
* @return {string} The safeStyleSheet object's contained string, unless
|
||||
* the run-time type check fails. In that case, {@code unwrap} returns an
|
||||
* innocuous string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.SafeStyleSheet.unwrap = function(safeStyleSheet) {
|
||||
// Perform additional Run-time type-checking to ensure that
|
||||
// safeStyleSheet is indeed an instance of the expected type. This
|
||||
// provides some additional protection against security bugs due to
|
||||
// application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (safeStyleSheet instanceof goog.html.SafeStyleSheet &&
|
||||
safeStyleSheet.constructor === goog.html.SafeStyleSheet &&
|
||||
safeStyleSheet.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail(
|
||||
"expected object of type SafeStyleSheet, got '" + safeStyleSheet +
|
||||
"'");
|
||||
return 'type_error:SafeStyleSheet';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create SafeStyleSheet instances.
|
||||
*
|
||||
* @param {string} styleSheet The string to initialize the SafeStyleSheet
|
||||
* object with.
|
||||
* @return {!goog.html.SafeStyleSheet} The initialized SafeStyleSheet object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse =
|
||||
function(styleSheet) {
|
||||
var safeStyleSheet = new goog.html.SafeStyleSheet();
|
||||
safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ =
|
||||
styleSheet;
|
||||
return safeStyleSheet;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A SafeStyleSheet instance corresponding to the empty string.
|
||||
* @const {!goog.html.SafeStyleSheet}
|
||||
*/
|
||||
goog.html.SafeStyleSheet.EMPTY =
|
||||
goog.html.SafeStyleSheet.
|
||||
createSafeStyleSheetSecurityPrivateDoNotAccessOrElse('');
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.safeStyleSheetTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.SafeStyleSheet and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.safeStyleSheetTest');
|
||||
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.string');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.safeStyleSheetTest');
|
||||
|
||||
|
||||
function testSafeStyleSheet() {
|
||||
var styleSheet = 'P.special { color:red ; }';
|
||||
var safeStyleSheet =
|
||||
goog.html.SafeStyleSheet.fromConstant(goog.string.Const.from(styleSheet));
|
||||
var extracted = goog.html.SafeStyleSheet.unwrap(safeStyleSheet);
|
||||
assertEquals(styleSheet, extracted);
|
||||
assertEquals(styleSheet, safeStyleSheet.getTypedStringValue());
|
||||
assertEquals('SafeStyleSheet{' + styleSheet + '}', String(safeStyleSheet));
|
||||
|
||||
// Interface marker is present.
|
||||
assertTrue(safeStyleSheet.implementsGoogStringTypedString);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.safeStyleSheetValueWithSecurityContract__googHtmlSecurityPrivate_ =
|
||||
'P.special { color:expression(evil) ; }';
|
||||
evil.SAFE_STYLE_TYPE_MARKER__GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.SafeStyleSheet.unwrap(evil);
|
||||
});
|
||||
assertTrue(goog.string.contains(
|
||||
exception.message,
|
||||
'expected object of type SafeStyleSheet'));
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_allowsEmptyString() {
|
||||
assertEquals(
|
||||
goog.html.SafeStyleSheet.EMPTY,
|
||||
goog.html.SafeStyleSheet.fromConstant(goog.string.Const.from('')));
|
||||
}
|
||||
|
||||
|
||||
function testFromConstant_throwsOnLessThanCharacter() {
|
||||
assertThrows(function() {
|
||||
goog.html.SafeStyleSheet.fromConstant(goog.string.Const.from('x<x'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testConcat() {
|
||||
var styleSheet1 = goog.html.SafeStyleSheet.fromConstant(
|
||||
goog.string.Const.from('P.special { color:red ; }'));
|
||||
var styleSheet2 = goog.html.SafeStyleSheet.fromConstant(
|
||||
goog.string.Const.from('P.regular { color:blue ; }'));
|
||||
var expected = 'P.special { color:red ; }P.special { color:red ; }' +
|
||||
'P.regular { color:blue ; }P.regular { color:blue ; }';
|
||||
|
||||
var concatStyleSheet = goog.html.SafeStyleSheet.concat(
|
||||
styleSheet1, [styleSheet1, styleSheet2], styleSheet2);
|
||||
assertEquals(
|
||||
expected, goog.html.SafeStyleSheet.unwrap(concatStyleSheet));
|
||||
|
||||
// Empty.
|
||||
concatStyleSheet = goog.html.SafeStyleSheet.concat();
|
||||
assertEquals('', goog.html.SafeStyleSheet.unwrap(concatStyleSheet));
|
||||
concatStyleSheet = goog.html.SafeStyleSheet.concat([]);
|
||||
assertEquals('', goog.html.SafeStyleSheet.unwrap(concatStyleSheet));
|
||||
}
|
||||
|
||||
|
||||
function testEmpty() {
|
||||
assertEquals(
|
||||
'', goog.html.SafeStyleSheet.unwrap(goog.html.SafeStyleSheet.EMPTY));
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview The SafeUrl type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.SafeUrl');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.i18n.bidi.DirectionalString');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A string that is safe to use in URL context in DOM APIs and HTML documents.
|
||||
*
|
||||
* A SafeUrl is a string-like object that carries the security type contract
|
||||
* that its value as a string will not cause untrusted script execution
|
||||
* when evaluated as a hyperlink URL in a browser.
|
||||
*
|
||||
* Values of this type are guaranteed to be safe to use in URL/hyperlink
|
||||
* contexts, such as, assignment to URL-valued DOM properties, or
|
||||
* interpolation into a HTML template in URL context (e.g., inside a href
|
||||
* attribute), in the sense that the use will not result in a
|
||||
* Cross-Site-Scripting vulnerability.
|
||||
*
|
||||
* Note that, as documented in {@code goog.html.SafeUrl.unwrap}, this type's
|
||||
* contract does not guarantee that instances are safe to interpolate into HTML
|
||||
* without appropriate escaping.
|
||||
*
|
||||
* Note also that this type's contract does not imply any guarantees regarding
|
||||
* the resource the URL refers to. In particular, SafeUrls are <b>not</b>
|
||||
* safe to use in a context where the referred-to resource is interpreted as
|
||||
* trusted code, e.g., as the src of a script tag.
|
||||
*
|
||||
* Instances of this type must be created via the factory methods
|
||||
* ({@code goog.html.SafeUrl.fromConstant}, {@code goog.html.SafeUrl.sanitize}),
|
||||
* etc and not by invoking its constructor. The constructor intentionally
|
||||
* takes no parameters and the type is immutable; hence only a default instance
|
||||
* corresponding to the empty string can be obtained via constructor invocation.
|
||||
*
|
||||
* @see goog.html.SafeUrl#fromConstant
|
||||
* @see goog.html.SafeUrl#from
|
||||
* @see goog.html.SafeUrl#sanitize
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.i18n.bidi.DirectionalString}
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.SafeUrl = function() {
|
||||
/**
|
||||
* The contained value of this SafeUrl. The field has a purposely ugly
|
||||
* name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.SafeUrl#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The innocuous string generated by goog.html.SafeUrl.sanitize when passed
|
||||
* an unsafe URL.
|
||||
*
|
||||
* about:invalid is registered in
|
||||
* http://www.w3.org/TR/css3-values/#about-invalid.
|
||||
* http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to
|
||||
* contain a fragment, which is not to be considered when determining if an
|
||||
* about URL is well-known.
|
||||
*
|
||||
* Using about:invalid seems preferable to using a fixed data URL, since
|
||||
* browsers might choose to not report CSP violations on it, as legitimate
|
||||
* CSS function calls to attr() can result in this URL being produced. It is
|
||||
* also a standard URL which matches exactly the semantics we need:
|
||||
* "The about:invalid URI references a non-existent document with a generic
|
||||
* error condition. It can be used when a URI is necessary, but the default
|
||||
* value shouldn't be resolveable as any type of document".
|
||||
*
|
||||
* @const {string}
|
||||
*/
|
||||
goog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez';
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeUrl.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Returns this SafeUrl's value a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code SafeUrl}, use {@code goog.html.SafeUrl.unwrap} instead of this
|
||||
* method. If in doubt, assume that it's security relevant. In particular, note
|
||||
* that goog.html functions which return a goog.html type do not guarantee that
|
||||
* the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
|
||||
* // goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
|
||||
* behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
|
||||
* be appropriately escaped before embedding in a HTML document. Note that the
|
||||
* required escaping is context-sensitive (e.g. a different escaping is
|
||||
* required for embedding a URL in a style property within a style
|
||||
* attribute, as opposed to embedding in a href attribute).
|
||||
*
|
||||
* @see goog.html.SafeUrl#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeUrl.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Returns this URLs directionality, which is always {@code LTR}.
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeUrl.prototype.getDirection = function() {
|
||||
return goog.i18n.bidi.Dir.LTR;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a SafeUrl, use
|
||||
* {@code goog.html.SafeUrl.unwrap}.
|
||||
*
|
||||
* @see goog.html.SafeUrl#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.SafeUrl.prototype.toString = function() {
|
||||
return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +
|
||||
'}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a SafeUrl
|
||||
* object, and returns its value.
|
||||
*
|
||||
* IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
|
||||
* behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
|
||||
* be appropriately escaped before embedding in a HTML document. Note that the
|
||||
* required escaping is context-sensitive (e.g. a different escaping is
|
||||
* required for embedding a URL in a style property within a style
|
||||
* attribute, as opposed to embedding in a href attribute).
|
||||
*
|
||||
* Note that the returned value does not necessarily correspond to the string
|
||||
* with which the SafeUrl was constructed, since goog.html.SafeUrl.sanitize
|
||||
* will percent-encode many characters.
|
||||
*
|
||||
* @param {!goog.html.SafeUrl} safeUrl The object to extract from.
|
||||
* @return {string} The SafeUrl object's contained string, unless the run-time
|
||||
* type check fails. In that case, {@code unwrap} returns an innocuous
|
||||
* string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.SafeUrl.unwrap = function(safeUrl) {
|
||||
// Perform additional Run-time type-checking to ensure that safeUrl is indeed
|
||||
// an instance of the expected type. This provides some additional protection
|
||||
// against security bugs due to application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (safeUrl instanceof goog.html.SafeUrl &&
|
||||
safeUrl.constructor === goog.html.SafeUrl &&
|
||||
safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail('expected object of type SafeUrl, got \'' +
|
||||
safeUrl + '\'');
|
||||
return 'type_error:SafeUrl';
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeUrl object from a compile-time constant string.
|
||||
*
|
||||
* Compile-time constant strings are inherently program-controlled and hence
|
||||
* trusted.
|
||||
*
|
||||
* @param {!goog.string.Const} url A compile-time-constant string from which to
|
||||
* create a SafeUrl.
|
||||
* @return {!goog.html.SafeUrl} A SafeUrl object initialized to {@code url}.
|
||||
*/
|
||||
goog.html.SafeUrl.fromConstant = function(url) {
|
||||
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
|
||||
goog.string.Const.unwrap(url));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A pattern that recognizes a commonly useful subset of URLs that satisfy
|
||||
* the SafeUrl contract.
|
||||
*
|
||||
* This regular expression matches a subset of URLs that will not cause script
|
||||
* execution if used in URL context within a HTML document. Specifically, this
|
||||
* regular expression matches if (comment from here on and regex copied from
|
||||
* Soy's EscapingConventions):
|
||||
* (1) Either a protocol in a whitelist (http, https, mailto).
|
||||
* (2) or no protocol. A protocol must be followed by a colon. The below
|
||||
* allows that by allowing colons only after one of the characters [/?#].
|
||||
* A colon after a hash (#) must be in the fragment.
|
||||
* Otherwise, a colon after a (?) must be in a query.
|
||||
* Otherwise, a colon after a single solidus (/) must be in a path.
|
||||
* Otherwise, a colon after a double solidus (//) must be in the authority
|
||||
* (before port).
|
||||
*
|
||||
* The pattern disallows &, used in HTML entity declarations before
|
||||
* one of the characters in [/?#]. This disallows HTML entities used in the
|
||||
* protocol name, which should never happen, e.g. "http" for "http".
|
||||
* It also disallows HTML entities in the first path part of a relative path,
|
||||
* e.g. "foo<bar/baz". Our existing escaping functions should not produce
|
||||
* that. More importantly, it disallows masking of a colon,
|
||||
* e.g. "javascript:...".
|
||||
*
|
||||
* @private
|
||||
* @const {!RegExp}
|
||||
*/
|
||||
goog.html.SAFE_URL_PATTERN_ = /^(?:(?:https?|mailto):|[^&:/?#]*(?:[/?#]|$))/i;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeUrl object from {@code url}. If {@code url} is a
|
||||
* goog.html.SafeUrl then it is simply returned. Otherwise the input string is
|
||||
* validated to match a pattern of commonly used safe URLs. The string is
|
||||
* converted to UTF-8 and non-whitelisted characters are percent-encoded. The
|
||||
* string wrapped by the created SafeUrl will thus contain only ASCII printable
|
||||
* characters.
|
||||
*
|
||||
* {@code url} may be a URL with the http, https, or mailto scheme,
|
||||
* or a relative URL (i.e., a URL without a scheme; specifically, a
|
||||
* scheme-relative, absolute-path-relative, or path-relative URL).
|
||||
*
|
||||
* {@code url} is converted to UTF-8 and non-whitelisted characters are
|
||||
* percent-encoded. Whitelisted characters are '%' and, from RFC 3986,
|
||||
* unreserved characters and reserved characters, with the exception of '\'',
|
||||
* '(' and ')'. This ensures the the SafeUrl contains only ASCII-printable
|
||||
* characters and reduces the chance of security bugs were it to be
|
||||
* interpolated into a specific context without the necessary escaping.
|
||||
*
|
||||
* If {@code url} fails validation or does not UTF-16 decode correctly
|
||||
* (JavaScript strings are UTF-16 encoded), this function returns a SafeUrl
|
||||
* object containing an innocuous string, goog.html.SafeUrl.INNOCUOUS_STRING.
|
||||
*
|
||||
* @see http://url.spec.whatwg.org/#concept-relative-url
|
||||
* @param {string|!goog.string.TypedString} url The URL to validate.
|
||||
* @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.
|
||||
*/
|
||||
goog.html.SafeUrl.sanitize = function(url) {
|
||||
if (url instanceof goog.html.SafeUrl) {
|
||||
return url;
|
||||
}
|
||||
else if (url.implementsGoogStringTypedString) {
|
||||
url = url.getTypedStringValue();
|
||||
} else {
|
||||
url = String(url);
|
||||
}
|
||||
if (!goog.html.SAFE_URL_PATTERN_.test(url)) {
|
||||
url = goog.html.SafeUrl.INNOCUOUS_STRING;
|
||||
} else {
|
||||
url = goog.html.SafeUrl.normalize_(url);
|
||||
}
|
||||
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Normalizes {@code url} the UTF-8 encoding of url, using a whitelist of
|
||||
* characters. Whitelisted characters are not percent-encoded.
|
||||
* @param {string} url The URL to normalize.
|
||||
* @return {string} The normalized URL.
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeUrl.normalize_ = function(url) {
|
||||
try {
|
||||
var normalized = encodeURI(url);
|
||||
} catch (e) { // Happens if url contains invalid surrogate sequences.
|
||||
return goog.html.SafeUrl.INNOCUOUS_STRING;
|
||||
}
|
||||
|
||||
return normalized.replace(
|
||||
goog.html.SafeUrl.NORMALIZE_MATCHER_,
|
||||
function(match) {
|
||||
return goog.html.SafeUrl.NORMALIZE_REPLACER_MAP_[match];
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Matches characters and strings which need to be replaced in the string
|
||||
* generated by encodeURI. Specifically:
|
||||
*
|
||||
* - '\'', '(' and ')' are not encoded. They are part of the reserved
|
||||
* characters group in RFC 3986 but only appear in the obsolete mark
|
||||
* production in Appendix D.2 of RFC 3986, so they can be encoded without
|
||||
* changing semantics.
|
||||
* - '[' and ']' are encoded by encodeURI, despite being reserved characters
|
||||
* which can be used to represent IPv6 addresses. So they need to be decoded.
|
||||
* - '%' is encoded by encodeURI. However, encoding '%' characters that are
|
||||
* already part of a valid percent-encoded sequence changes the semantics of a
|
||||
* URL, and hence we need to preserve them. Note that this may allow
|
||||
* non-encoded '%' characters to remain in the URL (i.e., occurrences of '%'
|
||||
* that are not part of a valid percent-encoded sequence, for example,
|
||||
* 'ab%xy').
|
||||
*
|
||||
* @const {!RegExp}
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeUrl.NORMALIZE_MATCHER_ = /[()']|%5B|%5D|%25/g;
|
||||
|
||||
|
||||
/**
|
||||
* Map of replacements to be done in string generated by encodeURI.
|
||||
* @const {!Object<string, string>}
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeUrl.NORMALIZE_REPLACER_MAP_ = {
|
||||
'\'': '%27',
|
||||
'(': '%28',
|
||||
')': '%29',
|
||||
'%5B': '[',
|
||||
'%5D': ']',
|
||||
'%25': '%'
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the SafeUrl type, used to implement additional run-time
|
||||
* type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create SafeUrl instances.
|
||||
*
|
||||
* @param {string} url The string to initialize the SafeUrl object with.
|
||||
* @return {!goog.html.SafeUrl} The initialized SafeUrl object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function(
|
||||
url) {
|
||||
var safeUrl = new goog.html.SafeUrl();
|
||||
safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = url;
|
||||
return safeUrl;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2006 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.safeUrlTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,201 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.SafeUrl and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.safeUrlTest');
|
||||
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.safeUrlTest');
|
||||
|
||||
|
||||
|
||||
function testSafeUrl() {
|
||||
var safeUrl = goog.html.SafeUrl.fromConstant(
|
||||
goog.string.Const.from('javascript:trusted();'));
|
||||
var extracted = goog.html.SafeUrl.unwrap(safeUrl);
|
||||
assertEquals('javascript:trusted();', extracted);
|
||||
assertEquals('javascript:trusted();', goog.html.SafeUrl.unwrap(safeUrl));
|
||||
assertEquals('SafeUrl{javascript:trusted();}', String(safeUrl));
|
||||
|
||||
// URLs are always LTR.
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR, safeUrl.getDirection());
|
||||
|
||||
// Interface markers are present.
|
||||
assertTrue(safeUrl.implementsGoogStringTypedString);
|
||||
assertTrue(safeUrl.implementsGoogI18nBidiDirectionalString);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.safeUrlValueWithSecurityContract_googHtmlSecurityPrivate_ =
|
||||
'<script>evil()</script';
|
||||
evil.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.SafeUrl.unwrap(evil);
|
||||
});
|
||||
assertTrue(exception.message.indexOf('expected object of type SafeUrl') > 0);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Assert that url passes through sanitization unchanged.
|
||||
* @param {string|!goog.string.TypedString} url The URL to sanitize.
|
||||
*/
|
||||
function assertGoodUrl(url) {
|
||||
var expected = url;
|
||||
if (url.implementsGoogStringTypedString) {
|
||||
expected = url.getTypedStringValue();
|
||||
}
|
||||
var safeUrl = goog.html.SafeUrl.sanitize(url);
|
||||
var extracted = goog.html.SafeUrl.unwrap(safeUrl);
|
||||
assertEquals(expected, extracted);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Assert that url fails sanitization.
|
||||
* @param {string|!goog.string.TypedString} url The URL to sanitize.
|
||||
*/
|
||||
function assertBadUrl(url) {
|
||||
assertEquals(
|
||||
goog.html.SafeUrl.INNOCUOUS_STRING,
|
||||
goog.html.SafeUrl.unwrap(
|
||||
goog.html.SafeUrl.sanitize(url)));
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlSanitize_validatesUrl() {
|
||||
// Whitelisted schemes.
|
||||
assertGoodUrl('http://example.com/');
|
||||
assertGoodUrl('https://example.com');
|
||||
assertGoodUrl('mailto:foo@example.com');
|
||||
// Scheme is case-insensitive
|
||||
assertGoodUrl('HTtp://example.com/');
|
||||
// Different URL components go through.
|
||||
assertGoodUrl('https://example.com/path?foo=bar#baz');
|
||||
// Scheme-less URL with authority.
|
||||
assertGoodUrl('//example.com/path');
|
||||
// Absolute path with no authority.
|
||||
assertGoodUrl('/path');
|
||||
assertGoodUrl('/path?foo=bar#baz');
|
||||
// Relative path.
|
||||
assertGoodUrl('path');
|
||||
assertGoodUrl('path?foo=bar#baz');
|
||||
assertGoodUrl('p//ath');
|
||||
assertGoodUrl('p//ath?foo=bar#baz');
|
||||
// Restricted characters ('&', ':', \') after [/?#].
|
||||
assertGoodUrl('/&');
|
||||
assertGoodUrl('?:');
|
||||
|
||||
// .sanitize() works on program constants.
|
||||
assertGoodUrl(goog.string.Const.from('http://example.com/'));
|
||||
|
||||
// Non-whitelisted schemes.
|
||||
assertBadUrl('javascript:evil();');
|
||||
assertBadUrl('javascript:evil();//\nhttp://good.com/');
|
||||
assertBadUrl('data:blah');
|
||||
// Restricted characters before [/?#].
|
||||
assertBadUrl('&');
|
||||
assertBadUrl(':');
|
||||
// '\' is not treated like '/': no restricted characters allowed after it.
|
||||
assertBadUrl('\\:');
|
||||
// Regex anchored to the left: doesn't match on '/:'.
|
||||
assertBadUrl(':/:');
|
||||
// Regex multiline not enabled: first line would match but second one
|
||||
// wouldn't.
|
||||
assertBadUrl('path\n:');
|
||||
|
||||
// .sanitize() does not exempt values known to be program constants.
|
||||
assertBadUrl(goog.string.Const.from('data:blah'));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Asserts that goog.html.SafeUrl.unwrap returns the expected string when the
|
||||
* SafeUrl has been constructed by passing the given url to
|
||||
* goog.html.SafeUrl.sanitize.
|
||||
* @param {string} url The string to pass to goog.html.SafeUrl.sanitize.
|
||||
* @param {string} expected The string representation that
|
||||
* goog.html.SafeUrl.unwrap should return.
|
||||
*/
|
||||
function assertSanitizeEncodesTo(url, expected) {
|
||||
var safeUrl = goog.html.SafeUrl.sanitize(url);
|
||||
var actual = goog.html.SafeUrl.unwrap(safeUrl);
|
||||
assertEquals(
|
||||
'SafeUrl.sanitize().unwrap() doesn\'t return expected ' +
|
||||
'percent-encoded string',
|
||||
expected,
|
||||
actual);
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlSanitize_percentEncodesUrl() {
|
||||
// '%' is preserved.
|
||||
assertSanitizeEncodesTo('%', '%');
|
||||
assertSanitizeEncodesTo('%2F', '%2F');
|
||||
|
||||
// Unreserved characters, RFC 3986.
|
||||
assertSanitizeEncodesTo('aA1-._~', 'aA1-._~');
|
||||
|
||||
// Reserved characters, RFC 3986. Only '\'', '(' and ')' are encoded.
|
||||
assertSanitizeEncodesTo('/:?#[]@!$&\'()*+,;=', '/:?#[]@!$&%27%28%29*+,;=');
|
||||
|
||||
|
||||
// Other ASCII characters, printable and non-printable.
|
||||
assertSanitizeEncodesTo('^"\\`\x00\n\r\x7f', '%5E%22%5C%60%00%0A%0D%7F');
|
||||
|
||||
// Codepoints which UTF-8 encode to 2 bytes.
|
||||
assertSanitizeEncodesTo('\u0080\u07ff', '%C2%80%DF%BF');
|
||||
|
||||
// Highest codepoint which can be UTF-16 encoded using two bytes
|
||||
// (one code unit). Highest codepoint in basic multilingual plane and highest
|
||||
// that JavaScript can represent using \u.
|
||||
assertSanitizeEncodesTo('\uffff', '%EF%BF%BF');
|
||||
|
||||
// Supplementary plane codepoint which UTF-16 and UTF-8 encode to 4 bytes.
|
||||
// Valid surrogate sequence.
|
||||
assertSanitizeEncodesTo('\ud800\udc00', '%F0%90%80%80');
|
||||
|
||||
// Invalid lead/high surrogate.
|
||||
assertSanitizeEncodesTo('\udc00', goog.html.SafeUrl.INNOCUOUS_STRING);
|
||||
|
||||
// Invalid trail/low surrogate.
|
||||
assertSanitizeEncodesTo('\ud800\ud800', goog.html.SafeUrl.INNOCUOUS_STRING);
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlSanitize_idempotentForSafeUrlArgument() {
|
||||
// This goes through percent-encoding.
|
||||
var safeUrl = goog.html.SafeUrl.sanitize('%11"');
|
||||
var safeUrl2 = goog.html.SafeUrl.sanitize(safeUrl);
|
||||
assertEquals(
|
||||
goog.html.SafeUrl.unwrap(safeUrl), goog.html.SafeUrl.unwrap(safeUrl2));
|
||||
|
||||
// This doesn't match the safe prefix, getting converted into an innocuous
|
||||
// string.
|
||||
safeUrl = goog.html.SafeUrl.sanitize('disallowed:foo');
|
||||
safeUrl2 = goog.html.SafeUrl.sanitize(safeUrl);
|
||||
assertEquals(
|
||||
goog.html.SafeUrl.unwrap(safeUrl), goog.html.SafeUrl.unwrap(safeUrl2));
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
|
||||
/**
|
||||
* @fileoverview SafeHtml factory methods for creating object tags for
|
||||
* loading Silverlight files.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.silverlight');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.flash');
|
||||
goog.require('goog.string.Const');
|
||||
|
||||
|
||||
/**
|
||||
* Attributes and param tag name attributes not allowed to be overriden
|
||||
* when calling createObjectForSilverlight().
|
||||
*
|
||||
* While values that should be specified as params are probably not
|
||||
* recognized as attributes, we block them anyway just to be sure.
|
||||
* @const {!Array<string>}
|
||||
* @private
|
||||
*/
|
||||
goog.html.silverlight.FORBIDDEN_ATTRS_AND_PARAMS_ON_SILVERLIGHT_ = [
|
||||
'data', // Always set to a fixed value.
|
||||
'source', // Specifies the URL for the Silverlight file.
|
||||
'type', // Always set to a fixed value.
|
||||
'typemustmatch' // Always set to a fixed value.
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml representing an object tag, for loading Silverlight files.
|
||||
*
|
||||
* The following attributes are set to these fixed values:
|
||||
* - data: data:application/x-silverlight-2,
|
||||
* - type: application/x-silverlight-2
|
||||
* - typemustmatch: "" (the empty string, meaning true for a boolean attribute)
|
||||
*
|
||||
* @param {!goog.html.TrustedResourceUrl} source The value of the source param.
|
||||
* @param {!Object<string, string>=} opt_params Mapping used to generate child
|
||||
* param tags. Each tag has a name and value attribute, as defined in
|
||||
* mapping. Only names consisting of [a-zA-Z0-9-] are allowed. Value of
|
||||
* null or undefined causes the param tag to be omitted.
|
||||
* @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
|
||||
* opt_attributes Mapping from other attribute names to their values. Only
|
||||
* attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
|
||||
* undefined causes the attribute to be omitted.
|
||||
* @return {!goog.html.SafeHtml} The SafeHtml content with the object tag.
|
||||
* @throws {Error} If invalid attribute or param name, or attribute or param
|
||||
* value is provided. Also if opt_attributes or opt_params contains any of
|
||||
* the attributes set to fixed values, documented above, or contains source.
|
||||
*
|
||||
*/
|
||||
goog.html.silverlight.createObject = function(
|
||||
source, opt_params, opt_attributes) {
|
||||
goog.html.flash.verifyKeysNotInMaps(
|
||||
goog.html.silverlight.FORBIDDEN_ATTRS_AND_PARAMS_ON_SILVERLIGHT_,
|
||||
opt_attributes,
|
||||
opt_params);
|
||||
|
||||
// We don't set default for Silverlight's EnableHtmlAccess and
|
||||
// AllowHtmlPopupwindow because their default changes depending on whether
|
||||
// a file loaded from the same domain.
|
||||
var paramTags = goog.html.flash.combineParams(
|
||||
{'source': source}, opt_params);
|
||||
var fixedAttributes = {
|
||||
'data': goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('data:application/x-silverlight-2,')),
|
||||
'type': 'application/x-silverlight-2',
|
||||
'typemustmatch': ''
|
||||
};
|
||||
var attributes = goog.html.SafeHtml.combineAttributes(
|
||||
fixedAttributes, {}, opt_attributes);
|
||||
|
||||
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
|
||||
'object', attributes, paramTags);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html.silverlight</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.silverlightTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2014 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.silverlight.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.silverlightTest');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.silverlight');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.silverlightTest');
|
||||
|
||||
|
||||
function testCreateObjectForSilverlight() {
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from('https://google.com/trusted&'));
|
||||
assertSameHtml(
|
||||
'<object data="data:application/x-silverlight-2," ' +
|
||||
'type="application/x-silverlight-2" typemustmatch="" ' +
|
||||
'class="test<">' +
|
||||
'<param name="source" value="https://google.com/trusted&">' +
|
||||
'<param name="onload" value="onload<">' +
|
||||
'</object>',
|
||||
goog.html.silverlight.createObject(
|
||||
trustedResourceUrl,
|
||||
{'onload': 'onload<'}, {'class': 'test<'}));
|
||||
|
||||
// Cannot override params, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.silverlight.createObject(
|
||||
trustedResourceUrl, {'datA': 'cantdothis'});
|
||||
});
|
||||
|
||||
// Cannot override attributes, case insensitive.
|
||||
assertThrows(function() {
|
||||
goog.html.silverlight.createObject(
|
||||
trustedResourceUrl, {}, {'datA': 'cantdothis'});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function assertSameHtml(expected, html) {
|
||||
assertEquals(expected, goog.html.SafeHtml.unwrap(html));
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Utilities to create arbitrary values of goog.html types for
|
||||
* testing purposes. These utility methods perform no validation, and the
|
||||
* resulting instances may violate type contracts.
|
||||
*
|
||||
* These methods are useful when types are constructed in a manner where using
|
||||
* the production API is too inconvenient. Please do use the production API
|
||||
* whenever possible; there is value in having tests reflect common usage and it
|
||||
* avoids, by design, non-contract complying instances from being created.
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.html.testing');
|
||||
goog.setTestOnly();
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeScript');
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeHtml wrapping the given value. No validation is performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} html The string to wrap into a SafeHtml.
|
||||
* @param {?goog.i18n.bidi.Dir=} opt_dir The optional directionality of the
|
||||
* SafeHtml to be constructed. A null or undefined value signifies an
|
||||
* unknown directionality.
|
||||
* @return {!goog.html.SafeHtml}
|
||||
*/
|
||||
goog.html.testing.newSafeHtmlForTest = function(html, opt_dir) {
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
html, (opt_dir == undefined ? null : opt_dir));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeScript wrapping the given value. No validation is performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} script The string to wrap into a SafeScript.
|
||||
* @return {!goog.html.SafeScript}
|
||||
*/
|
||||
goog.html.testing.newSafeScriptForTest = function(script) {
|
||||
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
|
||||
script);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeStyle wrapping the given value. No validation is performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} style String to wrap into a SafeStyle.
|
||||
* @return {!goog.html.SafeStyle}
|
||||
*/
|
||||
goog.html.testing.newSafeStyleForTest = function(style) {
|
||||
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
|
||||
style);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeStyleSheet wrapping the given value. No validation is
|
||||
* performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} styleSheet String to wrap into a SafeStyleSheet.
|
||||
* @return {!goog.html.SafeStyleSheet}
|
||||
*/
|
||||
goog.html.testing.newSafeStyleSheetForTest = function(styleSheet) {
|
||||
return goog.html.SafeStyleSheet.
|
||||
createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a SafeUrl wrapping the given value. No validation is performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} url String to wrap into a SafeUrl.
|
||||
* @return {!goog.html.SafeUrl}
|
||||
*/
|
||||
goog.html.testing.newSafeUrlForTest = function(url) {
|
||||
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a TrustedResourceUrl wrapping the given value. No validation is
|
||||
* performed.
|
||||
*
|
||||
* This function is for use in tests only and must never be used in production
|
||||
* code.
|
||||
*
|
||||
* @param {string} url String to wrap into a TrustedResourceUrl.
|
||||
* @return {!goog.html.TrustedResourceUrl}
|
||||
*/
|
||||
goog.html.testing.newTrustedResourceUrlForTest = function(url) {
|
||||
return goog.html.TrustedResourceUrl.
|
||||
createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
@@ -0,0 +1,224 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview The TrustedResourceUrl type and its builders.
|
||||
*
|
||||
* TODO(user): Link to document stating type contract.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.TrustedResourceUrl');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.i18n.bidi.DirectionalString');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.string.TypedString');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A URL which is under application control and from which script, CSS, and
|
||||
* other resources that represent executable code, can be fetched.
|
||||
*
|
||||
* Given that the URL can only be constructed from strings under application
|
||||
* control and is used to load resources, bugs resulting in a malformed URL
|
||||
* should not have a security impact and are likely to be easily detectable
|
||||
* during testing. Given the wide number of non-RFC compliant URLs in use,
|
||||
* stricter validation could prevent some applications from being able to use
|
||||
* this type.
|
||||
*
|
||||
* Instances of this type must be created via the factory method,
|
||||
* ({@code goog.html.TrustedResourceUrl.fromConstant}), and not by invoking its
|
||||
* constructor. The constructor intentionally takes no parameters and the type
|
||||
* is immutable; hence only a default instance corresponding to the empty
|
||||
* string can be obtained via constructor invocation.
|
||||
*
|
||||
* @see goog.html.TrustedResourceUrl#fromConstant
|
||||
* @constructor
|
||||
* @final
|
||||
* @struct
|
||||
* @implements {goog.i18n.bidi.DirectionalString}
|
||||
* @implements {goog.string.TypedString}
|
||||
*/
|
||||
goog.html.TrustedResourceUrl = function() {
|
||||
/**
|
||||
* The contained value of this TrustedResourceUrl. The field has a purposely
|
||||
* ugly name to make (non-compiled) code that attempts to directly access this
|
||||
* field stand out.
|
||||
* @private {string}
|
||||
*/
|
||||
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = '';
|
||||
|
||||
/**
|
||||
* A type marker used to implement additional run-time type checking.
|
||||
* @see goog.html.TrustedResourceUrl#unwrap
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
|
||||
goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true;
|
||||
|
||||
|
||||
/**
|
||||
* Returns this TrustedResourceUrl's value as a string.
|
||||
*
|
||||
* IMPORTANT: In code where it is security relevant that an object's type is
|
||||
* indeed {@code TrustedResourceUrl}, use
|
||||
* {@code goog.html.TrustedResourceUrl.unwrap} instead of this method. If in
|
||||
* doubt, assume that it's security relevant. In particular, note that
|
||||
* goog.html functions which return a goog.html type do not guarantee that
|
||||
* the returned instance is of the right type. For example:
|
||||
*
|
||||
* <pre>
|
||||
* var fakeSafeHtml = new String('fake');
|
||||
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
|
||||
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
|
||||
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
|
||||
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
|
||||
* // goog.html.SafeHtml.
|
||||
* </pre>
|
||||
*
|
||||
* @see goog.html.TrustedResourceUrl#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() {
|
||||
return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
* @const
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString =
|
||||
true;
|
||||
|
||||
|
||||
/**
|
||||
* Returns this URLs directionality, which is always {@code LTR}.
|
||||
* @override
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.prototype.getDirection = function() {
|
||||
return goog.i18n.bidi.Dir.LTR;
|
||||
};
|
||||
|
||||
|
||||
if (goog.DEBUG) {
|
||||
/**
|
||||
* Returns a debug string-representation of this value.
|
||||
*
|
||||
* To obtain the actual string value wrapped in a TrustedResourceUrl, use
|
||||
* {@code goog.html.TrustedResourceUrl.unwrap}.
|
||||
*
|
||||
* @see goog.html.TrustedResourceUrl#unwrap
|
||||
* @override
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.prototype.toString = function() {
|
||||
return 'TrustedResourceUrl{' +
|
||||
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}';
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a runtime check that the provided object is indeed a
|
||||
* TrustedResourceUrl object, and returns its value.
|
||||
*
|
||||
* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to
|
||||
* extract from.
|
||||
* @return {string} The trustedResourceUrl object's contained string, unless
|
||||
* the run-time type check fails. In that case, {@code unwrap} returns an
|
||||
* innocuous string, or, if assertions are enabled, throws
|
||||
* {@code goog.asserts.AssertionError}.
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) {
|
||||
// Perform additional Run-time type-checking to ensure that
|
||||
// trustedResourceUrl is indeed an instance of the expected type. This
|
||||
// provides some additional protection against security bugs due to
|
||||
// application code that disables type checks.
|
||||
// Specifically, the following checks are performed:
|
||||
// 1. The object is an instance of the expected type.
|
||||
// 2. The object is not an instance of a subclass.
|
||||
// 3. The object carries a type marker for the expected type. "Faking" an
|
||||
// object requires a reference to the type marker, which has names intended
|
||||
// to stand out in code reviews.
|
||||
if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl &&
|
||||
trustedResourceUrl.constructor === goog.html.TrustedResourceUrl &&
|
||||
trustedResourceUrl
|
||||
.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
|
||||
goog.html.TrustedResourceUrl
|
||||
.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
|
||||
return trustedResourceUrl
|
||||
.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
|
||||
} else {
|
||||
goog.asserts.fail('expected object of type TrustedResourceUrl, got \'' +
|
||||
trustedResourceUrl + '\'');
|
||||
return 'type_error:TrustedResourceUrl';
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a TrustedResourceUrl object from a compile-time constant string.
|
||||
*
|
||||
* Compile-time constant strings are inherently program-controlled and hence
|
||||
* trusted.
|
||||
*
|
||||
* @param {!goog.string.Const} url A compile-time-constant string from which to
|
||||
* create a TrustedResourceUrl.
|
||||
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
|
||||
* initialized to {@code url}.
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.fromConstant = function(url) {
|
||||
return goog.html.TrustedResourceUrl
|
||||
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(
|
||||
goog.string.Const.unwrap(url));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Type marker for the TrustedResourceUrl type, used to implement additional
|
||||
* run-time type checking.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Package-internal utility method to create TrustedResourceUrl instances.
|
||||
*
|
||||
* @param {string} url The string to initialize the TrustedResourceUrl object
|
||||
* with.
|
||||
* @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl
|
||||
* object.
|
||||
* @package
|
||||
*/
|
||||
goog.html.TrustedResourceUrl.
|
||||
createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) {
|
||||
var trustedResourceUrl = new goog.html.TrustedResourceUrl();
|
||||
trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ =
|
||||
url;
|
||||
return trustedResourceUrl;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2006 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.trustedResourceUrlTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.TrustedResourceUrl and its builders.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.trustedResourceUrlTest');
|
||||
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.trustedResourceUrlTest');
|
||||
|
||||
|
||||
function testTrustedResourceUrl() {
|
||||
var url = 'javascript:trusted();';
|
||||
var trustedResourceUrl = goog.html.TrustedResourceUrl.fromConstant(
|
||||
goog.string.Const.from(url));
|
||||
var extracted = goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl);
|
||||
assertEquals(url, extracted);
|
||||
assertEquals(url, trustedResourceUrl.getTypedStringValue());
|
||||
assertEquals(
|
||||
'TrustedResourceUrl{javascript:trusted();}', String(trustedResourceUrl));
|
||||
|
||||
// URLs are always LTR.
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR, trustedResourceUrl.getDirection());
|
||||
|
||||
// Interface markers are present.
|
||||
assertTrue(trustedResourceUrl.implementsGoogStringTypedString);
|
||||
assertTrue(trustedResourceUrl.implementsGoogI18nBidiDirectionalString);
|
||||
}
|
||||
|
||||
|
||||
/** @suppress {checkTypes} */
|
||||
function testUnwrap() {
|
||||
var evil = {};
|
||||
evil.trustedResourceUrlValueWithSecurityContract_googHtmlSecurityPrivate_ =
|
||||
'<script>evil()</script';
|
||||
evil.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
|
||||
|
||||
var exception = assertThrows(function() {
|
||||
goog.html.TrustedResourceUrl.unwrap(evil);
|
||||
});
|
||||
assertTrue(exception.message.indexOf(
|
||||
'expected object of type TrustedResourceUrl') > 0);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unchecked conversions to create values of goog.html types from
|
||||
* plain strings. Use of these functions could potentially result in instances
|
||||
* of goog.html types that violate their type contracts, and hence result in
|
||||
* security vulnerabilties.
|
||||
*
|
||||
* Therefore, all uses of the methods herein must be carefully security
|
||||
* reviewed. Avoid use of the methods in this file whenever possible; instead
|
||||
* prefer to create instances of goog.html types using inherently safe builders
|
||||
* or template systems.
|
||||
*
|
||||
*
|
||||
* @visibility {//closure/goog/html:approved_for_unchecked_conversion}
|
||||
* @visibility {//closure/goog/bin/sizetests:__pkg__}
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.html.uncheckedconversions');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeScript');
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.string');
|
||||
goog.require('goog.string.Const');
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to SafeHtml from a plain string that is
|
||||
* known to satisfy the SafeHtml type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code html} satisfies the SafeHtml type contract in all
|
||||
* possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} html A string that is claimed to adhere to the SafeHtml
|
||||
* contract.
|
||||
* @param {?goog.i18n.bidi.Dir=} opt_dir The optional directionality of the
|
||||
* SafeHtml to be constructed. A null or undefined value signifies an
|
||||
* unknown directionality.
|
||||
* @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml
|
||||
* object.
|
||||
* @suppress {visibility} For access to SafeHtml.create... Note that this
|
||||
* use is appropriate since this method is intended to be "package private"
|
||||
* withing goog.html. DO NOT call SafeHtml.create... from outside this
|
||||
* package; use appropriate wrappers instead.
|
||||
*/
|
||||
goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, html, opt_dir) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
|
||||
html, opt_dir || null);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to SafeScript from a plain string that is
|
||||
* known to satisfy the SafeScript type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code script} satisfies the SafeScript type contract in
|
||||
* all possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} script The string to wrap as a SafeScript.
|
||||
* @return {!goog.html.SafeScript} The value of {@code script}, wrapped in a
|
||||
* SafeScript object.
|
||||
*/
|
||||
goog.html.uncheckedconversions.safeScriptFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, script) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmpty(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
|
||||
script);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to SafeStyle from a plain string that is
|
||||
* known to satisfy the SafeStyle type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code style} satisfies the SafeUrl type contract in all
|
||||
* possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} style The string to wrap as a SafeStyle.
|
||||
* @return {!goog.html.SafeStyle} The value of {@code style}, wrapped in a
|
||||
* SafeStyle object.
|
||||
*/
|
||||
goog.html.uncheckedconversions.safeStyleFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, style) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
|
||||
style);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to SafeStyleSheet from a plain string
|
||||
* that is known to satisfy the SafeStyleSheet type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code styleSheet} satisfies the SafeUrl type contract in
|
||||
* all possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} styleSheet The string to wrap as a SafeStyleSheet.
|
||||
* @return {!goog.html.SafeStyleSheet} The value of {@code styleSheet}, wrapped
|
||||
* in a SafeStyleSheet object.
|
||||
*/
|
||||
goog.html.uncheckedconversions.
|
||||
safeStyleSheetFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, styleSheet) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.SafeStyleSheet.
|
||||
createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to SafeUrl from a plain string that is
|
||||
* known to satisfy the SafeUrl type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code url} satisfies the SafeUrl type contract in all
|
||||
* possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} url The string to wrap as a SafeUrl.
|
||||
* @return {!goog.html.SafeUrl} The value of {@code url}, wrapped in a SafeUrl
|
||||
* object.
|
||||
*/
|
||||
goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, url) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs an "unchecked conversion" to TrustedResourceUrl from a plain string
|
||||
* that is known to satisfy the TrustedResourceUrl type contract.
|
||||
*
|
||||
* IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
|
||||
* that the value of {@code url} satisfies the TrustedResourceUrl type contract
|
||||
* in all possible program states.
|
||||
*
|
||||
*
|
||||
* @param {!goog.string.Const} justification A constant string explaining why
|
||||
* this use of this method is safe. May include a security review ticket
|
||||
* number.
|
||||
* @param {string} url The string to wrap as a TrustedResourceUrl.
|
||||
* @return {!goog.html.TrustedResourceUrl} The value of {@code url}, wrapped in
|
||||
* a TrustedResourceUrl object.
|
||||
*/
|
||||
goog.html.uncheckedconversions.
|
||||
trustedResourceUrlFromStringKnownToSatisfyTypeContract =
|
||||
function(justification, url) {
|
||||
// unwrap() called inside an assert so that justification can be optimized
|
||||
// away in production code.
|
||||
goog.asserts.assertString(goog.string.Const.unwrap(justification),
|
||||
'must provide justification');
|
||||
goog.asserts.assert(
|
||||
!goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
|
||||
'must provide non-empty justification');
|
||||
return goog.html.TrustedResourceUrl.
|
||||
createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.uncheckedconversionsTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,159 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.uncheckedconversions.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.uncheckedconversionsTest');
|
||||
|
||||
goog.require('goog.html.SafeHtml');
|
||||
goog.require('goog.html.SafeScript');
|
||||
goog.require('goog.html.SafeStyle');
|
||||
goog.require('goog.html.SafeStyleSheet');
|
||||
goog.require('goog.html.SafeUrl');
|
||||
goog.require('goog.html.TrustedResourceUrl');
|
||||
goog.require('goog.html.uncheckedconversions');
|
||||
goog.require('goog.i18n.bidi.Dir');
|
||||
goog.require('goog.string.Const');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.uncheckedconversionsTest');
|
||||
|
||||
|
||||
function testSafeHtmlFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var html = '<div>irrelevant</div>';
|
||||
var safeHtml = goog.html.uncheckedconversions.
|
||||
safeHtmlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from('Test'),
|
||||
html,
|
||||
goog.i18n.bidi.Dir.LTR);
|
||||
assertEquals(html, goog.html.SafeHtml.unwrap(safeHtml));
|
||||
assertEquals(goog.i18n.bidi.Dir.LTR, safeHtml.getDirection());
|
||||
}
|
||||
|
||||
|
||||
function testSafeHtmlFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
safeHtmlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'irrelevant');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeScriptFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var script = 'functionCall(\'irrelevant\');';
|
||||
var safeScript = goog.html.uncheckedconversions.
|
||||
safeScriptFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(
|
||||
'Safe because value is constant. Security review: b/7685625.'),
|
||||
script);
|
||||
assertEquals(script, goog.html.SafeScript.unwrap(safeScript));
|
||||
}
|
||||
|
||||
|
||||
function testSafeScriptFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
safeScriptFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'irrelevant');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeStyleFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var style = 'P.special { color:red ; }';
|
||||
var safeStyle = goog.html.uncheckedconversions.
|
||||
safeStyleFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(
|
||||
'Safe because value is constant. Security review: b/7685625.'),
|
||||
style);
|
||||
assertEquals(style, goog.html.SafeStyle.unwrap(safeStyle));
|
||||
}
|
||||
|
||||
|
||||
function testSafeStyleFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
safeStyleFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'irrelevant');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeStyleSheetFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var styleSheet = 'P.special { color:red ; }';
|
||||
var safeStyleSheet = goog.html.uncheckedconversions.
|
||||
safeStyleSheetFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(
|
||||
'Safe because value is constant. Security review: b/7685625.'),
|
||||
styleSheet);
|
||||
assertEquals(styleSheet, goog.html.SafeStyleSheet.unwrap(safeStyleSheet));
|
||||
}
|
||||
|
||||
|
||||
function testSafeStyleSheetFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
safeStyleSheetFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'irrelevant');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var url = 'http://www.irrelevant.com';
|
||||
var safeUrl = goog.html.uncheckedconversions.
|
||||
safeUrlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(
|
||||
'Safe because value is constant. Security review: b/7685625.'),
|
||||
url);
|
||||
assertEquals(url, goog.html.SafeUrl.unwrap(safeUrl));
|
||||
}
|
||||
|
||||
|
||||
function testSafeUrlFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
safeUrlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'http://irrelevant.com');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testTrustedResourceUrlFromStringKnownToSatisfyTypeContract_ok() {
|
||||
var url = 'http://www.irrelevant.com';
|
||||
var trustedResourceUrl = goog.html.uncheckedconversions.
|
||||
trustedResourceUrlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(
|
||||
'Safe because value is constant. Security review: b/7685625.'),
|
||||
url);
|
||||
assertEquals(url, goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl));
|
||||
}
|
||||
|
||||
|
||||
function testTrustedResourceFromStringKnownToSatisfyTypeContract_error() {
|
||||
assertThrows(function() {
|
||||
goog.html.uncheckedconversions.
|
||||
trustedResourceUrlFromStringKnownToSatisfyTypeContract(
|
||||
goog.string.Const.from(''),
|
||||
'http://irrelevant.com');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
|
||||
/**
|
||||
* @fileoverview HTML processing utilities for HTML in string form.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.utils');
|
||||
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* Extracts plain text from HTML.
|
||||
*
|
||||
* This behaves similarly to extracting textContent from a hypothetical DOM
|
||||
* element containing the specified HTML. Block-level elements such as div are
|
||||
* surrounded with whitespace, but inline elements are not. Span is treated as
|
||||
* a block level element because it is often used as a container. Breaking
|
||||
* spaces are compressed and trimmed.
|
||||
*
|
||||
* @param {string} value The input HTML to have tags removed.
|
||||
* @return {string} The plain text of value without tags, HTML comments, or
|
||||
* other non-text content. Does NOT return safe HTML!
|
||||
*/
|
||||
goog.html.utils.stripHtmlTags = function(value) {
|
||||
// TODO(user): Make a version that extracts text attributes such as alt.
|
||||
return goog.string.unescapeEntities(goog.string.trim(value.replace(
|
||||
goog.html.utils.HTML_TAG_REGEX_, function(fullMatch, tagName) {
|
||||
return goog.html.utils.INLINE_HTML_TAG_REGEX_.test(tagName) ? '' : ' ';
|
||||
}).
|
||||
replace(/[\t\n ]+/g, ' ')));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Matches all tags that do not require extra space.
|
||||
*
|
||||
* @const
|
||||
* @private {RegExp}
|
||||
*/
|
||||
goog.html.utils.INLINE_HTML_TAG_REGEX_ =
|
||||
/^(?:abbr|acronym|address|b|em|i|small|strong|su[bp]|u)$/i;
|
||||
|
||||
|
||||
/**
|
||||
* Matches all tags, HTML comments, and DOCTYPEs in tag soup HTML.
|
||||
* By removing these, and replacing any '<' or '>' characters with
|
||||
* entities we guarantee that the result can be embedded into
|
||||
* an attribute without introducing a tag boundary.
|
||||
*
|
||||
* @private {RegExp}
|
||||
* @const
|
||||
*/
|
||||
goog.html.utils.HTML_TAG_REGEX_ = /<[!\/]?([a-z0-9]+)([\/ ][^>]*)?>/gi;
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<!--
|
||||
Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
|
||||
Use of this source code is governed by the Apache License, Version 2.0.
|
||||
See the COPYING file for details.
|
||||
-->
|
||||
<head>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<title>Closure Unit Tests - goog.html.utils</title>
|
||||
<script src="../base.js"></script>
|
||||
<script>
|
||||
goog.require('goog.html.UtilsTest');
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,122 @@
|
||||
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
/**
|
||||
* @fileoverview Unit tests for goog.html.util.
|
||||
*/
|
||||
|
||||
goog.provide('goog.html.UtilsTest');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.dom.TagName');
|
||||
goog.require('goog.html.utils');
|
||||
goog.require('goog.object');
|
||||
goog.require('goog.testing.jsunit');
|
||||
|
||||
goog.setTestOnly('goog.html.UtilsTest');
|
||||
|
||||
|
||||
var FAILURE_MESSAGE = 'Failed to strip all HTML.';
|
||||
var STRIP = 'Hello world!';
|
||||
var result;
|
||||
|
||||
|
||||
function tearDown() {
|
||||
result = null;
|
||||
}
|
||||
|
||||
|
||||
function testStripAllHtmlTagsSingle() {
|
||||
goog.object.forEach(goog.dom.TagName, function(tag) {
|
||||
result = goog.html.utils.stripHtmlTags(makeHtml_(tag, STRIP));
|
||||
assertEquals(FAILURE_MESSAGE, STRIP, result);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testStripAllHtmlTagsAttribute() {
|
||||
goog.object.forEach(goog.dom.TagName, function(tag) {
|
||||
result = goog.html.utils.stripHtmlTags(makeHtml_(tag, STRIP, 1, 0, 'a'));
|
||||
assertEquals(FAILURE_MESSAGE, STRIP, result);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function testStripAllHtmlTagsDouble() {
|
||||
var tag1 = goog.dom.TagName.B;
|
||||
var tag2 = goog.dom.TagName.DIV;
|
||||
result = goog.html.utils.stripHtmlTags(makeHtml_(tag1, STRIP, 2));
|
||||
assertEquals(FAILURE_MESSAGE, STRIP + STRIP, result);
|
||||
result = goog.html.utils.stripHtmlTags(makeHtml_(tag2, STRIP, 2));
|
||||
assertEquals(FAILURE_MESSAGE, STRIP + ' ' + STRIP, result);
|
||||
}
|
||||
|
||||
|
||||
function testComplex() {
|
||||
var html = '<h1 id=\"life\">Life at Google</h1>' +
|
||||
'<p>Read and interact with the information below to learn about ' +
|
||||
'life at <u>Google</u>.</p>' +
|
||||
'<h2 id=\"food\">Food at Google</h2>' +
|
||||
'<p>Google has <em>the best food in the world</em>.</p>' +
|
||||
'<h2 id=\"transportation\">Transportation at Google</h2>' +
|
||||
'<p>Google provides <i>free transportation</i>.</p>' +
|
||||
// Some text with symbols to make sure that it does not get stripped
|
||||
'<3i><x>\n-10<x<10 3cat < 3dog &<>"';
|
||||
result = goog.html.utils.stripHtmlTags(html);
|
||||
var expected = 'Life at Google ' +
|
||||
'Read and interact with the information below to learn about ' +
|
||||
'life at Google. ' +
|
||||
'Food at Google ' +
|
||||
'Google has the best food in the world. ' +
|
||||
'Transportation at Google ' +
|
||||
'Google provides free transportation. ' +
|
||||
'-10<x<10 3cat < 3dog &<>\"';
|
||||
assertEquals(FAILURE_MESSAGE, expected, result);
|
||||
}
|
||||
|
||||
|
||||
function testInteresting() {
|
||||
result = goog.html.utils.stripHtmlTags(
|
||||
'<img/src="bogus"onerror=alert(13) style="display:none">');
|
||||
assertEquals(FAILURE_MESSAGE, '', result);
|
||||
result = goog.html.utils.stripHtmlTags(
|
||||
'<img o\'reilly blob src=bogus onerror=alert(1337)>');
|
||||
assertEquals(FAILURE_MESSAGE, '', result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Constructs the HTML of an element from the given tag and content.
|
||||
* @param {goog.dom.TagName} tag The HTML tagName for the element.
|
||||
* @param {string} content The content.
|
||||
* @param {number=} opt_copies Optional number of copies to make.
|
||||
* @param {number=} opt_tabIndex Optional tabIndex to give the element.
|
||||
* @param {string=} opt_id Optional id to give the element.
|
||||
* @return {string} The HTML of an element from the given tag and content.
|
||||
*/
|
||||
function makeHtml_(tag, content, opt_copies, opt_tabIndex, opt_id) {
|
||||
var html = ['<' + tag, '>' + content + '</' + tag + '>'];
|
||||
if (goog.isNumber(opt_tabIndex)) {
|
||||
goog.array.insertAt(html, ' tabIndex=\"' + opt_tabIndex + '\"', 1);
|
||||
}
|
||||
if (goog.isString(opt_id)) {
|
||||
goog.array.insertAt(html, ' id=\"' + opt_id + '\"', 1);
|
||||
}
|
||||
html = html.join('');
|
||||
var array = [];
|
||||
for (var i = 0, length = opt_copies || 1; i < length; i++) {
|
||||
array[i] = html;
|
||||
}
|
||||
return array.join('');
|
||||
}
|
||||
Reference in New Issue
Block a user