Moved web root into root of project; this makes deployment easier.

Also deleted 'docs', which is now redundant.
This commit is contained in:
Simon Brooke 2020-02-27 14:18:29 +00:00
parent a5204c66b9
commit 743d8a1740
No known key found for this signature in database
GPG key ID: A7A4F18D1D4DF987
1592 changed files with 53626 additions and 139250 deletions

View file

@ -0,0 +1,195 @@
// 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 Transitional utilities to unsafely trust random strings as
* goog.html types. Intended for temporary use when upgrading a library that
* used to accept plain strings to use safe types, but where it's not
* practical to transitively update callers.
*
* IMPORTANT: No new code should use the conversion functions in this file,
* they are intended for refactoring old code to use goog.html types. New code
* should construct goog.html types via their APIs, template systems or
* sanitizers. If thats not possible it should use
* goog.html.uncheckedconversions and undergo security review.
*
* 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 will 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.
*
* There are only three valid uses of legacyconversions:
*
* 1. Introducing a goog.html version of a function which currently consumes
* string and passes that string to a DOM API which can execute script - and
* hence cause XSS - like innerHTML. For example, Dialog might expose a
* setContent method which takes a string and sets the innerHTML property of
* an element with it. In this case a setSafeHtmlContent function could be
* added, consuming goog.html.SafeHtml instead of string, and using
* goog.dom.safe.setInnerHtml instead of directly setting innerHTML.
* setContent could then internally use legacyconversions to create a SafeHtml
* from string and pass the SafeHtml to setSafeHtmlContent. In this scenario
* remember to document the use of legacyconversions in the modified setContent
* and consider deprecating it as well.
*
* 2. Automated refactoring of application code which handles HTML as string
* but needs to call a function which only takes goog.html types. For example,
* in the Dialog scenario from (1) an alternative option would be to refactor
* setContent to accept goog.html.SafeHtml instead of string and then refactor
* all current callers to use legacyconversions to pass SafeHtml. This is
* generally preferable to (1) because it keeps the library clean of
* legacyconversions, and makes code sites in application code that are
* potentially vulnerable to XSS more apparent.
*
* 3. Old code which needs to call APIs which consume goog.html types and for
* which it is prohibitively expensive to refactor to use goog.html types.
* Generally, this is code where safety from XSS is either hopeless or
* unimportant.
*
* @visibility {//closure/goog/html:approved_for_legacy_conversion}
* @visibility {//closure/goog/bin/sizetests:__pkg__}
*/
goog.provide('goog.html.legacyconversions');
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');
/**
* Performs an "unchecked conversion" from string to SafeHtml for legacy API
* purposes.
*
* Please read fileoverview documentation before using.
*
* @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.reportCallback_();
return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
html, null /* dir */);
};
/**
* Performs an "unchecked conversion" from string to SafeScript for legacy API
* purposes.
*
* Please read fileoverview documentation before using.
*
* @param {string} script A string to be converted to SafeScript.
* @return {!goog.html.SafeScript} The value of script, wrapped in a SafeScript
* object.
*/
goog.html.legacyconversions.safeScriptFromString = function(script) {
goog.html.legacyconversions.reportCallback_();
return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
script);
};
/**
* Performs an "unchecked conversion" from string to SafeStyle for legacy API
* purposes.
*
* Please read fileoverview documentation before using.
*
* @param {string} style A string to be converted to SafeStyle.
* @return {!goog.html.SafeStyle} The value of style, wrapped in a SafeStyle
* object.
*/
goog.html.legacyconversions.safeStyleFromString = function(style) {
goog.html.legacyconversions.reportCallback_();
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
style);
};
/**
* Performs an "unchecked conversion" from string to SafeStyleSheet for legacy
* API purposes.
*
* Please read fileoverview documentation before using.
*
* @param {string} styleSheet A string to be converted to SafeStyleSheet.
* @return {!goog.html.SafeStyleSheet} The value of style sheet, wrapped in
* a SafeStyleSheet object.
*/
goog.html.legacyconversions.safeStyleSheetFromString = function(styleSheet) {
goog.html.legacyconversions.reportCallback_();
return goog.html.SafeStyleSheet
.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
};
/**
* Performs an "unchecked conversion" from string to SafeUrl for legacy API
* purposes.
*
* Please read fileoverview documentation before using.
*
* @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.reportCallback_();
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};
/**
* Performs an "unchecked conversion" from string to TrustedResourceUrl for
* legacy API purposes.
*
* Please read fileoverview documentation before using.
*
* @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.reportCallback_();
return goog.html.TrustedResourceUrl
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(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;
};

View file

@ -0,0 +1,994 @@
// 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(xtof): Link to document stating type contract.
*/
goog.provide('goog.html.SafeHtml');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom.TagName');
goog.require('goog.dom.tags');
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.i18n.bidi.Dir');
goog.require('goog.i18n.bidi.DirectionalString');
goog.require('goog.labs.userAgent.browser');
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 {!Object}
* @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 as 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 + '\' of type ' + goog.typeOf(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
* &lt;br&gt;.
* @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
* &lt;br&gt; 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(
goog.dom.TagName.APPLET, goog.dom.TagName.BASE, goog.dom.TagName.EMBED,
goog.dom.TagName.IFRAME, goog.dom.TagName.LINK, goog.dom.TagName.MATH,
goog.dom.TagName.META, goog.dom.TagName.OBJECT, goog.dom.TagName.SCRIPT,
goog.dom.TagName.STYLE, goog.dom.TagName.SVG, goog.dom.TagName.TEMPLATE);
/**
* @typedef {string|number|goog.string.TypedString|
* goog.html.SafeStyle.PropertyMap|undefined}
*/
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, goog.string.Const or string is required. If a string
* is passed, it will be sanitized with SafeUrl.sanitize().
* - For tags which can load code or set security relevant page metadata,
* more specific goog.html.SafeHtml.create*() functions must be used. Tags
* which are not supported by this function are applet, base, embed, iframe,
* link, math, object, script, style, svg, and template.
*
* @param {!goog.dom.TagName|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) {
goog.html.SafeHtml.verifyTagName(String(tagName));
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
String(tagName), opt_attributes, opt_content);
};
/**
* Verifies if the tag name is valid and if it doesn't change the context.
* E.g. STRONG is fine but SCRIPT throws because it changes context. See
* goog.html.SafeHtml.create for an explanation of allowed tags.
* @param {string} tagName
* @throws {Error} If invalid tag name is provided.
* @package
*/
goog.html.SafeHtml.verifyTagName = function(tagName) {
if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) {
throw Error('Invalid tag name <' + tagName + '>.');
}
if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) {
throw Error('Tag name <' + tagName + '> is not allowed for SafeHtml.');
}
};
/**
* Creates a SafeHtml representing an iframe tag.
*
* This by default restricts the iframe as much as possible by setting the
* sandbox attribute to the empty string. If the iframe requires less
* restrictions, set the sandbox attribute as tight as possible, but do not rely
* on the sandbox as a security feature because it is not supported by older
* browsers. If a sandbox is essential to security (e.g. for third-party
* frames), use createSandboxIframe which checks for browser support.
*
* @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox
*
* @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) {
if (opt_src) {
// Check whether this is really TrustedResourceUrl.
goog.html.TrustedResourceUrl.unwrap(opt_src);
}
var fixedAttributes = {};
fixedAttributes['src'] = opt_src || null;
fixedAttributes['srcdoc'] =
opt_srcdoc && goog.html.SafeHtml.unwrap(opt_srcdoc);
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 sandboxed iframe tag.
*
* The sandbox attribute is enforced in its most restrictive mode, an empty
* string. Consequently, the security requirements for the src and srcdoc
* attributes are relaxed compared to SafeHtml.createIframe. This function
* will throw on browsers that do not support the sandbox attribute, as
* determined by SafeHtml.canUseSandboxIframe.
*
* The SafeHtml returned by this function can trigger downloads with no
* user interaction on Chrome (though only a few, further attempts are blocked).
* Firefox and IE will block all downloads from the sandbox.
*
* @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox
* @see https://lists.w3.org/Archives/Public/public-whatwg-archive/2013Feb/0112.html
*
* @param {string|!goog.html.SafeUrl=} opt_src The value of the src
* attribute. If null or undefined src will not be set.
* @param {string=} opt_srcdoc The value of the srcdoc attribute.
* If null or undefined srcdoc will not be set. Will not be sanitized.
* @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, srcdoc or sandbox
* attributes. If browser does not support the sandbox attribute on iframe.
*/
goog.html.SafeHtml.createSandboxIframe = function(
opt_src, opt_srcdoc, opt_attributes, opt_content) {
if (!goog.html.SafeHtml.canUseSandboxIframe()) {
throw new Error('The browser does not support sandboxed iframes.');
}
var fixedAttributes = {};
if (opt_src) {
// Note that sanitize is a no-op on SafeUrl.
fixedAttributes['src'] =
goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(opt_src));
} else {
fixedAttributes['src'] = null;
}
fixedAttributes['srcdoc'] = opt_srcdoc || null;
fixedAttributes['sandbox'] = '';
var attributes =
goog.html.SafeHtml.combineAttributes(fixedAttributes, {}, opt_attributes);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
'iframe', attributes, opt_content);
};
/**
* Checks if the user agent supports sandboxed iframes.
* @return {boolean}
*/
goog.html.SafeHtml.canUseSandboxIframe = function() {
return goog.global['HTMLIFrameElement'] &&
('sandbox' in goog.global['HTMLIFrameElement'].prototype);
};
/**
* Creates a SafeHtml representing a script tag with the src attribute.
* @param {!goog.html.TrustedResourceUrl} src The value of the src
* attribute.
* @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 value is provided. If
* opt_attributes contains the src attribute.
*/
goog.html.SafeHtml.createScriptSrc = function(src, opt_attributes) {
// TODO(mlourenco): The charset attribute should probably be blocked. If
// its value is attacker controlled, the script contains attacker controlled
// sub-strings (even if properly escaped) and the server does not set charset
// then XSS is likely possible.
// https://html.spec.whatwg.org/multipage/scripting.html#dom-script-charset
// Check whether this is really TrustedResourceUrl.
goog.html.TrustedResourceUrl.unwrap(src);
var fixedAttributes = {'src': src};
var defaultAttributes = {};
var attributes = goog.html.SafeHtml.combineAttributes(
fixedAttributes, defaultAttributes, opt_attributes);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
'script', attributes);
};
/**
* Creates a SafeHtml representing a script tag. Does not allow the language,
* src, text or type attributes to be set.
* @param {!goog.html.SafeScript|!Array<!goog.html.SafeScript>}
* script 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 language, src, text or type attribute.
*/
goog.html.SafeHtml.createScript = function(script, opt_attributes) {
for (var attr in opt_attributes) {
var attrLower = attr.toLowerCase();
if (attrLower == 'language' || attrLower == 'src' || attrLower == 'text' ||
attrLower == 'type') {
throw Error('Cannot set "' + attrLower + '" attribute');
}
}
var content = '';
script = goog.array.concat(script);
for (var i = 0; i < script.length; i++) {
content += goog.html.SafeScript.unwrap(script[i]);
}
// Convert to SafeHtml so that it's not HTML-escaped. This is safe because
// as part of its contract, SafeScript should have no dangerous '<'.
var htmlContent =
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
content, goog.i18n.bidi.Dir.NEUTRAL);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
'script', opt_attributes, htmlContent);
};
/**
* 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. This is safe because
// as part of its contract, SafeStyleSheet should have no dangerous '<'.
var htmlContent =
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
content, goog.i18n.bidi.Dir.NEUTRAL);
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
'style', attributes, htmlContent);
};
/**
* Creates a SafeHtml representing a meta refresh tag.
* @param {!goog.html.SafeUrl|string} url Where to redirect. If a string is
* passed, it will be sanitized with SafeUrl.sanitize().
* @param {number=} opt_secs Number of seconds until the page should be
* reloaded. Will be set to 0 if unspecified.
* @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
*/
goog.html.SafeHtml.createMetaRefresh = function(url, opt_secs) {
// Note that sanitize is a no-op on SafeUrl.
var unwrappedUrl = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(url));
if (goog.labs.userAgent.browser.isIE() ||
goog.labs.userAgent.browser.isEdge()) {
// IE/EDGE can't parse the content attribute if the url contains a
// semicolon. We can fix this by adding quotes around the url, but then we
// can't parse quotes in the URL correctly. Also, it seems that IE/EDGE
// did not unescape semicolons in these URLs at some point in the past. We
// take a best-effort approach.
//
// If the URL has semicolons (which may happen in some cases, see
// http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2
// for instance), wrap it in single quotes to protect the semicolons.
// If the URL has semicolons and single quotes, url-encode the single quotes
// as well.
//
// This is imperfect. Notice that both ' and ; are reserved characters in
// URIs, so this could do the wrong thing, but at least it will do the wrong
// thing in only rare cases.
if (goog.string.contains(unwrappedUrl, ';')) {
unwrappedUrl = "'" + unwrappedUrl.replace(/'/g, '%27') + "'";
}
}
var attributes = {
'http-equiv': 'refresh',
'content': (opt_secs || 0) + '; url=' + unwrappedUrl
};
// This function will handle the HTML escaping for attributes.
return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
'meta', attributes);
};
/**
* @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 according 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 if (goog.isString(value)) {
value = goog.html.SafeUrl.sanitize(value).getTypedStringValue();
} else {
throw Error(
'Attribute "' + name + '" on tag "' + tagName +
'" requires goog.html.SafeUrl, goog.string.Const, or string,' +
' 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 {!Object}
* @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) {
return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_(
html, dir);
};
/**
* Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This
* method exists only so that the compiler can dead code eliminate static
* fields (like EMPTY) when they're not accessed.
* @param {string} html
* @param {?goog.i18n.bidi.Dir} dir
* @return {!goog.html.SafeHtml}
* @private
*/
goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
html, dir) {
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html;
this.dir_ = dir;
return this;
};
/**
* 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;
result += goog.html.SafeHtml.stringifyAttributes(tagName, opt_attributes);
var content = opt_content;
if (!goog.isDefAndNotNull(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);
};
/**
* Creates a string with attributes to insert after tagName.
* @param {string} tagName
* @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes
* @return {string} Returns an empty string if there are no attributes, returns
* a string starting with a space otherwise.
* @throws {Error} If attribute value is unsafe for the given tag and attribute.
* @package
*/
goog.html.SafeHtml.stringifyAttributes = function(tagName, opt_attributes) {
var result = '';
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);
}
}
return result;
};
/**
* @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>} 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 HTML doctype: "<!DOCTYPE html>".
* @const {!goog.html.SafeHtml}
*/
goog.html.SafeHtml.DOCTYPE_HTML =
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
'<!DOCTYPE html>', goog.i18n.bidi.Dir.NEUTRAL);
/**
* 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);
/**
* A SafeHtml instance corresponding to the <br> tag.
* @const {!goog.html.SafeHtml}
*/
goog.html.SafeHtml.BR =
goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
'<br>', goog.i18n.bidi.Dir.NEUTRAL);

View file

@ -0,0 +1,234 @@
// 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(xtof): 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 &lt;} is dangerous, even when inside JavaScript strings, and so should
* always be forbidden or JavaScript escaped in user controlled input. For
* example, if {@code &lt;/script&gt;&lt;script&gt;evil&lt;/script&gt;"} 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 "&lt;" 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 {!Object}
* @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 {!Object}
* @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 + '\' of type ' + goog.typeOf(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) {
return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_(
script);
};
/**
* Called from createSafeScriptSecurityPrivateDoNotAccessOrElse(). This
* method exists only so that the compiler can dead code eliminate static
* fields (like EMPTY) when they're not accessed.
* @param {string} script
* @return {!goog.html.SafeScript}
* @private
*/
goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
script) {
this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script;
return this;
};
/**
* A SafeScript instance corresponding to the empty string.
* @const {!goog.html.SafeScript}
*/
goog.html.SafeScript.EMPTY =
goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse('');

View file

@ -0,0 +1,560 @@
// 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(xtof): Link to document stating type contract.
*/
goog.provide('goog.html.SafeStyle');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.html.SafeUrl');
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.
*
* SafeStyle's string representation can safely be:
* <ul>
* <li>Interpolated as the content of a *quoted* HTML style attribute.
* However, the SafeStyle string *must be HTML-attribute-escaped* before
* interpolation.
* <li>Interpolated as the content of a {}-wrapped block within a stylesheet.
* '<' characters in the SafeStyle string *must be CSS-escaped* before
* interpolation. The SafeStyle string is also guaranteed not to be able
* to introduce new properties or elide existing ones.
* <li>Interpolated as the content of a {}-wrapped block within an HTML
* <style> element. '<' characters in the SafeStyle string
* *must be CSS-escaped* before interpolation.
* <li>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 &lt;style&gt; tag (where it can't
* be HTML escaped). For example, if the SafeStyle containing
* "{@code font: 'foo &lt;style/&gt;&lt;script&gt;evil&lt;/script&gt;'}" were
* interpolated within a &lt;style&gt; 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(mlourenco): 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 {!Object}
* @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 {!Object}
* @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 + '\' of type ' + goog.typeOf(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) {
return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style);
};
/**
* Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This
* method exists only so that the compiler can dead code eliminate static
* fields (like EMPTY) when they're not accessed.
* @param {string} style
* @return {!goog.html.SafeStyle}
* @private
*/
goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
style) {
this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
return this;
};
/**
* 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.SafeStyle.create when passed
* an unsafe value.
* @const {string}
*/
goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';
/**
* A single property value.
* @typedef {string|!goog.string.Const|!goog.html.SafeUrl}
*/
goog.html.SafeStyle.PropertyValue;
/**
* Mapping of property names to their values.
* We don't support numbers even though some values might be numbers (e.g.
* line-height or 0 for any length). The reason is that most numeric values need
* units (e.g. '1px') and allowing numbers could cause users forgetting about
* them.
* @typedef {!Object<string, ?goog.html.SafeStyle.PropertyValue|
* ?Array<!goog.html.SafeStyle.PropertyValue>>}
*/
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], where " and ' must be properly balanced. We also
* allow simple functions like rgb() and url() which sanitizes its contents.
* Other values must be wrapped in goog.string.Const. URLs might be passed
* as goog.html.SafeUrl which will be wrapped into url(""). We also support
* array whose elements are joined with ' '. 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 (goog.isArray(value)) {
value = goog.array.map(value, goog.html.SafeStyle.sanitizePropertyValue_)
.join(' ');
} else {
value = goog.html.SafeStyle.sanitizePropertyValue_(value);
}
style += name + ':' + value + ';';
}
if (!style) {
return goog.html.SafeStyle.EMPTY;
}
goog.html.SafeStyle.checkStyle_(style);
return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
style);
};
/**
* Checks and converts value to string.
* @param {!goog.html.SafeStyle.PropertyValue} value
* @return {string}
* @private
*/
goog.html.SafeStyle.sanitizePropertyValue_ = function(value) {
if (value instanceof goog.html.SafeUrl) {
var url = goog.html.SafeUrl.unwrap(value);
return 'url("' + url.replace(/</g, '%3c').replace(/[\\"]/g, '\\$&') + '")';
}
var result = value instanceof goog.string.Const ?
goog.string.Const.unwrap(value) :
goog.html.SafeStyle.sanitizePropertyValueString_(String(value));
// These characters can be used to change context and we don't want that even
// with const values.
goog.asserts.assert(!/[{;}]/.test(result), 'Value does not allow [{;}].');
return result;
};
/**
* Checks string value.
* @param {string} value
* @return {string}
* @private
*/
goog.html.SafeStyle.sanitizePropertyValueString_ = function(value) {
var valueWithoutFunctions =
value.replace(goog.html.SafeUrl.FUNCTIONS_RE_, '$1')
.replace(goog.html.SafeUrl.URL_RE_, 'url');
if (!goog.html.SafeStyle.VALUE_RE_.test(valueWithoutFunctions)) {
goog.asserts.fail(
'String value allows only ' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ +
' and simple functions, got: ' + value);
return goog.html.SafeStyle.INNOCUOUS_STRING;
} else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) {
goog.asserts.fail('String value requires balanced quotes, got: ' + value);
return goog.html.SafeStyle.INNOCUOUS_STRING;
}
return goog.html.SafeStyle.sanitizeUrl_(value);
};
/**
* Checks that quotes (" and ') are properly balanced inside a string. Assumes
* that neither escape (\) nor any other character that could result in
* breaking out of a string parsing context are allowed;
* see http://www.w3.org/TR/css3-syntax/#string-token-diagram.
* @param {string} value Untrusted CSS property value.
* @return {boolean} True if property value is safe with respect to quote
* balancedness.
* @private
*/
goog.html.SafeStyle.hasBalancedQuotes_ = function(value) {
var outsideSingle = true;
var outsideDouble = true;
for (var i = 0; i < value.length; i++) {
var c = value.charAt(i);
if (c == "'" && outsideDouble) {
outsideSingle = !outsideSingle;
} else if (c == '"' && outsideSingle) {
outsideDouble = !outsideDouble;
}
}
return outsideSingle && outsideDouble;
};
/**
* Characters allowed in goog.html.SafeStyle.VALUE_RE_.
* @private {string}
*/
goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ = '[-,."\'%_!# a-zA-Z0-9]';
/**
* Regular expression for safe values.
*
* Quotes (" and ') are allowed, but a check must be done elsewhere to ensure
* they're balanced.
*
* ',' allows multiple values to be assigned to the same property
* (e.g. background-attachment or font-family) and hence could allow
* multiple values to get injected, but that should pose no risk of XSS.
*
* The expression checks only for XSS safety, not for CSS validity.
* @const {!RegExp}
* @private
*/
goog.html.SafeStyle.VALUE_RE_ =
new RegExp('^' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + '+$');
/**
* Regular expression for url(). We support URLs allowed by
* https://www.w3.org/TR/css-syntax-3/#url-token-diagram without using escape
* sequences. Use percent-encoding if you need to use special characters like
* backslash.
* @private @const {!RegExp}
*/
goog.html.SafeUrl.URL_RE_ = new RegExp(
'\\b(url\\([ \t\n]*)(' +
'\'[ -&(-\\[\\]-~]*\'' + // Printable characters except ' and \.
'|"[ !#-\\[\\]-~]*"' + // Printable characters except " and \.
'|[!#-&*-\\[\\]-~]*' + // Printable characters except [ "'()\\].
')([ \t\n]*\\))',
'g');
/**
* Regular expression for simple functions.
* @private @const {!RegExp}
*/
goog.html.SafeUrl.FUNCTIONS_RE_ = new RegExp(
'\\b(hsl|hsla|rgb|rgba|(rotate|scale|translate)(X|Y|Z|3d)?)' +
'\\([-0-9a-z.%, ]+\\)',
'g');
/**
* Sanitize URLs inside url().
*
* NOTE: We could also consider using CSS.escape once that's available in the
* browsers. However, loosely matching URL e.g. with url\(.*\) and then escaping
* the contents would result in a slightly different language than CSS leading
* to confusion of users. E.g. url(")") is valid in CSS but it would be invalid
* as seen by our parser. On the other hand, url(\) is invalid in CSS but our
* parser would be fine with it.
*
* @param {string} value Untrusted CSS property value.
* @return {string}
* @private
*/
goog.html.SafeStyle.sanitizeUrl_ = function(value) {
return value.replace(
goog.html.SafeUrl.URL_RE_, function(match, before, url, after) {
var quote = '';
url = url.replace(/^(['"])(.*)\1$/, function(match, start, inside) {
quote = start;
return inside;
});
var sanitized = goog.html.SafeUrl.sanitize(url).getTypedStringValue();
return before + quote + sanitized + quote + after;
});
};
/**
* 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);
};

View file

@ -0,0 +1,344 @@
// 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(xtof): Link to document stating type contract.
*/
goog.provide('goog.html.SafeStyleSheet');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.html.SafeStyle');
goog.require('goog.object');
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 &lt;} is dangerous, even when inside CSS strings, and so should
* always be forbidden or CSS-escaped in user controlled input. For example, if
* {@code &lt;/style&gt;&lt;script&gt;evil&lt;/script&gt;"} 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 &amp;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 {!Object}
* @private
*/
this.SAFE_STYLE_SHEET_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 {!Object}
* @private
*/
goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
/**
* Creates a style sheet consisting of one selector and one style definition.
* Use {@link goog.html.SafeStyleSheet.concat} to create longer style sheets.
* This function doesn't support @import, @media and similar constructs.
* @param {string} selector CSS selector, e.g. '#id' or 'tag .class, #id'. We
* support CSS3 selectors: https://w3.org/TR/css3-selectors/#selectors.
* @param {!goog.html.SafeStyle.PropertyMap|!goog.html.SafeStyle} style Style
* definition associated with the selector.
* @return {!goog.html.SafeStyleSheet}
* @throws {Error} If invalid selector is provided.
*/
goog.html.SafeStyleSheet.createRule = function(selector, style) {
if (goog.string.contains(selector, '<')) {
throw Error('Selector does not allow \'<\', got: ' + selector);
}
// Remove strings.
var selectorToCheck =
selector.replace(/('|")((?!\1)[^\r\n\f\\]|\\[\s\S])*\1/g, '');
// Check characters allowed in CSS3 selectors.
if (!/^[-_a-zA-Z0-9#.:* ,>+~[\]()=^$|]+$/.test(selectorToCheck)) {
throw Error(
'Selector allows only [-_a-zA-Z0-9#.:* ,>+~[\\]()=^$|] and ' +
'strings, got: ' + selector);
}
// Check balanced () and [].
if (!goog.html.SafeStyleSheet.hasBalancedBrackets_(selectorToCheck)) {
throw Error('() and [] in selector must be balanced, got: ' + selector);
}
if (!(style instanceof goog.html.SafeStyle)) {
style = goog.html.SafeStyle.create(style);
}
var styleSheet = selector + '{' + goog.html.SafeStyle.unwrap(style) + '}';
return goog.html.SafeStyleSheet
.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
};
/**
* Checks if a string has balanced () and [] brackets.
* @param {string} s String to check.
* @return {boolean}
* @private
*/
goog.html.SafeStyleSheet.hasBalancedBrackets_ = function(s) {
var brackets = {'(': ')', '[': ']'};
var expectedBrackets = [];
for (var i = 0; i < s.length; i++) {
var ch = s[i];
if (brackets[ch]) {
expectedBrackets.push(brackets[ch]);
} else if (goog.object.contains(brackets, ch)) {
if (expectedBrackets.pop() != ch) {
return false;
}
}
}
return expectedBrackets.length == 0;
};
/**
* 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 &lt; 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_STYLE_SHEET_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 + '\' of type ' + goog.typeOf(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) {
return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_(
styleSheet);
};
/**
* Called from createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(). This
* method exists only so that the compiler can dead code eliminate static
* fields (like EMPTY) when they're not accessed.
* @param {string} styleSheet
* @return {!goog.html.SafeStyleSheet}
* @private
*/
goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ =
function(styleSheet) {
this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = styleSheet;
return this;
};
/**
* A SafeStyleSheet instance corresponding to the empty string.
* @const {!goog.html.SafeStyleSheet}
*/
goog.html.SafeStyleSheet.EMPTY =
goog.html.SafeStyleSheet
.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse('');

View file

@ -0,0 +1,454 @@
// 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(xtof): Link to document stating type contract.
*/
goog.provide('goog.html.SafeUrl');
goog.require('goog.asserts');
goog.require('goog.fs.url');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.i18n.bidi.Dir');
goog.require('goog.i18n.bidi.DirectionalString');
goog.require('goog.string');
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, in the sense that
* the use will not result in a Cross-Site-Scripting vulnerability. Similarly,
* SafeUrls can be interpolated into the URL context of an HTML template (e.g.,
* inside a href attribute). However, appropriate HTML-escaping must still be
* applied.
*
* 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 {!Object}
* @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).
*
* @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 + '\' of type ' + goog.typeOf(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 matches Blob or data types that can have SafeUrls created
* from URL.createObjectURL(blob) or via a data: URI.
* @const
* @private
*/
goog.html.SAFE_MIME_TYPE_PATTERN_ = new RegExp(
'^(?:audio/(?:3gpp|3gpp2|aac|midi|mp4|mpeg|ogg|x-m4a|x-wav|webm)|' +
'image/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|' +
'text/csv|' +
'video/(?:mpeg|mp4|ogg|webm))$',
'i');
/**
* Creates a SafeUrl wrapping a blob URL for the given {@code blob}.
*
* The blob URL is created with {@code URL.createObjectURL}. If the MIME type
* for {@code blob} is not of a known safe audio, image or video MIME type,
* then the SafeUrl will wrap {@link #INNOCUOUS_STRING}.
*
* @see http://www.w3.org/TR/FileAPI/#url
* @param {!Blob} blob
* @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped
* as a SafeUrl.
*/
goog.html.SafeUrl.fromBlob = function(blob) {
var url = goog.html.SAFE_MIME_TYPE_PATTERN_.test(blob.type) ?
goog.fs.url.createObjectUrl(blob) :
goog.html.SafeUrl.INNOCUOUS_STRING;
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};
/**
* Matches a base-64 data URL, with the first match group being the MIME type.
* @const
* @private
*/
goog.html.DATA_URL_PATTERN_ = /^data:([^;,]*);base64,[a-z0-9+\/]+=*$/i;
/**
* Creates a SafeUrl wrapping a data: URL, after validating it matches a
* known-safe audio, image or video MIME type.
*
* @param {string} dataUrl A valid base64 data URL with one of the whitelisted
* audio, image or video MIME types.
* @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}
* wrapped as a SafeUrl if it does not pass.
*/
goog.html.SafeUrl.fromDataUrl = function(dataUrl) {
// There's a slight risk here that a browser sniffs the content type if it
// doesn't know the MIME type and executes HTML within the data: URL. For this
// to cause XSS it would also have to execute the HTML in the same origin
// of the page with the link. It seems unlikely that both of these will
// happen, particularly in not really old IEs.
var match = dataUrl.match(goog.html.DATA_URL_PATTERN_);
var valid = match && goog.html.SAFE_MIME_TYPE_PATTERN_.test(match[1]);
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
valid ? dataUrl : goog.html.SafeUrl.INNOCUOUS_STRING);
};
/**
* Creates a SafeUrl wrapping a tel: URL.
*
* @param {string} telUrl A tel URL.
* @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}
* wrapped as a SafeUrl if it does not pass.
*/
goog.html.SafeUrl.fromTelUrl = function(telUrl) {
// There's a risk that a tel: URL could immediately place a call once
// clicked, without requiring user confirmation. For that reason it is
// handled in this separate function.
if (!goog.string.caseInsensitiveStartsWith(telUrl, 'tel:')) {
telUrl = goog.html.SafeUrl.INNOCUOUS_STRING;
}
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
telUrl);
};
/**
* Creates a SafeUrl from TrustedResourceUrl. This is safe because
* TrustedResourceUrl is more tightly restricted than SafeUrl.
*
* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl
* @return {!goog.html.SafeUrl}
*/
goog.html.SafeUrl.fromTrustedResourceUrl = function(trustedResourceUrl) {
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl));
};
/**
* 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 or ftp).
* (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).
*
* @private
* @const {!RegExp}
*/
goog.html.SAFE_URL_PATTERN_ =
/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/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.
*
* {@code url} may be a URL with the http, https, mailto or ftp scheme,
* or a relative URL (i.e., a URL without a scheme; specifically, a
* scheme-relative, absolute-path-relative, or path-relative URL).
*
* @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;
}
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};
/**
* 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.
*
* {@code url} may be a URL with the http, https, mailto or ftp scheme,
* or a relative URL (i.e., a URL without a scheme; specifically, a
* scheme-relative, absolute-path-relative, or path-relative URL).
*
* This function asserts (using goog.asserts) that the URL matches this pattern.
* If it does not, in addition to failing the assert, an innocous URL will be
* returned.
*
* @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.sanitizeAssertUnchanged = function(url) {
if (url instanceof goog.html.SafeUrl) {
return url;
} else if (url.implementsGoogStringTypedString) {
url = url.getTypedStringValue();
} else {
url = String(url);
}
if (!goog.asserts.assert(goog.html.SAFE_URL_PATTERN_.test(url))) {
url = goog.html.SafeUrl.INNOCUOUS_STRING;
}
return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};
/**
* Type marker for the SafeUrl type, used to implement additional run-time
* type checking.
* @const {!Object}
* @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;
};
/**
* A SafeUrl corresponding to the special about:blank url.
* @const {!goog.html.SafeUrl}
*/
goog.html.SafeUrl.ABOUT_BLANK =
goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
'about:blank');

View file

@ -0,0 +1,408 @@
// 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(xtof): 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 fromConstant}, {@code fromConstants}, {@code format} or {@code
* formatWithParams}), 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 {!Object}
* @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 + '\' of type ' + goog.typeOf(trustedResourceUrl));
return 'type_error:TrustedResourceUrl';
}
};
/**
* Creates a TrustedResourceUrl from a format string and arguments.
*
* The arguments for interpolation into the format string map labels to values.
* Values of type `goog.string.Const` are interpolated without modifcation.
* Values of other types are cast to string and encoded with
* encodeURIComponent.
*
* `%{<label>}` markers are used in the format string to indicate locations
* to be interpolated with the valued mapped to the given label. `<label>`
* must contain only alphanumeric and `_` characters.
*
* The format string must start with one of the following:
* - `https://<origin>/`
* - `//<origin>/`
* - `/<pathStart>`
* - `about:blank`
*
* `<origin>` must contain only alphanumeric or any of the following: `-.:[]`.
* `<pathStart>` is any character except `/` and `\`.
*
* Example usage:
*
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(
* 'https://www.google.com/search?q=%{query}), {'query': searchTerm});
*
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(
* '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), {
* 'videoId': videoId,
* 'autoplay': opt_autoplay ?
* goog.string.Const.EMPTY : goog.string.Const.from('&autoplay=1')
* });
*
* While this function can be used to create a TrustedResourceUrl from only
* constants, fromConstant() and fromConstants() are generally preferable for
* that purpose.
*
* @param {!goog.string.Const} format The format string.
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping
* of labels to values to be interpolated into the format string.
* goog.string.Const values are interpolated without encoding.
* @return {!goog.html.TrustedResourceUrl}
* @throws {!Error} On an invalid format string or if a label used in the
* the format string is not present in args.
*/
goog.html.TrustedResourceUrl.format = function(format, args) {
var result = goog.html.TrustedResourceUrl.format_(format, args);
return goog.html.TrustedResourceUrl
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result);
};
/**
* String version of TrustedResourceUrl.format.
* @param {!goog.string.Const} format
* @param {!Object<string, (string|number|!goog.string.Const)>} args
* @return {string}
* @throws {!Error}
* @private
*/
goog.html.TrustedResourceUrl.format_ = function(format, args) {
var formatStr = goog.string.Const.unwrap(format);
if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) {
throw new Error('Invalid TrustedResourceUrl format: ' + formatStr);
}
return formatStr.replace(
goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) {
if (!Object.prototype.hasOwnProperty.call(args, id)) {
throw new Error(
'Found marker, "' + id + '", in format string, "' + formatStr +
'", but no valid label mapping found ' +
'in args: ' + JSON.stringify(args));
}
var arg = args[id];
if (arg instanceof goog.string.Const) {
return goog.string.Const.unwrap(arg);
} else {
return encodeURIComponent(String(arg));
}
});
};
/**
* @private @const {!RegExp}
*/
goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g;
/**
* The URL must be absolute, scheme-relative or path-absolute. So it must
* start with:
* - https:// followed by allowed origin characters.
* - // followed by allowed origin characters.
* - / not followed by / or \. There will only be an absolute path.
*
* Based on
* https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing
* an initial / which is not followed by another / or \ will end up in the "path
* state" and from there it can only go to "fragment state" and "query state".
*
* We don't enforce a well-formed domain name. So '.' or '1.2' are valid.
* That's ok because the origin comes from a compile-time constant.
*
* A regular expression is used instead of goog.uri for several reasons:
* - Strictness. E.g. we don't want any userinfo component and we don't
* want '/./, nor \' in the first path component.
* - Small trusted base. goog.uri is generic and might need to change,
* reasoning about all the ways it can parse a URL now and in the future
* is error-prone.
* - Code size. We expect many calls to .format(), many of which might
* not be using goog.uri.
* - Simplicity. Using goog.uri would likely not result in simpler nor shorter
* code.
* @private @const {!RegExp}
*/
goog.html.TrustedResourceUrl.BASE_URL_ =
/^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank(#|$)/i;
/**
* Formats the URL same as TrustedResourceUrl.format and then adds extra URL
* parameters.
*
* Example usage:
*
* // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and
* // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc'
* // and opt_autoplay=undefined.
* var url = goog.html.TrustedResourceUrl.formatWithParams(
* goog.string.Const.from('//www.youtube.com/v/%{videoId}'),
* {'videoId': videoId},
* {'autoplay': opt_autoplay});
*
* @param {!goog.string.Const} format The format string.
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping
* of labels to values to be interpolated into the format string.
* goog.string.Const values are interpolated without encoding.
* @param {!Object<string, *>} params Parameters to add to URL. Parameters with
* value {@code null} or {@code undefined} are skipped. Both keys and values
* are encoded. Note that JavaScript doesn't guarantee the order of values
* in an object which might result in non-deterministic order of the
* parameters. However, browsers currently preserve the order.
* @return {!goog.html.TrustedResourceUrl}
* @throws {!Error} On an invalid format string or if a label used in the
* the format string is not present in args.
*/
goog.html.TrustedResourceUrl.formatWithParams = function(format, args, params) {
var url = goog.html.TrustedResourceUrl.format_(format, args);
var separator = /\?/.test(url) ? '&' : '?';
for (var key in params) {
if (params[key] == null) {
continue;
}
url += separator + encodeURIComponent(key) + '=' +
encodeURIComponent(String(params[key]));
separator = '&';
}
return goog.html.TrustedResourceUrl
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
};
/**
* 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));
};
/**
* Creates a TrustedResourceUrl object from a compile-time constant strings.
*
* Compile-time constant strings are inherently program-controlled and hence
* trusted.
*
* @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from
* which to create a TrustedResourceUrl.
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
* initialized to concatenation of {@code parts}.
*/
goog.html.TrustedResourceUrl.fromConstants = function(parts) {
var unwrapped = '';
for (var i = 0; i < parts.length; i++) {
unwrapped += goog.string.Const.unwrap(parts[i]);
}
return goog.html.TrustedResourceUrl
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped);
};
/**
* Type marker for the TrustedResourceUrl type, used to implement additional
* run-time type checking.
* @const {!Object}
* @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;
};

View file

@ -0,0 +1,228 @@
// 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.
*/
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.isEmptyOrWhitespace(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 SafeStyle 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 SafeStyleSheet 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);
};