Debian Codegraph @

closure-library/closure/goog/html/safeurl.js

raw
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 SafeUrl type and its builders.
17 *
18 * TODO(xtof): Link to document stating type contract.
19 */
20
21 goog.provide('goog.html.SafeUrl');
22
23 goog.require('goog.asserts');
24 goog.require('goog.fs.url');
25 goog.require('goog.html.TrustedResourceUrl');
26 goog.require('goog.i18n.bidi.Dir');
27 goog.require('goog.i18n.bidi.DirectionalString');
28 goog.require('goog.string');
29 goog.require('goog.string.Const');
30 goog.require('goog.string.TypedString');
31
32
33
34 /**
35 * A string that is safe to use in URL context in DOM APIs and HTML documents.
36 *
37 * A SafeUrl is a string-like object that carries the security type contract
38 * that its value as a string will not cause untrusted script execution
39 * when evaluated as a hyperlink URL in a browser.
40 *
41 * Values of this type are guaranteed to be safe to use in URL/hyperlink
42 * contexts, such as assignment to URL-valued DOM properties, in the sense that
43 * the use will not result in a Cross-Site-Scripting vulnerability. Similarly,
44 * SafeUrls can be interpolated into the URL context of an HTML template (e.g.,
45 * inside a href attribute). However, appropriate HTML-escaping must still be
46 * applied.
47 *
48 * Note that, as documented in {@code goog.html.SafeUrl.unwrap}, this type's
49 * contract does not guarantee that instances are safe to interpolate into HTML
50 * without appropriate escaping.
51 *
52 * Note also that this type's contract does not imply any guarantees regarding
53 * the resource the URL refers to. In particular, SafeUrls are <b>not</b>
54 * safe to use in a context where the referred-to resource is interpreted as
55 * trusted code, e.g., as the src of a script tag.
56 *
57 * Instances of this type must be created via the factory methods
58 * ({@code goog.html.SafeUrl.fromConstant}, {@code goog.html.SafeUrl.sanitize}),
59 * etc and not by invoking its constructor. The constructor intentionally
60 * takes no parameters and the type is immutable; hence only a default instance
61 * corresponding to the empty string can be obtained via constructor invocation.
62 *
63 * @see goog.html.SafeUrl#fromConstant
64 * @see goog.html.SafeUrl#from
65 * @see goog.html.SafeUrl#sanitize
66 * @constructor
67 * @final
68 * @struct
69 * @implements {goog.i18n.bidi.DirectionalString}
70 * @implements {goog.string.TypedString}
71 */
72 goog.html.SafeUrl = function() {
73 /**
74 * The contained value of this SafeUrl. The field has a purposely ugly
75 * name to make (non-compiled) code that attempts to directly access this
76 * field stand out.
77 * @private {string}
78 */
79 this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';
80
81 /**
82 * A type marker used to implement additional run-time type checking.
83 * @see goog.html.SafeUrl#unwrap
84 * @const {!Object}
85 * @private
86 */
87 this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
88 goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
89 };
90
91
92 /**
93 * The innocuous string generated by goog.html.SafeUrl.sanitize when passed
94 * an unsafe URL.
95 *
96 * about:invalid is registered in
97 * http://www.w3.org/TR/css3-values/#about-invalid.
98 * http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to
99 * contain a fragment, which is not to be considered when determining if an
100 * about URL is well-known.
101 *
102 * Using about:invalid seems preferable to using a fixed data URL, since
103 * browsers might choose to not report CSP violations on it, as legitimate
104 * CSS function calls to attr() can result in this URL being produced. It is
105 * also a standard URL which matches exactly the semantics we need:
106 * "The about:invalid URI references a non-existent document with a generic
107 * error condition. It can be used when a URI is necessary, but the default
108 * value shouldn't be resolveable as any type of document".
109 *
110 * @const {string}
111 */
112 goog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez';
113
114
115 /**
116 * @override
117 * @const
118 */
119 goog.html.SafeUrl.prototype.implementsGoogStringTypedString = true;
120
121
122 /**
123 * Returns this SafeUrl's value a string.
124 *
125 * IMPORTANT: In code where it is security relevant that an object's type is
126 * indeed {@code SafeUrl}, use {@code goog.html.SafeUrl.unwrap} instead of this
127 * method. If in doubt, assume that it's security relevant. In particular, note
128 * that goog.html functions which return a goog.html type do not guarantee that
129 * the returned instance is of the right type. For example:
130 *
131 * <pre>
132 * var fakeSafeHtml = new String('fake');
133 * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
134 * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
135 * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
136 * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
137 * // goog.html.SafeHtml.
138 * </pre>
139 *
140 * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
141 * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
142 * be appropriately escaped before embedding in a HTML document. Note that the
143 * required escaping is context-sensitive (e.g. a different escaping is
144 * required for embedding a URL in a style property within a style
145 * attribute, as opposed to embedding in a href attribute).
146 *
147 * @see goog.html.SafeUrl#unwrap
148 * @override
149 */
150 goog.html.SafeUrl.prototype.getTypedStringValue = function() {
151 return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
152 };
153
154
155 /**
156 * @override
157 * @const
158 */
159 goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true;
160
161
162 /**
163 * Returns this URLs directionality, which is always {@code LTR}.
164 * @override
165 */
166 goog.html.SafeUrl.prototype.getDirection = function() {
167 return goog.i18n.bidi.Dir.LTR;
168 };
169
170
171 if (goog.DEBUG) {
172 /**
173 * Returns a debug string-representation of this value.
174 *
175 * To obtain the actual string value wrapped in a SafeUrl, use
176 * {@code goog.html.SafeUrl.unwrap}.
177 *
178 * @see goog.html.SafeUrl#unwrap
179 * @override
180 */
181 goog.html.SafeUrl.prototype.toString = function() {
182 return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +
183 '}';
184 };
185 }
186
187
188 /**
189 * Performs a runtime check that the provided object is indeed a SafeUrl
190 * object, and returns its value.
191 *
192 * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
193 * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
194 * be appropriately escaped before embedding in a HTML document. Note that the
195 * required escaping is context-sensitive (e.g. a different escaping is
196 * required for embedding a URL in a style property within a style
197 * attribute, as opposed to embedding in a href attribute).
198 *
199 * @param {!goog.html.SafeUrl} safeUrl The object to extract from.
200 * @return {string} The SafeUrl object's contained string, unless the run-time
201 * type check fails. In that case, {@code unwrap} returns an innocuous
202 * string, or, if assertions are enabled, throws
203 * {@code goog.asserts.AssertionError}.
204 */
205 goog.html.SafeUrl.unwrap = function(safeUrl) {
206 // Perform additional Run-time type-checking to ensure that safeUrl is indeed
207 // an instance of the expected type. This provides some additional protection
208 // against security bugs due to application code that disables type checks.
209 // Specifically, the following checks are performed:
210 // 1. The object is an instance of the expected type.
211 // 2. The object is not an instance of a subclass.
212 // 3. The object carries a type marker for the expected type. "Faking" an
213 // object requires a reference to the type marker, which has names intended
214 // to stand out in code reviews.
215 if (safeUrl instanceof goog.html.SafeUrl &&
216 safeUrl.constructor === goog.html.SafeUrl &&
217 safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
218 goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
219 return safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
220 } else {
221 goog.asserts.fail('expected object of type SafeUrl, got \'' +
222 safeUrl + '\' of type ' + goog.typeOf(safeUrl));
223 return 'type_error:SafeUrl';
224 }
225 };
226
227
228 /**
229 * Creates a SafeUrl object from a compile-time constant string.
230 *
231 * Compile-time constant strings are inherently program-controlled and hence
232 * trusted.
233 *
234 * @param {!goog.string.Const} url A compile-time-constant string from which to
235 * create a SafeUrl.
236 * @return {!goog.html.SafeUrl} A SafeUrl object initialized to {@code url}.
237 */
238 goog.html.SafeUrl.fromConstant = function(url) {
239 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
240 goog.string.Const.unwrap(url));
241 };
242
243
244 /**
245 * A pattern that matches Blob or data types that can have SafeUrls created
246 * from URL.createObjectURL(blob) or via a data: URI.
247 * @const
248 * @private
249 */
250 goog.html.SAFE_MIME_TYPE_PATTERN_ = new RegExp(
251 // Note: Due to content-sniffing concerns, only add MIME types for
252 // media formats.
253 '^(?:audio/(?:3gpp|3gpp2|aac|midi|mp4|mpeg|ogg|x-m4a|x-wav|webm)|' +
254 'image/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|' +
255 // TODO(b/68188949): Due to content-sniffing concerns, text/csv should
256 // be removed from the whitelist.
257 'text/csv|' +
258 'video/(?:mpeg|mp4|ogg|webm))$',
259 'i');
260
261
262 /**
263 * Creates a SafeUrl wrapping a blob URL for the given {@code blob}.
264 *
265 * The blob URL is created with {@code URL.createObjectURL}. If the MIME type
266 * for {@code blob} is not of a known safe audio, image or video MIME type,
267 * then the SafeUrl will wrap {@link #INNOCUOUS_STRING}.
268 *
269 * @see http://www.w3.org/TR/FileAPI/#url
270 * @param {!Blob} blob
271 * @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped
272 * as a SafeUrl.
273 */
274 goog.html.SafeUrl.fromBlob = function(blob) {
275 var url = goog.html.SAFE_MIME_TYPE_PATTERN_.test(blob.type) ?
276 goog.fs.url.createObjectUrl(blob) :
277 goog.html.SafeUrl.INNOCUOUS_STRING;
278 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
279 };
280
281
282 /**
283 * Matches a base-64 data URL, with the first match group being the MIME type.
284 * @const
285 * @private
286 */
287 goog.html.DATA_URL_PATTERN_ = /^data:([^;,]*);base64,[a-z0-9+\/]+=*$/i;
288
289
290 /**
291 * Creates a SafeUrl wrapping a data: URL, after validating it matches a
292 * known-safe audio, image or video MIME type.
293 *
294 * @param {string} dataUrl A valid base64 data URL with one of the whitelisted
295 * audio, image or video MIME types.
296 * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}
297 * wrapped as a SafeUrl if it does not pass.
298 */
299 goog.html.SafeUrl.fromDataUrl = function(dataUrl) {
300 // There's a slight risk here that a browser sniffs the content type if it
301 // doesn't know the MIME type and executes HTML within the data: URL. For this
302 // to cause XSS it would also have to execute the HTML in the same origin
303 // of the page with the link. It seems unlikely that both of these will
304 // happen, particularly in not really old IEs.
305 var match = dataUrl.match(goog.html.DATA_URL_PATTERN_);
306 var valid = match && goog.html.SAFE_MIME_TYPE_PATTERN_.test(match[1]);
307 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
308 valid ? dataUrl : goog.html.SafeUrl.INNOCUOUS_STRING);
309 };
310
311
312 /**
313 * Creates a SafeUrl wrapping a tel: URL.
314 *
315 * @param {string} telUrl A tel URL.
316 * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}
317 * wrapped as a SafeUrl if it does not pass.
318 */
319 goog.html.SafeUrl.fromTelUrl = function(telUrl) {
320 // There's a risk that a tel: URL could immediately place a call once
321 // clicked, without requiring user confirmation. For that reason it is
322 // handled in this separate function.
323 if (!goog.string.caseInsensitiveStartsWith(telUrl, 'tel:')) {
324 telUrl = goog.html.SafeUrl.INNOCUOUS_STRING;
325 }
326 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
327 telUrl);
328 };
329
330
331 /**
332 * Creates a SafeUrl from TrustedResourceUrl. This is safe because
333 * TrustedResourceUrl is more tightly restricted than SafeUrl.
334 *
335 * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl
336 * @return {!goog.html.SafeUrl}
337 */
338 goog.html.SafeUrl.fromTrustedResourceUrl = function(trustedResourceUrl) {
339 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
340 goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl));
341 };
342
343
344 /**
345 * A pattern that recognizes a commonly useful subset of URLs that satisfy
346 * the SafeUrl contract.
347 *
348 * This regular expression matches a subset of URLs that will not cause script
349 * execution if used in URL context within a HTML document. Specifically, this
350 * regular expression matches if (comment from here on and regex copied from
351 * Soy's EscapingConventions):
352 * (1) Either a protocol in a whitelist (http, https, mailto or ftp).
353 * (2) or no protocol. A protocol must be followed by a colon. The below
354 * allows that by allowing colons only after one of the characters [/?#].
355 * A colon after a hash (#) must be in the fragment.
356 * Otherwise, a colon after a (?) must be in a query.
357 * Otherwise, a colon after a single solidus (/) must be in a path.
358 * Otherwise, a colon after a double solidus (//) must be in the authority
359 * (before port).
360 *
361 * @private
362 * @const {!RegExp}
363 */
364 goog.html.SAFE_URL_PATTERN_ =
365 /^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;
366
367
368 /**
369 * Creates a SafeUrl object from {@code url}. If {@code url} is a
370 * goog.html.SafeUrl then it is simply returned. Otherwise the input string is
371 * validated to match a pattern of commonly used safe URLs.
372 *
373 * {@code url} may be a URL with the http, https, mailto or ftp scheme,
374 * or a relative URL (i.e., a URL without a scheme; specifically, a
375 * scheme-relative, absolute-path-relative, or path-relative URL).
376 *
377 * @see http://url.spec.whatwg.org/#concept-relative-url
378 * @param {string|!goog.string.TypedString} url The URL to validate.
379 * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.
380 */
381 goog.html.SafeUrl.sanitize = function(url) {
382 if (url instanceof goog.html.SafeUrl) {
383 return url;
384 } else if (url.implementsGoogStringTypedString) {
385 url = url.getTypedStringValue();
386 } else {
387 url = String(url);
388 }
389 if (!goog.html.SAFE_URL_PATTERN_.test(url)) {
390 url = goog.html.SafeUrl.INNOCUOUS_STRING;
391 }
392 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
393 };
394
395 /**
396 * Creates a SafeUrl object from {@code url}. If {@code url} is a
397 * goog.html.SafeUrl then it is simply returned. Otherwise the input string is
398 * validated to match a pattern of commonly used safe URLs.
399 *
400 * {@code url} may be a URL with the http, https, mailto or ftp scheme,
401 * or a relative URL (i.e., a URL without a scheme; specifically, a
402 * scheme-relative, absolute-path-relative, or path-relative URL).
403 *
404 * This function asserts (using goog.asserts) that the URL matches this pattern.
405 * If it does not, in addition to failing the assert, an innocous URL will be
406 * returned.
407 *
408 * @see http://url.spec.whatwg.org/#concept-relative-url
409 * @param {string|!goog.string.TypedString} url The URL to validate.
410 * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.
411 */
412 goog.html.SafeUrl.sanitizeAssertUnchanged = function(url) {
413 if (url instanceof goog.html.SafeUrl) {
414 return url;
415 } else if (url.implementsGoogStringTypedString) {
416 url = url.getTypedStringValue();
417 } else {
418 url = String(url);
419 }
420 if (!goog.asserts.assert(goog.html.SAFE_URL_PATTERN_.test(url))) {
421 url = goog.html.SafeUrl.INNOCUOUS_STRING;
422 }
423 return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
424 };
425
426
427
428 /**
429 * Type marker for the SafeUrl type, used to implement additional run-time
430 * type checking.
431 * @const {!Object}
432 * @private
433 */
434 goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
435
436
437 /**
438 * Package-internal utility method to create SafeUrl instances.
439 *
440 * @param {string} url The string to initialize the SafeUrl object with.
441 * @return {!goog.html.SafeUrl} The initialized SafeUrl object.
442 * @package
443 */
444 goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function(
445 url) {
446 var safeUrl = new goog.html.SafeUrl();
447 safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = url;
448 return safeUrl;
449 };
450
451
452 /**
453 * A SafeUrl corresponding to the special about:blank url.
454 * @const {!goog.html.SafeUrl}
455 */
456 goog.html.SafeUrl.ABOUT_BLANK =
457 goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
458 'about:blank');