| 1 |
// Copyright 2013 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
/** |
| 16 |
* @fileoverview The TrustedResourceUrl type and its builders. |
| 17 |
* |
| 18 |
* TODO(xtof): Link to document stating type contract. |
| 19 |
*/ |
| 20 |
|
| 21 |
goog.provide('goog.html.TrustedResourceUrl'); |
| 22 |
|
| 23 |
goog.require('goog.asserts'); |
| 24 |
goog.require('goog.i18n.bidi.Dir'); |
| 25 |
goog.require('goog.i18n.bidi.DirectionalString'); |
| 26 |
goog.require('goog.string.Const'); |
| 27 |
goog.require('goog.string.TypedString'); |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
/** |
| 32 |
* A URL which is under application control and from which script, CSS, and |
| 33 |
* other resources that represent executable code, can be fetched. |
| 34 |
* |
| 35 |
* Given that the URL can only be constructed from strings under application |
| 36 |
* control and is used to load resources, bugs resulting in a malformed URL |
| 37 |
* should not have a security impact and are likely to be easily detectable |
| 38 |
* during testing. Given the wide number of non-RFC compliant URLs in use, |
| 39 |
* stricter validation could prevent some applications from being able to use |
| 40 |
* this type. |
| 41 |
* |
| 42 |
* Instances of this type must be created via the factory method, |
| 43 |
* ({@code fromConstant}, {@code fromConstants}, {@code format} or {@code |
| 44 |
* formatWithParams}), and not by invoking its constructor. The constructor |
| 45 |
* intentionally takes no parameters and the type is immutable; hence only a |
| 46 |
* default instance corresponding to the empty string can be obtained via |
| 47 |
* constructor invocation. |
| 48 |
* |
| 49 |
* @see goog.html.TrustedResourceUrl#fromConstant |
| 50 |
* @constructor |
| 51 |
* @final |
| 52 |
* @struct |
| 53 |
* @implements {goog.i18n.bidi.DirectionalString} |
| 54 |
* @implements {goog.string.TypedString} |
| 55 |
*/ |
| 56 |
goog.html.TrustedResourceUrl = function() { |
| 57 |
/** |
| 58 |
* The contained value of this TrustedResourceUrl. The field has a purposely |
| 59 |
* ugly name to make (non-compiled) code that attempts to directly access this |
| 60 |
* field stand out. |
| 61 |
* @private {string} |
| 62 |
*/ |
| 63 |
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = ''; |
| 64 |
|
| 65 |
/** |
| 66 |
* A type marker used to implement additional run-time type checking. |
| 67 |
* @see goog.html.TrustedResourceUrl#unwrap |
| 68 |
* @const {!Object} |
| 69 |
* @private |
| 70 |
*/ |
| 71 |
this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = |
| 72 |
goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; |
| 73 |
}; |
| 74 |
|
| 75 |
|
| 76 |
/** |
| 77 |
* @override |
| 78 |
* @const |
| 79 |
*/ |
| 80 |
goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true; |
| 81 |
|
| 82 |
|
| 83 |
/** |
| 84 |
* Returns this TrustedResourceUrl's value as a string. |
| 85 |
* |
| 86 |
* IMPORTANT: In code where it is security relevant that an object's type is |
| 87 |
* indeed {@code TrustedResourceUrl}, use |
| 88 |
* {@code goog.html.TrustedResourceUrl.unwrap} instead of this method. If in |
| 89 |
* doubt, assume that it's security relevant. In particular, note that |
| 90 |
* goog.html functions which return a goog.html type do not guarantee that |
| 91 |
* the returned instance is of the right type. For example: |
| 92 |
* |
| 93 |
* <pre> |
| 94 |
* var fakeSafeHtml = new String('fake'); |
| 95 |
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; |
| 96 |
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); |
| 97 |
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by |
| 98 |
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof |
| 99 |
* // goog.html.SafeHtml. |
| 100 |
* </pre> |
| 101 |
* |
| 102 |
* @see goog.html.TrustedResourceUrl#unwrap |
| 103 |
* @override |
| 104 |
*/ |
| 105 |
goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() { |
| 106 |
return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; |
| 107 |
}; |
| 108 |
|
| 109 |
|
| 110 |
/** |
| 111 |
* @override |
| 112 |
* @const |
| 113 |
*/ |
| 114 |
goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString = |
| 115 |
true; |
| 116 |
|
| 117 |
|
| 118 |
/** |
| 119 |
* Returns this URLs directionality, which is always {@code LTR}. |
| 120 |
* @override |
| 121 |
*/ |
| 122 |
goog.html.TrustedResourceUrl.prototype.getDirection = function() { |
| 123 |
return goog.i18n.bidi.Dir.LTR; |
| 124 |
}; |
| 125 |
|
| 126 |
|
| 127 |
/** |
| 128 |
* Creates a new TrustedResourceUrl with params added to URL. |
| 129 |
* @param {!Object<string, *>} params Parameters to add to URL. Parameters with |
| 130 |
* value {@code null} or {@code undefined} are skipped. Both keys and values |
| 131 |
* are encoded. If the value is an array then the same parameter is added |
| 132 |
* for every element in the array. Note that JavaScript doesn't guarantee |
| 133 |
* the order of values in an object which might result in non-deterministic |
| 134 |
* order of the parameters. However, browsers currently preserve the order. |
| 135 |
* @return {!goog.html.TrustedResourceUrl} New TrustedResourceUrl with params. |
| 136 |
*/ |
| 137 |
goog.html.TrustedResourceUrl.prototype.cloneWithParams = function(params) { |
| 138 |
var url = goog.html.TrustedResourceUrl.unwrap(this); |
| 139 |
var separator = /\?/.test(url) ? '&' : '?'; |
| 140 |
for (var key in params) { |
| 141 |
var values = goog.isArray(params[key]) ? params[key] : [params[key]]; |
| 142 |
for (var i = 0; i < values.length; i++) { |
| 143 |
if (values[i] == null) { |
| 144 |
continue; |
| 145 |
} |
| 146 |
url += separator + encodeURIComponent(key) + '=' + |
| 147 |
encodeURIComponent(String(values[i])); |
| 148 |
separator = '&'; |
| 149 |
} |
| 150 |
} |
| 151 |
return goog.html.TrustedResourceUrl |
| 152 |
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url); |
| 153 |
}; |
| 154 |
|
| 155 |
|
| 156 |
if (goog.DEBUG) { |
| 157 |
/** |
| 158 |
* Returns a debug string-representation of this value. |
| 159 |
* |
| 160 |
* To obtain the actual string value wrapped in a TrustedResourceUrl, use |
| 161 |
* {@code goog.html.TrustedResourceUrl.unwrap}. |
| 162 |
* |
| 163 |
* @see goog.html.TrustedResourceUrl#unwrap |
| 164 |
* @override |
| 165 |
*/ |
| 166 |
goog.html.TrustedResourceUrl.prototype.toString = function() { |
| 167 |
return 'TrustedResourceUrl{' + |
| 168 |
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}'; |
| 169 |
}; |
| 170 |
} |
| 171 |
|
| 172 |
|
| 173 |
/** |
| 174 |
* Performs a runtime check that the provided object is indeed a |
| 175 |
* TrustedResourceUrl object, and returns its value. |
| 176 |
* |
| 177 |
* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to |
| 178 |
* extract from. |
| 179 |
* @return {string} The trustedResourceUrl object's contained string, unless |
| 180 |
* the run-time type check fails. In that case, {@code unwrap} returns an |
| 181 |
* innocuous string, or, if assertions are enabled, throws |
| 182 |
* {@code goog.asserts.AssertionError}. |
| 183 |
*/ |
| 184 |
goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) { |
| 185 |
// Perform additional Run-time type-checking to ensure that |
| 186 |
// trustedResourceUrl is indeed an instance of the expected type. This |
| 187 |
// provides some additional protection against security bugs due to |
| 188 |
// application code that disables type checks. |
| 189 |
// Specifically, the following checks are performed: |
| 190 |
// 1. The object is an instance of the expected type. |
| 191 |
// 2. The object is not an instance of a subclass. |
| 192 |
// 3. The object carries a type marker for the expected type. "Faking" an |
| 193 |
// object requires a reference to the type marker, which has names intended |
| 194 |
// to stand out in code reviews. |
| 195 |
if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl && |
| 196 |
trustedResourceUrl.constructor === goog.html.TrustedResourceUrl && |
| 197 |
trustedResourceUrl |
| 198 |
.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === |
| 199 |
goog.html.TrustedResourceUrl |
| 200 |
.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { |
| 201 |
return trustedResourceUrl |
| 202 |
.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; |
| 203 |
} else { |
| 204 |
goog.asserts.fail('expected object of type TrustedResourceUrl, got \'' + |
| 205 |
trustedResourceUrl + '\' of type ' + goog.typeOf(trustedResourceUrl)); |
| 206 |
return 'type_error:TrustedResourceUrl'; |
| 207 |
} |
| 208 |
}; |
| 209 |
|
| 210 |
|
| 211 |
/** |
| 212 |
* Creates a TrustedResourceUrl from a format string and arguments. |
| 213 |
* |
| 214 |
* The arguments for interpolation into the format string map labels to values. |
| 215 |
* Values of type `goog.string.Const` are interpolated without modifcation. |
| 216 |
* Values of other types are cast to string and encoded with |
| 217 |
* encodeURIComponent. |
| 218 |
* |
| 219 |
* `%{<label>}` markers are used in the format string to indicate locations |
| 220 |
* to be interpolated with the valued mapped to the given label. `<label>` |
| 221 |
* must contain only alphanumeric and `_` characters. |
| 222 |
* |
| 223 |
* The format string must start with one of the following: |
| 224 |
* - `https://<origin>/` |
| 225 |
* - `//<origin>/` |
| 226 |
* - `/<pathStart>` |
| 227 |
* - `about:blank` |
| 228 |
* |
| 229 |
* `<origin>` must contain only alphanumeric or any of the following: `-.:[]`. |
| 230 |
* `<pathStart>` is any character except `/` and `\`. |
| 231 |
* |
| 232 |
* Example usage: |
| 233 |
* |
| 234 |
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from( |
| 235 |
* 'https://www.google.com/search?q=%{query}'), {'query': searchTerm}); |
| 236 |
* |
| 237 |
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from( |
| 238 |
* '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), { |
| 239 |
* 'videoId': videoId, |
| 240 |
* 'autoplay': opt_autoplay ? |
| 241 |
* goog.string.Const.from('&autoplay=1') : goog.string.Const.EMPTY |
| 242 |
* }); |
| 243 |
* |
| 244 |
* While this function can be used to create a TrustedResourceUrl from only |
| 245 |
* constants, fromConstant() and fromConstants() are generally preferable for |
| 246 |
* that purpose. |
| 247 |
* |
| 248 |
* @param {!goog.string.Const} format The format string. |
| 249 |
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping |
| 250 |
* of labels to values to be interpolated into the format string. |
| 251 |
* goog.string.Const values are interpolated without encoding. |
| 252 |
* @return {!goog.html.TrustedResourceUrl} |
| 253 |
* @throws {!Error} On an invalid format string or if a label used in the |
| 254 |
* the format string is not present in args. |
| 255 |
*/ |
| 256 |
goog.html.TrustedResourceUrl.format = function(format, args) { |
| 257 |
var formatStr = goog.string.Const.unwrap(format); |
| 258 |
if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) { |
| 259 |
throw new Error('Invalid TrustedResourceUrl format: ' + formatStr); |
| 260 |
} |
| 261 |
var result = formatStr.replace( |
| 262 |
goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) { |
| 263 |
if (!Object.prototype.hasOwnProperty.call(args, id)) { |
| 264 |
throw new Error( |
| 265 |
'Found marker, "' + id + '", in format string, "' + formatStr + |
| 266 |
'", but no valid label mapping found ' + |
| 267 |
'in args: ' + JSON.stringify(args)); |
| 268 |
} |
| 269 |
var arg = args[id]; |
| 270 |
if (arg instanceof goog.string.Const) { |
| 271 |
return goog.string.Const.unwrap(arg); |
| 272 |
} else { |
| 273 |
return encodeURIComponent(String(arg)); |
| 274 |
} |
| 275 |
}); |
| 276 |
return goog.html.TrustedResourceUrl |
| 277 |
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result); |
| 278 |
}; |
| 279 |
|
| 280 |
|
| 281 |
/** |
| 282 |
* @private @const {!RegExp} |
| 283 |
*/ |
| 284 |
goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g; |
| 285 |
|
| 286 |
|
| 287 |
/** |
| 288 |
* The URL must be absolute, scheme-relative or path-absolute. So it must |
| 289 |
* start with: |
| 290 |
* - https:// followed by allowed origin characters. |
| 291 |
* - // followed by allowed origin characters. |
| 292 |
* - / not followed by / or \. There will only be an absolute path. |
| 293 |
* |
| 294 |
* Based on |
| 295 |
* https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing |
| 296 |
* an initial / which is not followed by another / or \ will end up in the "path |
| 297 |
* state" and from there it can only go to "fragment state" and "query state". |
| 298 |
* |
| 299 |
* We don't enforce a well-formed domain name. So '.' or '1.2' are valid. |
| 300 |
* That's ok because the origin comes from a compile-time constant. |
| 301 |
* |
| 302 |
* A regular expression is used instead of goog.uri for several reasons: |
| 303 |
* - Strictness. E.g. we don't want any userinfo component and we don't |
| 304 |
* want '/./, nor \' in the first path component. |
| 305 |
* - Small trusted base. goog.uri is generic and might need to change, |
| 306 |
* reasoning about all the ways it can parse a URL now and in the future |
| 307 |
* is error-prone. |
| 308 |
* - Code size. We expect many calls to .format(), many of which might |
| 309 |
* not be using goog.uri. |
| 310 |
* - Simplicity. Using goog.uri would likely not result in simpler nor shorter |
| 311 |
* code. |
| 312 |
* @private @const {!RegExp} |
| 313 |
*/ |
| 314 |
goog.html.TrustedResourceUrl.BASE_URL_ = |
| 315 |
/^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank(#|$)/i; |
| 316 |
|
| 317 |
|
| 318 |
/** |
| 319 |
* Formats the URL same as TrustedResourceUrl.format and then adds extra URL |
| 320 |
* parameters. |
| 321 |
* |
| 322 |
* Example usage: |
| 323 |
* |
| 324 |
* // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and |
| 325 |
* // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc' |
| 326 |
* // and opt_autoplay=undefined. |
| 327 |
* var url = goog.html.TrustedResourceUrl.formatWithParams( |
| 328 |
* goog.string.Const.from('//www.youtube.com/v/%{videoId}'), |
| 329 |
* {'videoId': videoId}, |
| 330 |
* {'autoplay': opt_autoplay}); |
| 331 |
* |
| 332 |
* @param {!goog.string.Const} format The format string. |
| 333 |
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping |
| 334 |
* of labels to values to be interpolated into the format string. |
| 335 |
* goog.string.Const values are interpolated without encoding. |
| 336 |
* @param {!Object<string, *>} params Parameters to add to URL. Parameters with |
| 337 |
* value {@code null} or {@code undefined} are skipped. Both keys and values |
| 338 |
* are encoded. If the value is an array then the same parameter is added |
| 339 |
* for every element in the array. Note that JavaScript doesn't guarantee |
| 340 |
* the order of values in an object which might result in non-deterministic |
| 341 |
* order of the parameters. However, browsers currently preserve the order. |
| 342 |
* @return {!goog.html.TrustedResourceUrl} |
| 343 |
* @throws {!Error} On an invalid format string or if a label used in the |
| 344 |
* the format string is not present in args. |
| 345 |
*/ |
| 346 |
goog.html.TrustedResourceUrl.formatWithParams = function(format, args, params) { |
| 347 |
var url = goog.html.TrustedResourceUrl.format(format, args); |
| 348 |
return url.cloneWithParams(params); |
| 349 |
}; |
| 350 |
|
| 351 |
|
| 352 |
/** |
| 353 |
* Creates a TrustedResourceUrl object from a compile-time constant string. |
| 354 |
* |
| 355 |
* Compile-time constant strings are inherently program-controlled and hence |
| 356 |
* trusted. |
| 357 |
* |
| 358 |
* @param {!goog.string.Const} url A compile-time-constant string from which to |
| 359 |
* create a TrustedResourceUrl. |
| 360 |
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object |
| 361 |
* initialized to {@code url}. |
| 362 |
*/ |
| 363 |
goog.html.TrustedResourceUrl.fromConstant = function(url) { |
| 364 |
return goog.html.TrustedResourceUrl |
| 365 |
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse( |
| 366 |
goog.string.Const.unwrap(url)); |
| 367 |
}; |
| 368 |
|
| 369 |
|
| 370 |
/** |
| 371 |
* Creates a TrustedResourceUrl object from a compile-time constant strings. |
| 372 |
* |
| 373 |
* Compile-time constant strings are inherently program-controlled and hence |
| 374 |
* trusted. |
| 375 |
* |
| 376 |
* @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from |
| 377 |
* which to create a TrustedResourceUrl. |
| 378 |
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object |
| 379 |
* initialized to concatenation of {@code parts}. |
| 380 |
*/ |
| 381 |
goog.html.TrustedResourceUrl.fromConstants = function(parts) { |
| 382 |
var unwrapped = ''; |
| 383 |
for (var i = 0; i < parts.length; i++) { |
| 384 |
unwrapped += goog.string.Const.unwrap(parts[i]); |
| 385 |
} |
| 386 |
return goog.html.TrustedResourceUrl |
| 387 |
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped); |
| 388 |
}; |
| 389 |
|
| 390 |
|
| 391 |
/** |
| 392 |
* Type marker for the TrustedResourceUrl type, used to implement additional |
| 393 |
* run-time type checking. |
| 394 |
* @const {!Object} |
| 395 |
* @private |
| 396 |
*/ |
| 397 |
goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; |
| 398 |
|
| 399 |
|
| 400 |
/** |
| 401 |
* Package-internal utility method to create TrustedResourceUrl instances. |
| 402 |
* |
| 403 |
* @param {string} url The string to initialize the TrustedResourceUrl object |
| 404 |
* with. |
| 405 |
* @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl |
| 406 |
* object. |
| 407 |
* @package |
| 408 |
*/ |
| 409 |
goog.html.TrustedResourceUrl |
| 410 |
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) { |
| 411 |
var trustedResourceUrl = new goog.html.TrustedResourceUrl(); |
| 412 |
trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = |
| 413 |
url; |
| 414 |
return trustedResourceUrl; |
| 415 |
}; |