diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2020-09-23 09:09:45 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2020-09-23 09:09:45 +0300 |
commit | 86fa823611b3ab5701d144aca1c57c51b4af25d5 (patch) | |
tree | ae6b2858c282d6f0cd2763135ef32f564c9295e8 /app/assets/javascripts/lib | |
parent | 8007620dc7216ff2b9e7dde0aa88e6f47fc433e7 (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'app/assets/javascripts/lib')
-rw-r--r-- | app/assets/javascripts/lib/dompurify.js | 53 | ||||
-rw-r--r-- | app/assets/javascripts/lib/utils/highlight.js | 2 |
2 files changed, 54 insertions, 1 deletions
diff --git a/app/assets/javascripts/lib/dompurify.js b/app/assets/javascripts/lib/dompurify.js new file mode 100644 index 00000000000..d9ea57fbbce --- /dev/null +++ b/app/assets/javascripts/lib/dompurify.js @@ -0,0 +1,53 @@ +import { sanitize as dompurifySanitize, addHook } from 'dompurify'; +import { getBaseURL, relativePathToAbsolute } from '~/lib/utils/url_utility'; + +// Safely allow SVG <use> tags + +const defaultConfig = { + ADD_TAGS: ['use'], +}; + +// Only icons urls from `gon` are allowed +const getAllowedIconUrls = (gon = window.gon) => + [gon.sprite_file_icons, gon.sprite_icons].filter(Boolean); + +const isUrlAllowed = url => getAllowedIconUrls().some(allowedUrl => url.startsWith(allowedUrl)); + +const isHrefSafe = url => + isUrlAllowed(url) || isUrlAllowed(relativePathToAbsolute(url, getBaseURL())); + +const removeUnsafeHref = (node, attr) => { + if (!node.hasAttribute(attr)) { + return; + } + + if (!isHrefSafe(node.getAttribute(attr))) { + node.removeAttribute(attr); + } +}; + +/** + * Sanitize icons' <use> tag attributes, to safely include + * svgs such as in: + * + * <svg viewBox="0 0 100 100"> + * <use href="/assets/icons-xxx.svg#icon_name"></use> + * </svg> + * + * @param {Object} node - Node to sanitize + */ +const sanitizeSvgIcon = node => { + removeUnsafeHref(node, 'href'); + + // Note: `xlink:href` is deprecated, but still in use + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href + removeUnsafeHref(node, 'xlink:href'); +}; + +addHook('afterSanitizeAttributes', node => { + if (node.tagName.toLowerCase() === 'use') { + sanitizeSvgIcon(node); + } +}); + +export const sanitize = (val, config = defaultConfig) => dompurifySanitize(val, config); diff --git a/app/assets/javascripts/lib/utils/highlight.js b/app/assets/javascripts/lib/utils/highlight.js index 32553af9af3..8fa8af670b3 100644 --- a/app/assets/javascripts/lib/utils/highlight.js +++ b/app/assets/javascripts/lib/utils/highlight.js @@ -1,5 +1,5 @@ import fuzzaldrinPlus from 'fuzzaldrin-plus'; -import { sanitize } from 'dompurify'; +import { sanitize } from '~/lib/dompurify'; /** * Wraps substring matches with HTML `<span>` elements. |