Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Escape HTML in media title and creator (#2852)

Dhruv Bhanushalidb6e57256a49
diff --git a/frontend/src/utils/attribution-html.ts b/frontend/src/utils/attribution-html.ts
index 5857fabb8..4c0222bd7 100644
--- a/frontend/src/utils/attribution-html.ts
+++ b/frontend/src/utils/attribution-html.ts
@@ -18,6 +18,21 @@ import type VueI18n from "vue-i18n"
/* Helper functions */
+/**
+ * Escape characters that have special meaning in HTML to break script injection
+ * attacks.
+ *
+ * @param unsafe - the unsafe text to sanitise
+ * @returns the sanitised text content
+ */
+const escapeHtml = (unsafe: string) =>
+ unsafe
+ .replace(/&/g, "&")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#039;")
+
/**
* Create an HTML tag with the given name, attributes and children.
*
@@ -163,6 +178,7 @@ export const getAttribution = (
/* Title */
let title = mediaItem.originalTitle || tFn("genericTitle")
+ if (!isPlaintext) title = escapeHtml(title)
if (!isPlaintext && mediaItem.foreign_landing_url)
title = extLink(mediaItem.foreign_landing_url, title)
if (mediaItem.originalTitle) title = tFn("actualTitle", { title })
@@ -204,6 +220,7 @@ export const getAttribution = (
if (mediaItem.creator) {
let creator = mediaItem.creator
+ if (!isPlaintext) creator = escapeHtml(creator)
if (!isPlaintext && mediaItem.creator_url)
creator = extLink(mediaItem.creator_url, creator)
attributionParts.creator = tFn("creatorText", {
diff --git a/frontend/test/unit/specs/utils/attribution-html.spec.ts b/frontend/test/unit/specs/utils/attribution-html.spec.ts
index 656abfdd7..62cded6bc 100644
--- a/frontend/test/unit/specs/utils/attribution-html.spec.ts
+++ b/frontend/test/unit/specs/utils/attribution-html.spec.ts
@@ -62,6 +62,18 @@ describe("getAttribution", () => {
expect(attrText).toContain(expectation)
})
+ it("escapes embedded HTML", () => {
+ const mediaItemWithHtml = {
+ ...mediaItem,
+ originalTitle: '<script>console.log("HELLO");</script>',
+ }
+ const attrText = getAttribution(mediaItemWithHtml, i18n)
+ const expectation =
+ "&lt;script&gt;console.log(&quot;HELLO&quot;);&lt;/script&gt;"
+ expect(attrText).toContain(expectation)
+ expect(attrText).not.toContain(mediaItemWithHtml.originalTitle)
+ })
+
it("does not use anchors in plain-text mode", () => {
document.body.innerHTML = getAttribution(mediaItem, i18n)
expect(document.getElementsByTagName("a")).not.toHaveLength(0)