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
9 changes: 8 additions & 1 deletion server/pages.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,14 @@ func (s *Server) handleRaw(w http.ResponseWriter, r *http.Request, rs *repoState
}
h.Set("Content-Type", ct)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Content-Security-Policy", "default-src 'none'; sandbox")
if ct == "application/pdf" {
// The CSP sandbox keyword makes Chromium refuse to instantiate
// its PDF viewer, so PDFs trade it for an embed restriction.
// Threat analysis in spec 2011 doc 18 section 4.3.
h.Set("Content-Security-Policy", "frame-ancestors 'self'")
} else {
h.Set("Content-Security-Policy", "default-src 'none'; sandbox")
}
h.Set("Cache-Control", "no-cache")
// ServeContent gives us Range, HEAD, and 206 handling for media; the
// empty name and zero time keep it from guessing the type or etag.
Expand Down
3 changes: 2 additions & 1 deletion server/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func loadTemplates(opts Options) (*templates, error) {
chromaCSS: viewer.ChromaCSS(),
csp: "default-src 'none'; img-src 'self' data: https:; style-src 'self'; " +
"script-src 'self' 'sha256-" + base64.StdEncoding.EncodeToString(hash[:]) + "'; " +
"connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
"connect-src 'self'; media-src 'self'; frame-src 'self'; " +
"form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
version: opts.Version,
}

Expand Down
3 changes: 3 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func New(ctx context.Context, repos []backend.Repo, opts Options) (*Server, erro
// goes last and every text file always renders somehow.
viewers: viewer.NewRegistry(
viewer.Image(),
viewer.Audio(),
viewer.Video(),
viewer.PDF(),
viewer.Markdown(),
viewer.Code(),
),
Expand Down
69 changes: 69 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,72 @@ func TestHostileContent(t *testing.T) {
t.Errorf("raw nosniff header = %q", got)
}
}

func TestMediaAndPDFViewers(t *testing.T) {
g := gittest.New(t)
g.Write("song.mp3", "ID3fakeaudio")
g.Write("clip.mp4", "fakevideo")
g.Write("paper.pdf", "%PDF-1.4 fake")
g.Commit("media fixtures")
g.SetOrigin("https://github.com/octo/media.git")
repo, err := local.New(context.Background(), g.Path())
if err != nil {
t.Fatal(err)
}
s, err := New(context.Background(), []backend.Repo{repo}, Options{Dev: true})
if err != nil {
t.Fatal(err)
}

res, body := get(t, s, "/octo/media/blob/main/song.mp3")
mustContain(t, body, `data-kind="audio"`, "<audio controls", `preload="metadata"`)

_, body = get(t, s, "/octo/media/blob/main/clip.mp4")
mustContain(t, body, `data-kind="video"`, "<video controls")

_, body = get(t, s, "/octo/media/blob/main/paper.pdf")
mustContain(t, body, `data-kind="pdf"`, "<iframe")

// The page policy lets same-origin media and frames through.
csp := res.Header.Get("Content-Security-Policy")
for _, src := range []string{"media-src 'self'", "frame-src 'self'"} {
if !strings.Contains(csp, src) {
t.Errorf("page CSP missing %q: %s", src, csp)
}
}

// Raw media keeps the sandbox and the right type.
res, _ = get(t, s, "/octo/media/raw/main/song.mp3")
if ct := res.Header.Get("Content-Type"); ct != "audio/mpeg" {
t.Errorf("mp3 Content-Type = %q", ct)
}
if !strings.Contains(res.Header.Get("Content-Security-Policy"), "sandbox") {
t.Error("raw mp3 lost the sandbox CSP")
}

// Raw PDF drops the sandbox (it blanks Chromium's viewer) and
// restricts embedding to gitview pages instead.
res, _ = get(t, s, "/octo/media/raw/main/paper.pdf")
if ct := res.Header.Get("Content-Type"); ct != "application/pdf" {
t.Errorf("pdf Content-Type = %q", ct)
}
pdfCSP := res.Header.Get("Content-Security-Policy")
if pdfCSP != "frame-ancestors 'self'" {
t.Errorf("pdf CSP = %q", pdfCSP)
}
if res.Header.Get("X-Content-Type-Options") != "nosniff" {
t.Error("pdf raw lost nosniff")
}

// ServeContent gives media seeking: a Range request gets a 206.
req := httptest.NewRequest("GET", "/octo/media/raw/main/song.mp3", nil)
req.Header.Set("Range", "bytes=0-3")
rec := httptest.NewRecorder()
s.ServeHTTP(rec, req)
if rec.Code != http.StatusPartialContent {
t.Errorf("range status = %d, want 206", rec.Code)
}
if got := rec.Body.String(); got != "ID3f" {
t.Errorf("range body = %q", got)
}
}
4 changes: 4 additions & 0 deletions server/static/primer.css
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,10 @@ html[data-color-mode="auto"] .theme-icon-dark { display: none; }

.blob-notice { padding: 64px 16px; text-align: center; }
.blob-image { max-width: 100%; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Crect width='8' height='8' fill='%23eee'/%3E%3Crect x='8' y='8' width='8' height='8' fill='%23eee'/%3E%3C/svg%3E"); }
.blob-media { padding: 16px; text-align: center; }
.blob-media audio { width: 100%; max-width: 640px; }
.blob-media video { max-width: 100%; max-height: 70vh; }
.blob-frame iframe { display: block; width: 100%; height: 80vh; border: 0; background: var(--color-canvas-subtle); }

/* ---- Commits list ------------------------------------------------------ */

Expand Down
47 changes: 47 additions & 0 deletions server/viewer/media.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package viewer

import (
"html/template"
"strings"
)

// Audio renders an <audio> element over the raw URL. preload="metadata"
// keeps a directory crawl from pulling whole files; never autoplay.
// Codec support is the browser's problem: the element shows its native
// error UI when it cannot play the file.
func Audio() Renderer { return audioRenderer{} }

type audioRenderer struct{}

func (audioRenderer) Kind() string { return "audio" }

func (audioRenderer) Match(in Input) bool {
mt, ok := MIME(in.Ext)
return ok && strings.HasPrefix(mt, "audio/")
}

func (audioRenderer) Render(in Input) (Output, error) {
body := `<div class="blob-media" data-kind="audio"><audio controls preload="metadata" src="` +
template.HTMLEscapeString(in.RawURL) + `"></audio></div>`
return Output{Kind: "audio", Body: template.HTML(body)}, nil
}

// Video renders a <video> element over the raw URL. Same rules as audio:
// metadata preload, no autoplay, no poster. CSS caps the element at the
// blob box width and 70vh.
func Video() Renderer { return videoRenderer{} }

type videoRenderer struct{}

func (videoRenderer) Kind() string { return "video" }

func (videoRenderer) Match(in Input) bool {
mt, ok := MIME(in.Ext)
return ok && strings.HasPrefix(mt, "video/")
}

func (videoRenderer) Render(in Input) (Output, error) {
body := `<div class="blob-media" data-kind="video"><video controls preload="metadata" src="` +
template.HTMLEscapeString(in.RawURL) + `"></video></div>`
return Output{Kind: "video", Body: template.HTML(body)}, nil
}
16 changes: 16 additions & 0 deletions server/viewer/mime.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ var mimeByExt = map[string]string{
".bmp": "image/bmp",
".ico": "image/x-icon",
".svg": "image/svg+xml",

".mp3": "audio/mpeg",
".wav": "audio/wav",
".ogg": "audio/ogg",
".oga": "audio/ogg",
".flac": "audio/flac",
".m4a": "audio/mp4",
".opus": "audio/ogg",

".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
".mov": "video/quicktime",
".ogv": "video/ogg",

".pdf": "application/pdf",
}

// MIME returns the Content-Type for a lowercased extension with dot.
Expand Down
27 changes: 27 additions & 0 deletions server/viewer/pdf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package viewer

import (
"html/template"
)

// PDF embeds the browser's own viewer in an iframe over the raw URL.
// No magic check: a text file named x.pdf shows the viewer's broken
// document message, which is more honest than code-viewing it. The
// iframe carries no sandbox attribute on purpose: a sandboxed frame
// blocks Chromium's PDF plugin outright, and the raw response behind
// it already drops the CSP sandbox for application/pdf with the
// frame-ancestors 'self' analysis from spec 2011 doc 18 section 4.3.
func PDF() Renderer { return pdfRenderer{} }

type pdfRenderer struct{}

func (pdfRenderer) Kind() string { return "pdf" }

func (pdfRenderer) Match(in Input) bool { return in.Ext == ".pdf" }

func (pdfRenderer) Render(in Input) (Output, error) {
body := `<div class="blob-frame" data-kind="pdf"><iframe src="` +
template.HTMLEscapeString(in.RawURL) + `" title="` +
template.HTMLEscapeString(in.Name) + `"></iframe></div>`
return Output{Kind: "pdf", Body: template.HTML(body)}, nil
}
110 changes: 110 additions & 0 deletions server/viewer/viewer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package viewer

import (
"errors"
"strings"
"testing"
)

type fakeRenderer struct {
kind string
match bool
err error
}

func (f fakeRenderer) Kind() string { return f.kind }
func (f fakeRenderer) Match(Input) bool { return f.match }
func (f fakeRenderer) Render(Input) (Output, error) {
if f.err != nil {
return Output{}, f.err
}
return Output{Kind: f.kind}, nil
}

func TestRegistryFirstMatchWins(t *testing.T) {
g := NewRegistry(
fakeRenderer{kind: "a", match: false},
fakeRenderer{kind: "b", match: true},
fakeRenderer{kind: "c", match: true},
)
out, ok := g.Render(Input{})
if !ok || out.Kind != "b" {
t.Fatalf("got %q ok=%v, want b", out.Kind, ok)
}
}

func TestRegistryErrorFallsThrough(t *testing.T) {
g := NewRegistry(
fakeRenderer{kind: "broken", match: true, err: errors.New("corrupt")},
fakeRenderer{kind: "fallback", match: true},
)
out, ok := g.Render(Input{})
if !ok || out.Kind != "fallback" {
t.Fatalf("got %q ok=%v, want fallback", out.Kind, ok)
}
}

func TestRegistryNothingMatches(t *testing.T) {
g := NewRegistry(fakeRenderer{kind: "a", match: false})
if _, ok := g.Render(Input{}); ok {
t.Fatal("expected no render")
}
}

func TestProbeDoesNotRender(t *testing.T) {
g := NewRegistry(
fakeRenderer{kind: "broken", match: true, err: errors.New("corrupt")},
fakeRenderer{kind: "next", match: true},
)
// Probe reports the first match even when its Render would fail;
// it answers "what kind claims this", not "what would succeed".
k, ok := g.Probe(Input{})
if !ok || k != "broken" {
t.Fatalf("probe = %q ok=%v, want broken", k, ok)
}
}

func TestMediaRenderersEscapeAttributes(t *testing.T) {
in := Input{
Name: `x"><script>.mp4`,
Ext: ".mp4",
RawURL: `/r/raw/main/x"><script>.mp4`,
}
for _, r := range []Renderer{Audio(), Video(), PDF(), Image()} {
out, err := r.Render(in)
if err != nil {
t.Fatalf("%s: %v", r.Kind(), err)
}
if strings.Contains(string(out.Body), "<script>") {
t.Errorf("%s body not escaped: %s", r.Kind(), out.Body)
}
}
}

func TestMediaMatch(t *testing.T) {
cases := []struct {
ext string
kind string
}{
{".mp3", "audio"},
{".flac", "audio"},
{".opus", "audio"},
{".mp4", "video"},
{".webm", "video"},
{".mov", "video"},
{".pdf", "pdf"},
{".png", "image"},
{".svg", "image"},
}
g := NewRegistry(Image(), Audio(), Video(), PDF(), Markdown(), Code())
for _, c := range cases {
k, ok := g.Probe(Input{Ext: c.ext, Binary: true})
if !ok || k != c.kind {
t.Errorf("%s -> %q ok=%v, want %q", c.ext, k, ok, c.kind)
}
}
// Plain never disables a binary-backed viewer.
if k, _ := g.Probe(Input{Ext: ".mp4", Binary: true, Plain: true}); k != "video" {
t.Errorf("plain mp4 -> %q, want video", k)
}
}
Loading