Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Serve room attachments whose names are not latin-1 (#1064)

massimo-sandboxaq97e48b43c93c
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index cc8a962f5..61299f677 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -114,6 +114,7 @@ from switch_core.bridges.agent.registration_bootstrap import (
)
from switch_core.budgets import BudgetExceeded
from switch_core.config import SwitchConfig
+from switch_core.content_disposition import content_disposition
from switch_core.db.models import Agent
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.gateway.known_agents import known_agent
@@ -519,7 +520,9 @@ async def download_media(
headers = {}
if filename:
- headers["Content-Disposition"] = f'inline; filename="{filename}"'
+ headers["Content-Disposition"] = content_disposition(
+ "inline", filename, "attachment"
+ )
return Response(
content=data,
media_type=content_type or "application/octet-stream",
diff --git a/core/switch_core/content_disposition.py b/core/switch_core/content_disposition.py
new file mode 100644
index 000000000..68b3865f3
--- /dev/null
+++ b/core/switch_core/content_disposition.py
@@ -0,0 +1,26 @@
+"""`Content-Disposition` headers for files whose names are free text."""
+
+import os.path
+import re
+from urllib.parse import quote
+
+_UNSAFE_IN_FILENAME = re.compile(r"[^A-Za-z0-9._-]+")
+
+
+def content_disposition(disposition: str, filename: str, fallback_stem: str) -> str:
+ """A download header a filename cannot break out of (RFC 6266).
+
+ The name is free text, so it may hold a quote, a newline, or a character
+ outside latin-1 — a macOS screenshot's name has a narrow no-break space
+ before its AM/PM. Interpolated raw, the first corrupts the header, the
+ second appends one of the caller's choosing, and the third fails the whole
+ response — headers are latin-1 on the wire. So the plain `filename` is
+ reduced to an ASCII skeleton (`fallback_stem` standing in for a name with
+ nothing left of it) and the real name travels percent-encoded in
+ `filename*`, which is what a modern client prefers anyway.
+ """
+ stem, extension = os.path.splitext(filename)
+ stem = _UNSAFE_IN_FILENAME.sub("-", stem).strip("-") or fallback_stem
+ extension = _UNSAFE_IN_FILENAME.sub("-", extension)
+ encoded = quote(filename, safe="")
+ return f"{disposition}; filename=\"{stem}{extension}\"; filename*=UTF-8''{encoded}"
diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.py
index d4cc767d8..3c29b4aa1 100644
--- a/core/switch_core/gateway/templates.py
+++ b/core/switch_core/gateway/templates.py
@@ -13,9 +13,7 @@ already answered — agreeing right up until the day it did not.
from __future__ import annotations
-import re
from typing import Annotated
-from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy.ext.asyncio import AsyncSession
@@ -30,6 +28,7 @@ from switch_core.authz import (
validate_visibility_pair,
)
from switch_core.config import SwitchConfig
+from switch_core.content_disposition import content_disposition
from switch_core.db.models import Template, User
from switch_core.db.stores.template_store import (
TemplateListing,
@@ -80,29 +79,11 @@ def _kind(value: str | None) -> str:
router = APIRouter()
-_UNSAFE_IN_FILENAME = re.compile(r"[^A-Za-z0-9._-]+")
-
-
def _size_bytes(content: str) -> int:
"""What the document weighs on the wire, not how many characters it has."""
return len(content.encode("utf-8"))
-def _content_disposition(name: str) -> str:
- """A download header a template name cannot break out of (RFC 6266).
-
- The name is free text, so it may hold a quote, a newline, or a character
- outside latin-1. Interpolated raw, the first corrupts the header, the
- second appends one of the caller's choosing, and the third fails the whole
- response — headers are latin-1 on the wire. So the plain `filename` is
- reduced to an ASCII skeleton and the real name travels percent-encoded in
- `filename*`, which is what a modern client prefers anyway.
- """
- stem = _UNSAFE_IN_FILENAME.sub("-", name).strip("-") or "template"
- encoded = quote(f"{name}.yaml", safe="")
- return f"attachment; filename=\"{stem}.yaml\"; filename*=UTF-8''{encoded}"
-
-
def _summary(
row: TemplateListing, owner_name: str | None, principal: Principal
) -> TemplateSummary:
@@ -450,7 +431,9 @@ async def get_template_content(
content=template.content.encode("utf-8"),
media_type="application/x-yaml",
headers={
- "Content-Disposition": _content_disposition(template.name),
+ "Content-Disposition": content_disposition(
+ "attachment", f"{template.name}.yaml", "template"
+ ),
# The bytes are whatever someone uploaded, so a browser must not be
# talked into sniffing them into something it will render.
"X-Content-Type-Options": "nosniff",
diff --git a/core/tests/switch_core/test_content_disposition.py b/core/tests/switch_core/test_content_disposition.py
new file mode 100644
index 000000000..1154b9daf
--- /dev/null
+++ b/core/tests/switch_core/test_content_disposition.py
@@ -0,0 +1,37 @@
+from urllib.parse import unquote
+
+import pytest
+from starlette.responses import Response
+
+from switch_core.content_disposition import content_disposition
+
+
+ "filename",
+ [
+ "Device profile — SSH host.png",
+ "Screenshot 2026-10-26 at 10.15.32 AM.png",
+ "Capture d’écran.png",
+ 'quote" and\r\nX-Injected: 1.png',
+ ],
+)
+def test_a_free_text_name_makes_a_header_the_response_can_send(filename: str) -> None:
+ header = content_disposition("inline", filename, "attachment")
+
+ Response(content=b"x", headers={"Content-Disposition": header})
+ assert "\r" not in header and "\n" not in header
+ plain, encoded = header.split("; ")[1:]
+ assert plain.count('"') == 2
+ assert unquote(encoded.removeprefix("filename*=UTF-8''")) == filename
+
+
+def test_an_ascii_name_is_kept_as_it_is() -> None:
+ assert content_disposition("inline", "settings_devices.png", "attachment") == (
+ "inline; filename=\"settings_devices.png\"; filename*=UTF-8''settings_devices.png"
+ )
+
+
+def test_a_name_with_nothing_ascii_left_falls_back_to_the_stem() -> None:
+ header = content_disposition("attachment", "☕.yaml", "template")
+
+ assert header.startswith('attachment; filename="template.yaml";')