Path: blob/trunk/third_party/closure/goog/html/safestyle.js
2868 views
// Copyright 2014 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview The SafeStyle type and its builders.16*17* TODO(xtof): Link to document stating type contract.18*/1920goog.provide('goog.html.SafeStyle');2122goog.require('goog.array');23goog.require('goog.asserts');24goog.require('goog.string');25goog.require('goog.string.Const');26goog.require('goog.string.TypedString');27282930/**31* A string-like object which represents a sequence of CSS declarations32* ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})33* and that carries the security type contract that its value, as a string,34* will not cause untrusted script execution (XSS) when evaluated as CSS in a35* browser.36*37* Instances of this type must be created via the factory methods38* ({@code goog.html.SafeStyle.create} or39* {@code goog.html.SafeStyle.fromConstant}) and not by invoking its40* constructor. The constructor intentionally takes no parameters and the type41* is immutable; hence only a default instance corresponding to the empty string42* can be obtained via constructor invocation.43*44* A SafeStyle's string representation ({@link #getTypedStringValue()}) can45* safely:46* <ul>47* <li>Be interpolated as the entire content of a *quoted* HTML style48* attribute, or before already existing properties. The SafeStyle string49* *must be HTML-attribute-escaped* (where " and ' are escaped) before50* interpolation.51* <li>Be interpolated as the entire content of a {}-wrapped block within a52* stylesheet, or before already existing properties. The SafeStyle string53* should not be escaped before interpolation. SafeStyle's contract also54* guarantees that the string will not be able to introduce new properties55* or elide existing ones.56* <li>Be assigned to the style property of a DOM node. The SafeStyle string57* should not be escaped before being assigned to the property.58* </ul>59*60* A SafeStyle may never contain literal angle brackets. Otherwise, it could61* be unsafe to place a SafeStyle into a <style> tag (where it can't62* be HTML escaped). For example, if the SafeStyle containing63* "{@code font: 'foo <style/><script>evil</script>'}" were64* interpolated within a <style> tag, this would then break out of the65* style context into HTML.66*67* A SafeStyle may contain literal single or double quotes, and as such the68* entire style string must be escaped when used in a style attribute (if69* this were not the case, the string could contain a matching quote that70* would escape from the style attribute).71*72* Values of this type must be composable, i.e. for any two values73* {@code style1} and {@code style2} of this type,74* {@code goog.html.SafeStyle.unwrap(style1) +75* goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies76* the SafeStyle type constraint. This requirement implies that for any value77* {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must78* not end in a "property value" or "property name" context. For example,79* a value of {@code background:url("} or {@code font-} would not satisfy the80* SafeStyle contract. This is because concatenating such strings with a81* second value that itself does not contain unsafe CSS can result in an82* overall string that does. For example, if {@code javascript:evil())"} is83* appended to {@code background:url("}, the resulting string may result in84* the execution of a malicious script.85*86* TODO(mlourenco): Consider whether we should implement UTF-8 interchange87* validity checks and blacklisting of newlines (including Unicode ones) and88* other whitespace characters (\t, \f). Document here if so and also update89* SafeStyle.fromConstant().90*91* The following example values comply with this type's contract:92* <ul>93* <li><pre>width: 1em;</pre>94* <li><pre>height:1em;</pre>95* <li><pre>width: 1em;height: 1em;</pre>96* <li><pre>background:url('http://url');</pre>97* </ul>98* In addition, the empty string is safe for use in a CSS attribute.99*100* The following example values do NOT comply with this type's contract:101* <ul>102* <li><pre>background: red</pre> (missing a trailing semi-colon)103* <li><pre>background:</pre> (missing a value and a trailing semi-colon)104* <li><pre>1em</pre> (missing an attribute name, which provides context for105* the value)106* </ul>107*108* @see goog.html.SafeStyle#create109* @see goog.html.SafeStyle#fromConstant110* @see http://www.w3.org/TR/css3-syntax/111* @constructor112* @final113* @struct114* @implements {goog.string.TypedString}115*/116goog.html.SafeStyle = function() {117/**118* The contained value of this SafeStyle. The field has a purposely119* ugly name to make (non-compiled) code that attempts to directly access this120* field stand out.121* @private {string}122*/123this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';124125/**126* A type marker used to implement additional run-time type checking.127* @see goog.html.SafeStyle#unwrap128* @const {!Object}129* @private130*/131this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =132goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;133};134135136/**137* @override138* @const139*/140goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;141142143/**144* Type marker for the SafeStyle type, used to implement additional145* run-time type checking.146* @const {!Object}147* @private148*/149goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};150151152/**153* Creates a SafeStyle object from a compile-time constant string.154*155* {@code style} should be in the format156* {@code name: value; [name: value; ...]} and must not have any < or >157* characters in it. This is so that SafeStyle's contract is preserved,158* allowing the SafeStyle to correctly be interpreted as a sequence of CSS159* declarations and without affecting the syntactic structure of any160* surrounding CSS and HTML.161*162* This method performs basic sanity checks on the format of {@code style}163* but does not constrain the format of {@code name} and {@code value}, except164* for disallowing tag characters.165*166* @param {!goog.string.Const} style A compile-time-constant string from which167* to create a SafeStyle.168* @return {!goog.html.SafeStyle} A SafeStyle object initialized to169* {@code style}.170*/171goog.html.SafeStyle.fromConstant = function(style) {172var styleString = goog.string.Const.unwrap(style);173if (styleString.length === 0) {174return goog.html.SafeStyle.EMPTY;175}176goog.html.SafeStyle.checkStyle_(styleString);177goog.asserts.assert(178goog.string.endsWith(styleString, ';'),179'Last character of style string is not \';\': ' + styleString);180goog.asserts.assert(181goog.string.contains(styleString, ':'),182'Style string must contain at least one \':\', to ' +183'specify a "name: value" pair: ' + styleString);184return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(185styleString);186};187188189/**190* Checks if the style definition is valid.191* @param {string} style192* @private193*/194goog.html.SafeStyle.checkStyle_ = function(style) {195goog.asserts.assert(196!/[<>]/.test(style), 'Forbidden characters in style string: ' + style);197};198199200/**201* Returns this SafeStyle's value as a string.202*203* IMPORTANT: In code where it is security relevant that an object's type is204* indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of205* this method. If in doubt, assume that it's security relevant. In particular,206* note that goog.html functions which return a goog.html type do not guarantee207* the returned instance is of the right type. For example:208*209* <pre>210* var fakeSafeHtml = new String('fake');211* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;212* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);213* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by214* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml215* // instanceof goog.html.SafeHtml.216* </pre>217*218* @see goog.html.SafeStyle#unwrap219* @override220*/221goog.html.SafeStyle.prototype.getTypedStringValue = function() {222return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;223};224225226if (goog.DEBUG) {227/**228* Returns a debug string-representation of this value.229*230* To obtain the actual string value wrapped in a SafeStyle, use231* {@code goog.html.SafeStyle.unwrap}.232*233* @see goog.html.SafeStyle#unwrap234* @override235*/236goog.html.SafeStyle.prototype.toString = function() {237return 'SafeStyle{' + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ +238'}';239};240}241242243/**244* Performs a runtime check that the provided object is indeed a245* SafeStyle object, and returns its value.246*247* @param {!goog.html.SafeStyle} safeStyle The object to extract from.248* @return {string} The safeStyle object's contained string, unless249* the run-time type check fails. In that case, {@code unwrap} returns an250* innocuous string, or, if assertions are enabled, throws251* {@code goog.asserts.AssertionError}.252*/253goog.html.SafeStyle.unwrap = function(safeStyle) {254// Perform additional Run-time type-checking to ensure that255// safeStyle is indeed an instance of the expected type. This256// provides some additional protection against security bugs due to257// application code that disables type checks.258// Specifically, the following checks are performed:259// 1. The object is an instance of the expected type.260// 2. The object is not an instance of a subclass.261// 3. The object carries a type marker for the expected type. "Faking" an262// object requires a reference to the type marker, which has names intended263// to stand out in code reviews.264if (safeStyle instanceof goog.html.SafeStyle &&265safeStyle.constructor === goog.html.SafeStyle &&266safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===267goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {268return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;269} else {270goog.asserts.fail('expected object of type SafeStyle, got \'' +271safeStyle + '\' of type ' + goog.typeOf(safeStyle));272return 'type_error:SafeStyle';273}274};275276277/**278* Package-internal utility method to create SafeStyle instances.279*280* @param {string} style The string to initialize the SafeStyle object with.281* @return {!goog.html.SafeStyle} The initialized SafeStyle object.282* @package283*/284goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = function(285style) {286return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style);287};288289290/**291* Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This292* method exists only so that the compiler can dead code eliminate static293* fields (like EMPTY) when they're not accessed.294* @param {string} style295* @return {!goog.html.SafeStyle}296* @private297*/298goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(299style) {300this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;301return this;302};303304305/**306* A SafeStyle instance corresponding to the empty string.307* @const {!goog.html.SafeStyle}308*/309goog.html.SafeStyle.EMPTY =310goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');311312313/**314* The innocuous string generated by goog.html.SafeUrl.create when passed315* an unsafe value.316* @const {string}317*/318goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';319320321/**322* Mapping of property names to their values.323* @typedef {!Object<string, goog.string.Const|string>}324*/325goog.html.SafeStyle.PropertyMap;326327328/**329* Creates a new SafeStyle object from the properties specified in the map.330* @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to331* their values, for example {'margin': '1px'}. Names must consist of332* [-_a-zA-Z0-9]. Values might be strings consisting of333* [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced.334* Other values must be wrapped in goog.string.Const. Null value causes335* skipping the property.336* @return {!goog.html.SafeStyle}337* @throws {Error} If invalid name is provided.338* @throws {goog.asserts.AssertionError} If invalid value is provided. With339* disabled assertions, invalid value is replaced by340* goog.html.SafeStyle.INNOCUOUS_STRING.341*/342goog.html.SafeStyle.create = function(map) {343var style = '';344for (var name in map) {345if (!/^[-_a-zA-Z0-9]+$/.test(name)) {346throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name);347}348var value = map[name];349if (value == null) {350continue;351}352if (value instanceof goog.string.Const) {353value = goog.string.Const.unwrap(value);354// These characters can be used to change context and we don't want that355// even with const values.356goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].');357} else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) {358goog.asserts.fail(359'String value allows only [-,."\'%_!# a-zA-Z0-9], rgb() and ' +360'rgba(), got: ' + value);361value = goog.html.SafeStyle.INNOCUOUS_STRING;362} else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) {363goog.asserts.fail('String value requires balanced quotes, got: ' + value);364value = goog.html.SafeStyle.INNOCUOUS_STRING;365}366style += name + ':' + value + ';';367}368if (!style) {369return goog.html.SafeStyle.EMPTY;370}371goog.html.SafeStyle.checkStyle_(style);372return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(373style);374};375376377/**378* Checks that quotes (" and ') are properly balanced inside a string. Assumes379* that neither escape (\) nor any other character that could result in380* breaking out of a string parsing context are allowed;381* see http://www.w3.org/TR/css3-syntax/#string-token-diagram.382* @param {string} value Untrusted CSS property value.383* @return {boolean} True if property value is safe with respect to quote384* balancedness.385* @private386*/387goog.html.SafeStyle.hasBalancedQuotes_ = function(value) {388var outsideSingle = true;389var outsideDouble = true;390for (var i = 0; i < value.length; i++) {391var c = value.charAt(i);392if (c == "'" && outsideDouble) {393outsideSingle = !outsideSingle;394} else if (c == '"' && outsideSingle) {395outsideDouble = !outsideDouble;396}397}398return outsideSingle && outsideDouble;399};400401402// Keep in sync with the error string in create().403/**404* Regular expression for safe values.405*406* Quotes (" and ') are allowed, but a check must be done elsewhere to ensure407* they're balanced.408*409* ',' allows multiple values to be assigned to the same property410* (e.g. background-attachment or font-family) and hence could allow411* multiple values to get injected, but that should pose no risk of XSS.412*413* The rgb() and rgba() expression checks only for XSS safety, not for CSS414* validity.415* @const {!RegExp}416* @private417*/418goog.html.SafeStyle.VALUE_RE_ =419/^([-,."'%_!# a-zA-Z0-9]+|(?:rgb|hsl)a?\([0-9.%, ]+\))$/;420421422/**423* Creates a new SafeStyle object by concatenating the values.424* @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args425* SafeStyles to concatenate.426* @return {!goog.html.SafeStyle}427*/428goog.html.SafeStyle.concat = function(var_args) {429var style = '';430431/**432* @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument433*/434var addArgument = function(argument) {435if (goog.isArray(argument)) {436goog.array.forEach(argument, addArgument);437} else {438style += goog.html.SafeStyle.unwrap(argument);439}440};441442goog.array.forEach(arguments, addArgument);443if (!style) {444return goog.html.SafeStyle.EMPTY;445}446return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(447style);448};449450451