diff --git a/apps/core/templatetags/__init__.py b/apps/core/templatetags/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/apps/core/templatetags/safe_urls.py b/apps/core/templatetags/safe_urls.py
new file mode 100644
index 0000000..4fd13fa
--- /dev/null
+++ b/apps/core/templatetags/safe_urls.py
@@ -0,0 +1,12 @@
+from django import template
+
+from apps.core.urlutils import http_url_or_empty
+
+register = template.Library()
+
+
+@register.filter
+def safe_http_url(value):
+ """ "" unless value is an absolute http(s) URL — use before putting any
+ feed-supplied URL in an href (see apps.core.urlutils)."""
+ return http_url_or_empty(value)
diff --git a/apps/core/test_urlutils.py b/apps/core/test_urlutils.py
new file mode 100644
index 0000000..09d5ec5
--- /dev/null
+++ b/apps/core/test_urlutils.py
@@ -0,0 +1,44 @@
+import pytest
+from django.template import Context, Template
+
+from .urlutils import http_url_or_empty, resolve_http_url
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "javascript:alert(1)",
+ "JaVaScRiPt:alert(1)",
+ "java\tscript:alert(1)",
+ " javascript:alert(1)",
+ "data:text/html,",
+ "vbscript:msgbox(1)",
+ "file:///etc/passwd",
+ "ftp://example.com/feed.xml",
+ "//example.com/no-scheme",
+ "/relative/path",
+ "http://",
+ "",
+ None,
+ ],
+)
+def test_unsafe_or_non_absolute_urls_are_rejected(value):
+ assert http_url_or_empty(value) == ""
+
+
+@pytest.mark.parametrize("value", ["http://example.com/a", "https://example.com/a?b=1#c"])
+def test_http_and_https_urls_pass_through(value):
+ assert http_url_or_empty(value) == value
+
+
+def test_relative_links_resolve_against_the_feed_url_and_are_still_checked():
+ base = "https://blog.example.com/feed.xml"
+ assert resolve_http_url(base, "/2026/post") == "https://blog.example.com/2026/post"
+ assert resolve_http_url(base, "javascript:alert(1)") == ""
+ assert resolve_http_url(base, "https://other.example.com/x") == "https://other.example.com/x"
+
+
+def test_template_filter_blanks_unsafe_urls():
+ template = Template("{% load safe_urls %}[{{ url|safe_http_url }}]")
+ assert template.render(Context({"url": "javascript:alert(1)"})) == "[]"
+ assert template.render(Context({"url": "https://example.com/"})) == "[https://example.com/]"
diff --git a/apps/core/urlutils.py b/apps/core/urlutils.py
new file mode 100644
index 0000000..46d5106
--- /dev/null
+++ b/apps/core/urlutils.py
@@ -0,0 +1,30 @@
+from urllib.parse import urljoin, urlsplit
+
+ALLOWED_SCHEMES = {"http", "https"}
+
+
+def http_url_or_empty(value: str | None) -> str:
+ """The URL if it's an absolute http(s) URL, else "". Feed content is
+ untrusted: a link of "javascript:..." or "data:..." is harmless inside
+ an escaped attribute value but becomes script the moment someone
+ clicks it, so every URL we store from a feed or OPML file, and every
+ one we render as a link, goes through this. (urlsplit already ignores
+ the tab/newline tricks browsers also ignore inside a scheme.)"""
+ if not value:
+ return ""
+ value = value.strip()
+ try:
+ parts = urlsplit(value)
+ except ValueError:
+ return ""
+ if parts.scheme.lower() not in ALLOWED_SCHEMES or not parts.netloc:
+ return ""
+ return value
+
+
+def resolve_http_url(base: str, value: str | None) -> str:
+ """Like http_url_or_empty, but first resolves a relative link (feeds
+ often give "/2026/post") against the feed's own URL."""
+ if not value:
+ return ""
+ return http_url_or_empty(urljoin(base, value.strip()))
diff --git a/apps/feeds/forms.py b/apps/feeds/forms.py
index ff9af68..e85cc05 100644
--- a/apps/feeds/forms.py
+++ b/apps/feeds/forms.py
@@ -1,10 +1,21 @@
from django import forms
+from apps.core.urlutils import http_url_or_empty
+
from .models import Subscription
class AddFeedForm(forms.Form):
feed_url = forms.URLField(label="Feed URL", max_length=1000, assume_scheme="https")
+
+ def clean_feed_url(self):
+ # URLField also accepts ftp:// and ftps://; feeds are only ever
+ # fetched over http(s).
+ url = http_url_or_empty(self.cleaned_data["feed_url"])
+ if not url:
+ raise forms.ValidationError("Enter a feed URL starting with http:// or https://.")
+ return url
+
tag_names = forms.CharField(
label="Tags",
max_length=500,
diff --git a/apps/feeds/opml.py b/apps/feeds/opml.py
index 804231b..caa7713 100644
--- a/apps/feeds/opml.py
+++ b/apps/feeds/opml.py
@@ -17,6 +17,7 @@ from io import BytesIO
import defusedxml.ElementTree as DefusedET
from apps.articles.models import SubscriptionTag, Tag
+from apps.core.urlutils import http_url_or_empty
from .models import Feed, Subscription
@@ -66,7 +67,9 @@ def parse_opml(file_obj) -> list[dict]:
def walk(container, ancestor_names):
for outline in container.findall("outline"):
- xml_url = outline.get("xmlUrl")
+ xml_url = http_url_or_empty(outline.get("xmlUrl"))
+ if outline.get("xmlUrl") and not xml_url:
+ continue # a feed URL that isn't http(s) can never be fetched
if xml_url:
tag_names = list(ancestor_names)
category_attr = outline.get("category")
@@ -79,7 +82,7 @@ def parse_opml(file_obj) -> list[dict]:
{
"feed_url": xml_url,
"title": outline.get("title") or outline.get("text") or "",
- "site_url": outline.get("htmlUrl") or "",
+ "site_url": http_url_or_empty(outline.get("htmlUrl")),
"tag_names": tag_names,
}
)
diff --git a/apps/feeds/services/fetcher.py b/apps/feeds/services/fetcher.py
index 9247fb1..dd416a0 100644
--- a/apps/feeds/services/fetcher.py
+++ b/apps/feeds/services/fetcher.py
@@ -23,6 +23,7 @@ from django.utils import timezone
from apps.articles.models import Article, PurgedArticle
from apps.core.models import SiteSettings
+from apps.core.urlutils import resolve_http_url
from apps.feeds.models import Feed
from .ssrf_guard import SSRFBlocked, safe_get
@@ -222,7 +223,7 @@ def fetch_and_ingest(feed: Feed) -> FetchResult:
channel_title = parsed.feed.get("title")
if channel_title and not feed.title:
feed.title = channel_title[:500]
- channel_link = parsed.feed.get("link")
+ channel_link = resolve_http_url(feed.feed_url, parsed.feed.get("link"))
if channel_link and not feed.site_url:
feed.site_url = channel_link[:1000]
@@ -249,7 +250,7 @@ def fetch_and_ingest(feed: Feed) -> FetchResult:
if guid in parsed_entries:
continue
title = (getattr(entry, "title", "") or "")[:1000]
- link = (getattr(entry, "link", "") or "")[:2000]
+ link = resolve_http_url(feed.feed_url, getattr(entry, "link", ""))[:2000]
author = (getattr(entry, "author", "") or "")[:500]
summary = (getattr(entry, "summary", "") or "")[:5000]
content_html = sanitize_html(_entry_content_html(entry))
diff --git a/apps/feeds/test_fetcher.py b/apps/feeds/test_fetcher.py
index ba59ce0..1e0615c 100644
--- a/apps/feeds/test_fetcher.py
+++ b/apps/feeds/test_fetcher.py
@@ -399,3 +399,27 @@ def test_old_entries_are_ingested_normally_when_retention_is_off(feed):
responses.add(responses.GET, FEED_URL, body=xml, status=200)
assert len(fetch_and_ingest(feed).new_article_ids) == 1
+
+
+@pytest.mark.django_db
+@responses.activate
+def test_unsafe_urls_in_a_feed_are_not_stored(feed):
+ """R2-S1: a feed's channel link and entry links are untrusted — only
+ absolute http(s) URLs may be persisted (they end up in href attributes)."""
+ xml = (
+ '