Skip to content
quarry Artifact [1f9b5860f6]
Login

Artifact [1f9b5860f6]

Artifact 1f9b5860f62649896736c4bfc35615b2306eb63f29470eac5b41980eeef05465:


package web

import (
	"context"
	"encoding/base64"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/ops"
)

type docStubIn struct {
	Repo string `json:"repo" validate:"required,max=64"`
	Hash string `json:"hash" validate:"required,max=64"`
	Path string `json:"path" validate:"required"`
}

// docStubRegistry answers doc.get with an image the test chose, shaped as
// the op shapes it, so the route's own headers are what is under test.
func docStubRegistry(t *testing.T, ctype string, body []byte) *ops.Registry {
	t.Helper()
	r := viewRegistry(t, nil)
	if err := ops.Register(r, ops.Op[docStubIn, docDetail]{
		Name:  "doc.get",
		Caps:  "o",
		Doc:   "test stub",
		Kind:  ops.Query,
		Auth:  ops.Anonymous,
		Route: "GET /api/v1/r/{repo}/doc/{hash}/{path...}",
		Run: func(_ context.Context, in docStubIn) (docDetail, error) {
			return docDetail{Hash: in.Hash, Path: in.Path, Size: len(body),
				ContentType: ctype, Content: base64.StdEncoding.EncodeToString(body)}, nil
		},
	}); err != nil {
		t.Fatal(err)
	}
	return r
}

// docServed runs the doc route behind the page-policy middleware, with a
// bucket bound to the repository so the policy is the widened one the
// middleware swaps in at WriteHeader.
func docServed(t *testing.T, ctype, path string, body []byte) *httptest.ResponseRecorder {
	t.Helper()
	h := WithCSP(Handler(docStubRegistry(t, ctype, body), nil, nil),
		WithRepoOrigins(func(string) []string { return []string{"https://bucket.example"} }))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/r/egress/doc/abc123/"+path, nil))
	return rec
}

func TestDocSVGIsServedUnderASandboxingPolicy(t *testing.T) {
	for name, body := range map[string][]byte{
		"plain":  []byte(`<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`),
		"script": []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`),
	} {
		rec := docServed(t, "image/svg+xml", "docs/images/mark.svg", body)
		if rec.Code != http.StatusOK {
			t.Fatalf("FAIL: %s svg answered %d", name, rec.Code)
		}
		h := rec.Header()
		t.Logf("%s svg headers: %v", name, h)
		if got := h.Get("Content-Type"); got != "image/svg+xml" {
			t.Errorf("FAIL: %s Content-Type %q", name, got)
		}
		if got := h.Get("X-Content-Type-Options"); got != "nosniff" {
			t.Errorf("FAIL: %s nosniff %q", name, got)
		}
		if h.Get("Content-Disposition") == "attachment" || strings.HasPrefix(h.Get("Content-Disposition"), "attachment") {
			t.Errorf("FAIL: %s svg is an attachment, which breaks <img>", name)
		}
		csp := h.Values("Content-Security-Policy")
		if len(csp) != 1 {
			t.Fatalf("FAIL: %s svg carries %d policies, want exactly one", name, len(csp))
		}
		for _, want := range []string{"default-src 'none'", "sandbox"} {
			if !strings.Contains(csp[0], want) {
				t.Errorf("FAIL: %s policy lacks %q: %s", name, want, csp[0])
			}
		}
		for _, banned := range []string{"script-src", "nonce-", "allow-scripts", "allow-same-origin", "bucket.example"} {
			if strings.Contains(csp[0], banned) {
				t.Errorf("FAIL: %s policy carries %q from the page policy: %s", name, banned, csp[0])
			}
		}
		if rec.Body.String() != string(body) {
			t.Errorf("FAIL: %s bytes changed in transit", name)
		}
	}
}

func TestDocPNGIsServedAsBefore(t *testing.T) {
	rec := docServed(t, "image/png", "a.png", pngBytes)
	h := rec.Header()
	if rec.Code != http.StatusOK || h.Get("Content-Type") != "image/png" ||
		h.Get("X-Content-Type-Options") != "nosniff" {
		t.Errorf("FAIL: png answered %d %v", rec.Code, h)
	}
	if strings.Contains(h.Get("Content-Security-Policy"), "sandbox") {
		t.Errorf("FAIL: a png took the svg policy")
	}
	if !strings.HasPrefix(h.Get("Cache-Control"), "public") {
		t.Errorf("FAIL: an anonymous png is not cacheable: %q", h.Get("Cache-Control"))
	}
}