Skip to content

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

Build admin read-only field links from DOM nodes (#5627)

Konstantin Obenland639e92669e50
diff --git a/api/api/admin/media_report.py b/api/api/admin/media_report.py
index d8a2a2308..f93b63ac3 100644
--- a/api/api/admin/media_report.py
+++ b/api/api/admin/media_report.py
@@ -895,7 +895,7 @@ class MediaReportAdmin(admin.ModelAdmin):
@admin.display(description="Media obj")
def media_id(self, obj):
path = reverse(f"admin:api_{self.media_type}_change", args=(obj.media_obj.id,))
- return format_html(f'<a href="{path}">{obj.media_obj}</a>')
+ return format_html('<a href="{}">{}</a>', path, obj.media_obj)
###############
# Change view #
diff --git a/api/api/models/media.py b/api/api/models/media.py
index 694ac3a05..1c50e7379 100644
--- a/api/api/models/media.py
+++ b/api/api/models/media.py
@@ -254,7 +254,7 @@ class AbstractMediaReport(models.Model):
def url(self, request=None) -> str:
url = self.media_url(request)
- return format_html(f"<a href={url}>{url}</a>")
+ return format_html('<a href="{}">{}</a>', url, url)
@property
def is_pending(self) -> bool:
diff --git a/api/api/templates/admin/api/media/change_form.html b/api/api/templates/admin/api/media/change_form.html
index 3dea00a53..926deaae2 100644
--- a/api/api/templates/admin/api/media/change_form.html
+++ b/api/api/templates/admin/api/media/change_form.html
@@ -6,13 +6,28 @@
`TextField`s, they are not rendered as links in the Django Admin UI.
This script identifies `<div>`s containing links and converts them to
`<a>` tags.
+
+ The field text is rebuilt from text and anchor nodes rather than from an
+ HTML string, so the escaping Django applied when rendering the page is
+ preserved.
-->
<script>
document.addEventListener("DOMContentLoaded", function() {
+ const urlPattern = /(https?:\/\/\S+)/;
document.querySelectorAll("div.readonly").forEach(div => {
- if (div.textContent.match(/https?:\/\/\S+/)) {
- div.innerHTML = div.textContent.replace(/(https?:\/\/\S+)/g, '<a href="$1">$1</a>');
+ const parts = div.textContent.split(urlPattern);
+ if (parts.length === 1) {
+ return;
}
+ div.replaceChildren(...parts.map((part, index) => {
+ if (index % 2 === 0) {
+ return document.createTextNode(part);
+ }
+ const link = document.createElement("a");
+ link.href = part;
+ link.textContent = part;
+ return link;
+ }));
});
});
</script>
diff --git a/api/test/unit/admin/test_media_report.py b/api/test/unit/admin/test_media_report.py
index cb4ca175c..cd92021ac 100644
--- a/api/test/unit/admin/test_media_report.py
+++ b/api/test/unit/admin/test_media_report.py
@@ -1,8 +1,16 @@
from unittest import mock
+from django.urls import reverse
+
import pytest
-from api.admin.media_report import _non_production_deferred, _production_deferred
+from api.admin.media_report import (
+ ImageReportAdmin,
+ _non_production_deferred,
+ _production_deferred,
+)
+from api.admin.site import openverse_admin
+from api.models import ImageReport
@pytest.mark.parametrize(
@@ -21,3 +29,16 @@ def test_production_deferred(values, environment, prod_expected, non_prod_expect
non_prod_deferred = _non_production_deferred(*values)
assert prod_deferred == prod_expected
assert non_prod_deferred == non_prod_expected
+
+
+def test_media_id_escapes_media_representation():
+ model_admin = ImageReportAdmin(ImageReport, openverse_admin)
+ report = mock.MagicMock()
+ report.media_obj.id = 1
+ report.media_obj.__str__.return_value = "<b>Image</b>"
+
+ html = model_admin.media_id(report)
+
+ assert f'href="{reverse("admin:api_image_change", args=(1,))}"' in html
+ assert "&lt;b&gt;Image&lt;/b&gt;" in html
+ assert "<b>" not in html
diff --git a/api/test/unit/templates/test_admin_media_change_form.py b/api/test/unit/templates/test_admin_media_change_form.py
new file mode 100644
index 000000000..4f9044b6c
--- /dev/null
+++ b/api/test/unit/templates/test_admin_media_change_form.py
@@ -0,0 +1,19 @@
+import re
+
+from django.template.loader import get_template
+
+
+HTML_STRING_SINKS = re.compile(
+ r"innerHTML|outerHTML|insertAdjacentHTML|document\.write"
+)
+
+
+def test_change_form_script_keeps_field_text_as_text():
+ """
+ The script that turns URLs into links must build DOM nodes from the field
+ text so that the escaping applied by the server is preserved.
+ """
+
+ source = get_template("admin/api/media/change_form.html").template.source
+
+ assert not HTML_STRING_SINKS.search(source)