Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix: allow split-origin attachment previews (#4539)

Bohan Jiang35e54559539f
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d6b0829660..a221ea2ff5 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -158,6 +158,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
}
cfSigner := auth.NewCloudFrontSignerFromEnv()
+ origins := allowedOrigins()
signupConfig := handler.Config{
AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
@@ -170,6 +171,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),
AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
+ AttachmentFrameAncestors: origins,
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
h.Metrics = opts.BusinessMetrics
@@ -480,7 +482,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
}
r.Use(chimw.Recoverer)
r.Use(middleware.ContentSecurityPolicy)
- origins := allowedOrigins()
// Share allowed origins with WebSocket origin checker.
realtime.SetAllowedOrigins(origins)
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 754c1f99ff..7c3e1377e3 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -34,14 +34,6 @@ const maxUploadSize = 100 << 20 // 100 MB
const defaultAttachmentDownloadURLTTL = 30 * time.Minute
-const attachmentPreviewCSPHeader = "default-src 'none'; " +
- "img-src 'self' data:; " +
- "media-src 'self'; " +
- "frame-ancestors 'self'; " +
- "object-src 'none'; " +
- "base-uri 'none'; " +
- "form-action 'none'"
-
type attachmentDownloadMode string
const (
@@ -748,17 +740,56 @@ func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request
w.Header().Set("Content-Disposition", storage.ContentDisposition(att.ContentType, att.Filename))
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
- setAttachmentPreviewSecurityHeaders(w)
+ h.setAttachmentPreviewSecurityHeaders(w)
if _, err := io.Copy(w, reader); err != nil {
slog.Error("failed to stream attachment download", "id", uuidToString(att.ID), "error", err)
}
}
-func setAttachmentPreviewSecurityHeaders(w http.ResponseWriter) {
- // Attachment preview responses may be loaded in same-origin iframes
- // (for example PDF previews) but must remain unembeddable by third-party
- // sites. This intentionally overrides the app-wide frame-ancestors 'none'.
- w.Header().Set("Content-Security-Policy", attachmentPreviewCSPHeader)
+func (h *Handler) setAttachmentPreviewSecurityHeaders(w http.ResponseWriter) {
+ // Attachment preview responses may be loaded by the web app in same-origin
+ // deployments or split app/api self-hosted deployments. Allow only the API
+ // origin itself plus configured frontend/CORS origins.
+ w.Header().Set("Content-Security-Policy", attachmentPreviewCSPHeader(h.cfg.AttachmentFrameAncestors))
+}
+
+func attachmentPreviewCSPHeader(frameAncestors []string) string {
+ ancestors := []string{"'self'"}
+ seen := map[string]struct{}{"'self'": {}}
+ for _, raw := range frameAncestors {
+ source, ok := normalizeFrameAncestorSource(raw)
+ if !ok {
+ continue
+ }
+ if _, exists := seen[source]; exists {
+ continue
+ }
+ seen[source] = struct{}{}
+ ancestors = append(ancestors, source)
+ }
+ return "default-src 'none'; " +
+ "img-src 'self' data:; " +
+ "media-src 'self'; " +
+ "frame-ancestors " + strings.Join(ancestors, " ") + "; " +
+ "object-src 'none'; " +
+ "base-uri 'none'; " +
+ "form-action 'none'"
+}
+
+func normalizeFrameAncestorSource(raw string) (string, bool) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "*" {
+ return "", false
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return "", false
+ }
+ scheme := strings.ToLower(u.Scheme)
+ if scheme != "http" && scheme != "https" {
+ return "", false
+ }
+ return scheme + "://" + strings.ToLower(u.Host), true
}
// ---------------------------------------------------------------------------
@@ -826,7 +857,7 @@ func (h *Handler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
// when a user explicitly opens a preview.
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
- setAttachmentPreviewSecurityHeaders(w)
+ h.setAttachmentPreviewSecurityHeaders(w)
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
if _, err := w.Write(body); err != nil {
slog.Error("failed to write attachment preview body", "id", attachmentID, "error", err)
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 26cf9c2a82..8ece0d084f 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -442,7 +442,7 @@ func newDownloadRequest(t *testing.T, attachmentID, workspaceID string) (*http.R
return req, httptest.NewRecorder()
}
-func requireAttachmentPreviewCSP(t *testing.T, header http.Header) {
+func requireAttachmentPreviewCSP(t *testing.T, header http.Header, extraAncestors ...string) {
t.Helper()
csp := header.Get("Content-Security-Policy")
if csp == "" {
@@ -459,11 +459,45 @@ func requireAttachmentPreviewCSP(t *testing.T, header http.Header) {
t.Fatalf("Content-Security-Policy missing %q; got %q", directive, csp)
}
}
+ for _, ancestor := range extraAncestors {
+ if !strings.Contains(csp, ancestor) {
+ t.Fatalf("Content-Security-Policy missing frame ancestor %q; got %q", ancestor, csp)
+ }
+ }
if strings.Contains(csp, "frame-ancestors 'none'") {
t.Fatalf("Content-Security-Policy still blocks same-origin previews: %q", csp)
}
}
+func TestAttachmentPreviewCSPHeader_AllowsConfiguredFrontendOrigins(t *testing.T) {
+ csp := attachmentPreviewCSPHeader([]string{
+ "https://app.example.test",
+ " https://App.Example.Test/some/path ",
+ "http://localhost:3000",
+ "*",
+ "javascript:alert(1)",
+ "not a url",
+ })
+
+ for _, want := range []string{
+ "frame-ancestors 'self' https://app.example.test http://localhost:3000",
+ "default-src 'none'",
+ "object-src 'none'",
+ } {
+ if !strings.Contains(csp, want) {
+ t.Fatalf("Content-Security-Policy missing %q; got %q", want, csp)
+ }
+ }
+ for _, reject := range []string{"*", "javascript:", "not a url", "some/path"} {
+ if strings.Contains(csp, reject) {
+ t.Fatalf("Content-Security-Policy includes rejected source %q; got %q", reject, csp)
+ }
+ }
+ if strings.Count(csp, "https://app.example.test") != 1 {
+ t.Fatalf("Content-Security-Policy should dedupe origins; got %q", csp)
+ }
+}
+
func newDownloadRouter() http.Handler {
// Mirrors the production router after MUL-3130: the download
// route is registered under Auth-only with no
@@ -706,6 +740,7 @@ func TestDownloadAttachment_AutoInternalEndpointProxies(t *testing.T) {
origSigner := testHandler.CFSigner
testHandler.Storage = store
testHandler.cfg.AttachmentDownloadMode = "auto"
+ testHandler.cfg.AttachmentFrameAncestors = []string{"https://app.example.test"}
testHandler.CFSigner = nil
t.Cleanup(func() {
testHandler.Storage = origStorage
@@ -740,7 +775,7 @@ func TestDownloadAttachment_AutoInternalEndpointProxies(t *testing.T) {
if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
}
- requireAttachmentPreviewCSP(t, w.Header())
+ requireAttachmentPreviewCSP(t, w.Header(), "https://app.example.test")
if len(store.presignCalls) != 0 {
t.Fatalf("internal endpoint should not presign, calls=%v", store.presignCalls)
}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 2b06e7679a..80f7a8617c 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -86,6 +86,11 @@ type Config struct {
CloudRuntimeFleetTimeout time.Duration
AttachmentDownloadMode string
AttachmentDownloadURLTTL time.Duration
+ // AttachmentFrameAncestors are trusted browser origins allowed to embed
+ // attachment preview responses. In production this should mirror the
+ // frontend/CORS origin allowlist so split app/api self-hosted deployments
+ // can frame API-hosted PDFs without allowing arbitrary third-party frames.
+ AttachmentFrameAncestors []string
}
type cloudRuntimeProxy interface {