trustedresourceurl.js 15 KB

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