Skip to content

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

Route external link hrefs through a shared URL helper (#5615)

Konstantin Obenland8323a34babec
diff --git a/frontend/shared/utils/attribution-html.ts b/frontend/shared/utils/attribution-html.ts
index b1e825ad1..0d87a27a4 100644
--- a/frontend/shared/utils/attribution-html.ts
+++ b/frontend/shared/utils/attribution-html.ts
@@ -11,6 +11,7 @@ import {
getFullLicenseName,
isPublicDomain,
} from "#shared/utils/license"
+import { sanitizeHref } from "#shared/utils/sanitize-href"
import type { Media } from "#shared/types/media"
import type { Composer } from "vue-i18n"
@@ -143,29 +144,6 @@ const licenseElementImg = (licenseElement: LicenseElement): string => {
})
}
-/**
- * Drop URLs with a non-http(s)/mailto scheme to `about:blank`, so a
- * `javascript:` or `data:` URL can't yield an executable link. Escaping the
- * attribute value does not stop these, as they contain nothing to escape.
- *
- * @param href - the untrusted URL to sanitise
- * @returns the URL if its scheme is safe, otherwise `about:blank`
- */
-const sanitizeHref = (href: string): string => {
- // Strip the C0 controls and spaces a browser ignores when parsing, else `\x01javascript:` or `java\tscript:` evades the check but still runs.
- const stripped = Array.from(href)
- .filter((char) => (char.codePointAt(0) ?? 0) > 0x20)
- .join("")
- const scheme = stripped.match(/^([a-z][a-z0-9+.-]*):/i)
- if (
- scheme &&
- !["http", "https", "mailto"].includes(scheme[1].toLowerCase())
- ) {
- return "about:blank"
- }
- return href
-}
-
/**
* Get an HTML `<a>` tag set up with the `target` and `rel` attributes.
*
diff --git a/frontend/shared/utils/sanitize-href.ts b/frontend/shared/utils/sanitize-href.ts
new file mode 100644
index 000000000..ceb8f7253
--- /dev/null
+++ b/frontend/shared/utils/sanitize-href.ts
@@ -0,0 +1,34 @@
+/**
+ * Shared URL-scheme guard for values rendered into anchor `href`/`to`
+ * attributes. Both the raw-HTML attribution builder and the shared `VLink`
+ * component route untrusted, provider-supplied URLs (e.g. `creator_url`,
+ * `foreign_landing_url`) through this, so a single allow-list governs every
+ * link sink.
+ */
+
+/**
+ * Schemes permitted to appear in a rendered link. Anything else with an
+ * explicit scheme (`javascript:`, `data:`, `vbscript:`, …) is neutralised.
+ */
+const ALLOWED_SCHEMES = ["http", "https", "mailto"]
+
+/**
+ * Drop URLs with a non-allow-listed scheme to `about:blank`, so a
+ * `javascript:` or `data:` URL can't yield an executable link. Escaping the
+ * attribute value does not stop these, as they contain nothing to escape.
+ * Scheme-relative and relative URLs (no explicit scheme) are left untouched.
+ *
+ * @param href - the untrusted URL to sanitise
+ * @returns the URL if its scheme is safe, otherwise `about:blank`
+ */
+export const sanitizeHref = (href: string): string => {
+ // Strip the C0 controls and spaces a browser ignores when parsing, else `\x01javascript:` or `java\tscript:` evades the check but still runs.
+ const stripped = Array.from(href)
+ .filter((char) => (char.codePointAt(0) ?? 0) > 0x20)
+ .join("")
+ const scheme = stripped.match(/^([a-z][a-z0-9+.-]*):/i)
+ if (scheme && !ALLOWED_SCHEMES.includes(scheme[1].toLowerCase())) {
+ return "about:blank"
+ }
+ return href
+}
diff --git a/frontend/src/components/VLink.vue b/frontend/src/components/VLink.vue
index 1af3ce1d2..cae1dc187 100644
--- a/frontend/src/components/VLink.vue
+++ b/frontend/src/components/VLink.vue
@@ -11,6 +11,7 @@
import { useNuxtApp } from "#imports"
import { computed, useAttrs } from "vue"
+import { sanitizeHref } from "#shared/utils/sanitize-href"
import { useAnalytics } from "~/composables/use-analytics"
import VIcon from "~/components/VIcon/VIcon.vue"
@@ -89,7 +90,8 @@ const to = computed(() => {
// Internal link should link to the localized page
return localePath(props.href) ?? props.href
} else {
- return props.href
+ // External href comes from untrusted sources (e.g. provider metadata); block script-bearing schemes.
+ return sanitizeHref(props.href)
}
}
// if href is undefined, return props that make the link disabled
diff --git a/frontend/test/unit/specs/components/v-link.spec.js b/frontend/test/unit/specs/components/v-link.spec.js
index ef62f03dd..4e005b34f 100644
--- a/frontend/test/unit/specs/components/v-link.spec.js
+++ b/frontend/test/unit/specs/components/v-link.spec.js
@@ -39,6 +39,33 @@ describe("VLink", () => {
expect(link.getAttribute("rel")).toEqual(rel)
}
)
+ it.each`
+ href | expected
+ ${"javascript:alert(1)"} | ${"about:blank"}
+ ${"JavaScript:alert(1)"} | ${"about:blank"}
+ ${"java\tscript:alert(1)"} | ${"about:blank"}
+ ${"data:text/html,<script>1</script>"} | ${"about:blank"}
+ ${"https://good.example.com/landing"} | ${"https://good.example.com/landing"}
+ `(
+ "neutralises script-bearing external hrefs ($href)",
+ async ({ href, expected }) => {
+ options.props = { href }
+ options.slots = { default: () => "Code is Poetry" }
+ await render(VLink, options)
+ const link = screen.getByRole("link")
+ expect(link.getAttribute("href")).toEqual(expected)
+ }
+ )
+ it("re-applies the guard when href changes from safe to unsafe", async () => {
+ options.props = { href: "https://good.example.com/landing" }
+ options.slots = { default: () => "Code is Poetry" }
+ const { rerender } = render(VLink, options)
+ expect(screen.getByRole("link").getAttribute("href")).toEqual(
+ "https://good.example.com/landing"
+ )
+ await rerender({ href: "javascript:alert(1)" })
+ expect(screen.getByRole("link").getAttribute("href")).toEqual("about:blank")
+ })
it.each`
href
${"/about"}
diff --git a/frontend/test/unit/specs/utils/sanitize-href.spec.ts b/frontend/test/unit/specs/utils/sanitize-href.spec.ts
new file mode 100644
index 000000000..698b5e0f2
--- /dev/null
+++ b/frontend/test/unit/specs/utils/sanitize-href.spec.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest"
+
+import { sanitizeHref } from "#shared/utils/sanitize-href"
+
+describe("sanitizeHref", () => {
+ it.each([
+ "javascript:alert(1)",
+ "JavaScript:alert(document.domain)",
+ "jAvAsCrIpT:alert(1)",
+ "java\tscript:alert(1)",
+ "java\nscript:alert(1)",
+ "java\rscript:alert(1)",
+ " javascript:alert(1)",
+ "data:text/html,<script>alert(1)</script>",
+ "vbscript:msgbox(1)",
+ ])("blanks script-bearing scheme %j", (href) => {
+ expect(sanitizeHref(href)).toBe("about:blank")
+ })
+
+ it.each([0, 1, 9, 31])(
+ "blanks a scheme hidden behind leading control char %i",
+ (code) => {
+ expect(
+ sanitizeHref(String.fromCharCode(code) + "javascript:alert(1)")
+ ).toBe("about:blank")
+ }
+ )
+
+ it.each([
+ "https://example.com/landing?a=1&b=2",
+ "http://example.com",
+ "mailto:[email protected]",
+ "/internal/path",
+ "//scheme-relative.example.com",
+ "relative/path",
+ // Encoded payloads are not decoded here — and the browser doesn't decode the scheme either, so they stay inert as-is rather than being wrongly rewritten.
+ "%6Aavascript:alert(1)",
+ "&#106;avascript:alert(1)",
+ ])("preserves safe or scheme-less URL %j", (href) => {
+ expect(sanitizeHref(href)).toBe(href)
+ })
+})