Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions src/postmaster/mail_url_redaction_v981014.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Prevent passive readers and URL-scanning extensions seeing raw bearer URLs.

Redaction happens BEFORE untrusted email content reaches an authenticated
WebGUI HTML fragment, including escaped diagnostics and cache snippets.
The actual MIME/URL inventory remains unchanged for explicit, authorized
on-demand inspection. No DNS, HTTP, tracking click, or file fetch occurs.
"""
from __future__ import annotations

import re
from html import escape
from html.parser import HTMLParser

URL_HIDDEN = "[URL hidden — reveal explicitly]"
_URL = re.compile(
r"(?i)(?:\b(?:https?|ftps?)://|(?<![\w@])www\.|"
r"(?<![\w])/t/(?:c|i|o|a)/)[^\s<>'\"()]*"
)


def hide_url_text(value: str) -> str:
"""Mask absolute, common schemeless, and relative tracked URLs as text."""
return _URL.sub(URL_HIDDEN, str(value or ""))


class _SafeHtmlURLMask(HTMLParser):
"""Accept ONLY already-sanitized Safe Email HTML, never raw email HTML."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []

def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
# Rebuild escaped attributes. safe_email_html() already disallows
# active tags, remote assets, event handlers, and navigable href.
attr = "".join(
' ' + escape(k, quote=True) + '="' +
escape(hide_url_text(v or ""), quote=True) + '"'
for k, v in attrs
)
self.parts.append("<" + tag + attr + ">")

def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)

def handle_endtag(self, tag: str) -> None:
self.parts.append("</" + tag + ">")

def handle_data(self, data: str) -> None:
self.parts.append(escape(hide_url_text(data), quote=False))

def handle_entityref(self, name: str) -> None:
self.parts.append("&" + name + ";")

def handle_charref(self, name: str) -> None:
self.parts.append("&#" + name + ";")

def handle_comment(self, value: str) -> None:
return


def hide_urls_in_safe_html(sanitized_html: str) -> str:
"""Redact *visible text*, including attribute titles, without breaking tags."""
parser = _SafeHtmlURLMask()
try:
parser.feed(sanitized_html or "")
parser.close()
except Exception:
# Fail closed: never serve unmodified HTML containing opaque tokens.
return escape(hide_url_text(re.sub(r"<[^>]*>", "", sanitized_html or "")))
return "".join(parser.parts)


__all__ = ["URL_HIDDEN", "hide_url_text", "hide_urls_in_safe_html"]
64 changes: 59 additions & 5 deletions src/postmaster/webgui_links_v984.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from .webgui_helpers import owner_options, project_options
from .webgui_v962_perf import active_projects, owners
from .mail_url_redaction_v981014 import hide_url_text


def _e(value: Any) -> str:
Expand Down Expand Up @@ -120,7 +121,7 @@ def render_tracked_links_v984(base: Any, core: Any, request: Request, *, target_
status = str(link.get("status") or "unknown")
target = str(link.get("destination_url") or link.get("filename") or link.get("file_id") or "")
kind = "Tracked file" if link.get("target_type") == "stored_file" else "Tracked URL"
tracked_url = str(link.get("tracked_url") or "")
# Tracked URL must not be serialized into the dashboard HTML.
counters = link.get("analytics") or link.get("aggregate") or {}
if not isinstance(counters, dict):
counters = {}
Expand All @@ -137,14 +138,21 @@ def render_tracked_links_v984(base: Any, core: Any, request: Request, *, target_
'<input type="hidden" name="confirm" value="yes">'
'<button type="submit" class="danger">Revoke</button></form>'
)
reveal = (
'<form method="post" action="/dashboard/tracked-links/reveal" target="_blank">'
f'<input type="hidden" name="csrf" value="{_e(csrf)}">'
f'<input type="hidden" name="owner_id" value="{_e(oid)}">'
f'<input type="hidden" name="project_id" value="{_e(pid)}">'
f'<input type="hidden" name="tracked_link_id" value="{_e(link_id)}">'
'<button type="submit">Reveal URL (explicit)</button></form>'
)
rows.append(
'<tr>'
f'<td><strong>{_e(link.get("label"))}</strong><div class="small muted">{_e(kind)} · {_e(status)}</div>'
f'<td><strong>{_e(hide_url_text(str(link.get("label") or "")))}</strong><div class="small muted">{_e(kind)} · {_e(status)}</div>'
f'<small class="mono">{_e(link_id)}</small></td>'
f'<td><span class="small">{_e(oid)} / {_e(pid or "owner-wide")}</span></td>'
f'<td><span class="small">{_e(target)}</span></td>'
f'<td><input aria-label="Tracked link URL" class="v984-link-value" readonly '
f'value="{_e(tracked_url)}" onclick="this.select()" size="28"></td>'
f'<td><span class="small">{_e(hide_url_text(target))}</span></td>'
f'<td>{reveal}</td>'
f'<td>{_e(count)}</td><td>{revocation}</td></tr>'
)
errors_html = (
Expand Down Expand Up @@ -239,9 +247,55 @@ async def revoke(request: Request) -> Response:
)
return RedirectResponse(_redirect(owner, project, "Tracked link revoked"),status_code=303)

async def reveal(request: Request) -> Response:
"""Read-only capability disclosure only after verified explicit POST."""
form, error = await base._verified_form(request)
if error is not None:
return error
try:
owner, project = _scope(form, base)
link_id = str(form.get("tracked_link_id") or "").strip()
if not link_id or len(link_id) > 200:
raise ValueError("Invalid tracked link")
result = core.list_tracked_links(
owner_id=owner, project_id=project,
active_only=False, limit=500,
)
if not isinstance(result, dict) or result.get("ok") is not True:
raise ValueError("Tracked link lookup failed")
item = next(
(x for x in result.get("links", [])
if isinstance(x, dict) and str(x.get("id") or "") == link_id
and str(x.get("owner_id") or "") == owner
and str(x.get("project_id") or "") == str(project or "")),
None,
)
if item is None:
raise ValueError("Tracked link not found")
url = str(item.get("tracked_url") or "")
if not url:
raise ValueError("Tracked link unavailable")
dest = str(item.get("destination_url") or "")
except (ValueError, KeyError, TypeError):
return PlainTextResponse("Tracked link not available", status_code=404)
# No <a>, images, redirects or resource fetches. The browser only sees
# the URL after the authorized administrator explicitly presses Reveal.
return PlainTextResponse(
"Tracked URL (explicit display, not requested):\n" + url
+ ("\n\nDestination:\n" + dest if dest else "") + "\n",
headers={
"Cache-Control": "no-store, max-age=0",
"Content-Security-Policy": "default-src 'none'; base-uri 'none'; form-action 'none'",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
"X-Robots-Tag": "noindex, nofollow, noarchive",
},
)

index = next(
(i for i, route in enumerate(app.router.routes) if isinstance(route, Mount)),
len(app.router.routes),
)
app.router.routes.insert(index, Route("/dashboard/tracked-links/create", create, methods=["POST"]))
app.router.routes.insert(index+1, Route("/dashboard/tracked-links/revoke", revoke, methods=["POST"]))
app.router.routes.insert(index+2, Route("/dashboard/tracked-links/reveal", reveal, methods=["POST"]))
22 changes: 7 additions & 15 deletions src/postmaster/webgui_tracking_v984.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from starlette.requests import Request

from .tracking_geoip_v984 import global_tracking_network_events
from .mail_url_redaction_v981014 import hide_url_text

_ZONE = ZoneInfo("Europe/Rome")
_PERIODS = {"24h": timedelta(hours=24), "7d": timedelta(days=7),
Expand Down Expand Up @@ -192,7 +193,7 @@ def _event_html(event: dict[str, Any]) -> str:
disclosure; no external resource is fetched or opened while rendering.
"""
def e(k: str) -> str:
return escape(str(event.get(k) or "—"))
return escape(hide_url_text(str(event.get(k) or "—")))

kind = str(event.get("event_kind") or "")
names = {
Expand All @@ -202,11 +203,11 @@ def e(k: str) -> str:
"tracked_file_download": "File scaricato",
}
title = names.get(kind, kind)
subject = str(event.get("email_subject") or "").strip()
subject = hide_url_text(str(event.get("email_subject") or "").strip())
recipient = str(event.get("recipient") or "").strip()
original = str(event.get("original_url") or "").strip()
filename = str(event.get("download_filename") or "").strip()
label = str(event.get("label") or "").strip()
label = hide_url_text(str(event.get("label") or "").strip())
href = str(event.get("email_href") or "").strip()
info: list[str] = []
if kind.startswith("email_"):
Expand All @@ -216,7 +217,7 @@ def e(k: str) -> str:
if recipient:
info.append("<small>Destinatario: " + escape(recipient) + "</small>")
if kind == "email_click" and original:
info.append("<small>Destinazione del link: " + escape(original) + "</small>")
info.append("<small>Destinazione del link: [URL hidden — reveal explicitly in Mail]</small>")
if href.startswith("/?") and href.endswith("#inbox"):
info.append(
'<a data-v960-fragment="inbox" href="' + escape(href, quote=True)
Expand All @@ -230,17 +231,8 @@ def e(k: str) -> str:
info.append("<small>Etichetta: " + escape(label) + "</small>")
else:
info.append("<strong>URL di destinazione:</strong>")
try:
parts = urlsplit(original)
clickable = parts.scheme.lower() in {"http", "https"} and bool(parts.netloc)
except ValueError:
clickable = False
if clickable:
info.append('<a href="' + escape(original, quote=True) +
'" target="_blank" rel="noopener noreferrer">' +
escape(original) + "</a>")
elif original:
info.append("<small>" + escape(original) + "</small>")
if original:
info.append("<small>[URL hidden — use Tracked Links to reveal]</small>")
else:
info.append("<small>Destinazione non disponibile</small>")
if label:
Expand Down
Loading
Loading