Skip to content

Fix serving images and other raw files - #22

Open
merlimat wants to merge 1 commit into
Ch00k:mainfrom
merlimat:serve-images
Open

merlimat wants to merge 1 commit into
Ch00k:mainfrom
merlimat:serve-images

Conversation

@merlimat

Copy link
Copy Markdown

Problem

Images embedded in a document never load in the viewer. Every file that isn't Markdown or a directory goes through the raw-file branch of handleProjectFiles, and that branch answers 404 to every request, so ![diagram](diagrams/flow.svg) shows as a broken image.

Example

With a project at /home/me/proj, a document docs/design.md that embeds diagrams/flow.svg makes the browser request /projects/home/me/proj/docs/diagrams/flow.svg, which ends up here:

// Otherwise serve raw file
prefix := "/projects/" + url.PathEscape(project)
fs := http.FileServer(http.Dir(project))
http.StripPrefix(prefix, fs).ServeHTTP(w, r)

url.PathEscape escapes the slashes of the project path, so the prefix is /projects/%2Fhome%2Fme%2Fproj. It never matches the request path, and StripPrefix returns 404.

Change

By then handleProjectFiles has matched the project and resolved the file inside it, so the branch serves that path directly:

// Otherwise serve raw file, such as an image the document embeds.
// no-cache makes the browser revalidate it on reload, so edits show up.
w.Header().Set("Cache-Control", "no-cache")
http.ServeFileFS(w, r, os.DirFS(project), childPath)
  • os.DirFS keeps the file inside the project, and ServeFileFS rejects request paths that contain .. with 400. TestE2E_PathTraversal_Security now exercises this branch (test.md/../../secret.txt resolves to an existing file outside the project) and still passes.
  • The viewer reloads with location.reload() after a file change, and a reload can reuse a cached image. no-cache makes the browser revalidate it, which costs a 304 when the file is unchanged, so an edited image shows up.

Testing

  • New e2e test TestE2E_WebInterface_RawFile: an SVG next to the documents is served with image/svg+xml, no-cache and its content. It fails on main (404) and passes with this change.
  • go test ./... passes.
  • Checked in Chrome with a set of SVG diagrams: they render, and a reload revalidates them.

The raw-file branch stripped the prefix "/projects/" + url.PathEscape(project),
and PathEscape turns the slashes of the project path into %2F, so the prefix
never matched and every image a document embeds returned 404. Serve the
resolved path with http.ServeFileFS over os.DirFS(project) instead, which keeps
the file inside the project.

Also set Cache-Control: no-cache, so that the reload after a file change
revalidates images and shows edited ones.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant