carlos / platform Public

feat: negotiate Markdown twins for static HTML pages

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev fe7ecccae39113fb61b2286c239150d0edd6343b parent a921b59
4 files changed, +542 −25
  • internal/edge/static.go +48 −18
  • internal/edge/static_cache_test.go +7 −7
  • internal/edge/static_markdown.go +156 −0
  • internal/edge/static_markdown_test.go +331 −0

CI failed — run details

diff --git a/internal/edge/static.go b/internal/edge/static.go
index e0057e5d0..13ff63fbf 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -699,7 +699,23 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
w.WriteHeader(http.StatusMovedPermanently)
return
}
- s.serveFile(fp, p, fi, status, extra, w, r)
+ rep := selectStaticRepresentation(fp, fi, r.Header)
+ if guard {
+ // Check the file we will send, including an index reached through
+ // a directory and a Markdown sibling selected by negotiation.
+ target, err := filepath.Rel(tree.dir, rep.path)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if hit, ok := edgeguard.CheckTier("/"+filepath.ToSlash(target), "", reqrec.TierHard); ok && guardDecide(w, r, hit) {
+ return
+ }
+ }
+ if rep.varies {
+ w.Header().Add("Vary", "Accept")
+ }
+ s.serveFile(rep.path, p, rep.info, rep.contentType, status, extra, w, r)
return
}
}
@@ -743,7 +759,7 @@ func staticBurstDecide(w http.ResponseWriter, r *http.Request) bool {
// 200 path takes it, through a headerWriter that applies it if ServeContent
// answers 200, 206 or 304 and leaves its 412s and 416s as they are: a 404 page
// marked immutable would pin a typo in every browser for a year.
-func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra http.Header, w http.ResponseWriter, r *http.Request) {
+func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, contentType string, status int, extra http.Header, w http.ResponseWriter, r *http.Request) {
f, err := os.Open(fp)
if err != nil {
// ServeFile's mapping, kept: a file that vanished since the Stat is
@@ -762,7 +778,10 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
}
defer f.Close()
if status != http.StatusOK {
- ctype := mime.TypeByExtension(filepath.Ext(fp))
+ ctype := contentType
+ if ctype == "" {
+ ctype = mime.TypeByExtension(filepath.Ext(fp))
+ }
if ctype == "" {
var head [512]byte
n, _ := io.ReadFull(f, head[:])
@@ -786,11 +805,14 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
defer hw.finish()
w = hw
}
+ if contentType != "" {
+ w.Header().Set("Content-Type", contentType)
+ }
// Stat the OPEN file: its identity is what a remembered tag is checked
// against, and it is the file whose bytes are about to be sent.
if ofi, err := f.Stat(); err == nil && !ofi.IsDir() {
fi = ofi
- if tag, ctype, err := staticTags.tag(r.Context(), fp, f, fi); err == nil {
+ if tag, ctype, err := staticTags.tag(r.Context(), fp, f, fi, contentType); err == nil {
// The type the tag was computed over is the type sent: set here,
// ServeContent leaves it alone.
w.Header().Set("ETag", tag)
@@ -870,8 +892,8 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
// demand, which costs hashing and never correctness.
type tagCache struct {
mu sync.Mutex
- entries map[string]tagEntry
- flights map[string]chan struct{} // closed when the hash for that path is done
+ entries map[staticTagKey]tagEntry
+ flights map[staticTagKey]chan struct{} // closed when this representation's hash is done
sem chan struct{}
wait time.Duration
@@ -883,6 +905,10 @@ type tagCache struct {
hold func()
}
+type staticTagKey struct {
+ path, contentType string
+}
+
type tagEntry struct {
fi os.FileInfo
tag, ctype string
@@ -901,8 +927,8 @@ var errTagBusy = errors.New("static tag: hashers busy")
func newTagCache() *tagCache {
return &tagCache{
- entries: map[string]tagEntry{},
- flights: map[string]chan struct{}{},
+ entries: map[staticTagKey]tagEntry{},
+ flights: map[staticTagKey]chan struct{}{},
sem: make(chan struct{}, tagHashers),
wait: tagWait,
}
@@ -919,11 +945,12 @@ func (e tagEntry) current(fi os.FileInfo) bool {
// hashing it if no current entry exists. f is left positioned at its start.
// ctx and the wait budget bound the WAITING — on another request's hash, or
// on a free hasher — never a hash in progress.
-func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.FileInfo) (tag, ctype string, err error) {
+func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.FileInfo, contentType string) (tag, ctype string, err error) {
+ key := staticTagKey{path: fp, contentType: contentType}
var budget <-chan time.Time
for {
c.mu.Lock()
- if e, ok := c.entries[fp]; ok && e.current(fi) {
+ if e, ok := c.entries[key]; ok && e.current(fi) {
c.mu.Unlock()
return e.tag, e.ctype, nil
}
@@ -932,7 +959,7 @@ func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.Fi
defer t.Stop()
budget = t.C
}
- if flight, ok := c.flights[fp]; ok {
+ if flight, ok := c.flights[key]; ok {
c.mu.Unlock()
c.waiting.Add(1)
select {
@@ -948,25 +975,25 @@ func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.Fi
}
}
done := make(chan struct{})
- c.flights[fp] = done
+ c.flights[key] = done
c.mu.Unlock()
- tag, ctype, err = c.hash(ctx, budget, f, fi)
+ tag, ctype, err = c.hash(ctx, budget, f, fi, contentType)
c.mu.Lock()
if err == nil {
if len(c.entries) >= tagCacheMax {
- c.entries = map[string]tagEntry{}
+ c.entries = map[staticTagKey]tagEntry{}
}
- c.entries[fp] = tagEntry{fi: fi, tag: tag, ctype: ctype}
+ c.entries[key] = tagEntry{fi: fi, tag: tag, ctype: ctype}
}
- delete(c.flights, fp)
+ delete(c.flights, key)
c.mu.Unlock()
close(done)
return tag, ctype, err
}
}
-func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadSeeker, fi os.FileInfo) (tag, ctype string, err error) {
+func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadSeeker, fi os.FileInfo, contentType string) (tag, ctype string, err error) {
if fi.Size() > tagInline {
select {
case c.sem <- struct{}{}:
@@ -997,7 +1024,10 @@ func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadS
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return "", "", err
}
- ctype = mime.TypeByExtension(filepath.Ext(fi.Name()))
+ ctype = contentType
+ if ctype == "" {
+ ctype = mime.TypeByExtension(filepath.Ext(fi.Name()))
+ }
if ctype == "" {
ctype = http.DetectContentType(head[:n])
}
diff --git a/internal/edge/static_cache_test.go b/internal/edge/static_cache_test.go
index ccdbd09d9..1e89dcaa9 100644
--- a/internal/edge/static_cache_test.go
+++ b/internal/edge/static_cache_test.go
@@ -392,7 +392,7 @@ func TestTagCacheHashesAColdFileOnceForOverlappingRequests(t *testing.T) {
errs[i] = err
return
}
- tags[i], _, errs[i] = c.tag(context.Background(), fp, f, fi)
+ tags[i], _, errs[i] = c.tag(context.Background(), fp, f, fi, "")
}
wg.Add(1)
go call(0)
@@ -434,7 +434,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
}
fp, f, fi := openTagged(t, dir, "big.bin", strings.Repeat("x", tagInline+1))
- if _, _, err := c.tag(context.Background(), fp, f, fi); !errors.Is(err, errTagBusy) {
+ if _, _, err := c.tag(context.Background(), fp, f, fi, ""); !errors.Is(err, errTagBusy) {
t.Fatalf("a large file with no free hasher = %v, want errTagBusy", err)
}
if n := len(c.flights); n != 0 {
@@ -442,7 +442,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
}
fp, f, fi = openTagged(t, dir, "page.html", "<p>a small page</p>")
- tag, ctype, err := c.tag(context.Background(), fp, f, fi)
+ tag, ctype, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || tag == "" || !strings.HasPrefix(ctype, "text/html") {
t.Fatalf("a small file while every hasher is busy = %q %q %v; want it tagged at once", tag, ctype, err)
}
@@ -453,7 +453,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
<-c.sem
c.wait = time.Minute
fp, f, fi = openTagged(t, dir, "big.bin", strings.Repeat("x", tagInline+1))
- if tag, _, err := c.tag(context.Background(), fp, f, fi); err != nil || tag == "" {
+ if tag, _, err := c.tag(context.Background(), fp, f, fi, ""); err != nil || tag == "" {
t.Fatalf("a large file with a free hasher = %q, %v", tag, err)
}
}
@@ -469,7 +469,7 @@ func TestTagCacheTagCoversTheResolvedContentType(t *testing.T) {
// last run's mapping in place of an unknown one).
ext := fmt.Sprintf(".zzcarlos%d", time.Now().UnixNano())
fp, f, fi := openTagged(t, t.TempDir(), "notes"+ext, body)
- sniffedTag, sniffedType, err := c.tag(context.Background(), fp, f, fi)
+ sniffedTag, sniffedType, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || !strings.HasPrefix(sniffedType, "text/plain") {
t.Fatalf("an unknown extension = %q %v, want it sniffed as text/plain", sniffedType, err)
}
@@ -479,7 +479,7 @@ func TestTagCacheTagCoversTheResolvedContentType(t *testing.T) {
t.Fatal(err)
}
fp, f, fi = openTagged(t, t.TempDir(), "notes"+ext, body)
- knownTag, knownType, err := c.tag(context.Background(), fp, f, fi)
+ knownTag, knownType, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || !strings.HasPrefix(knownType, "text/markdown") {
t.Fatalf("a mapped extension = %q %v, want text/markdown", knownType, err)
}
@@ -585,7 +585,7 @@ func TestTagCacheRewindsTheFileWhenHashingFails(t *testing.T) {
_, _, fi := openTagged(t, t.TempDir(), "picture", "placeholder")
for _, good := range []int{100, 2000} { // fails inside the sniffed prefix, and after it
f := &failingFile{data: make([]byte, 4096), good: good}
- if _, _, err := c.tag(context.Background(), fmt.Sprintf("/nowhere/picture-%d", good), f, fi); err == nil {
+ if _, _, err := c.tag(context.Background(), fmt.Sprintf("/nowhere/picture-%d", good), f, fi, ""); err == nil {
t.Fatalf("hashing a file that fails after %d bytes reported no error", good)
}
if f.pos != 0 {
diff --git a/internal/edge/static_markdown.go b/internal/edge/static_markdown.go
new file mode 100644
index 000000000..fd7414229
--- /dev/null
+++ b/internal/edge/static_markdown.go
@@ -0,0 +1,156 @@
+package edge
+
+import (
+ "mime"
+ "net/http"
+ "os"
+ "strings"
+)
+
+const staticMarkdownType = "text/markdown; charset=utf-8"
+
+type staticRepresentation struct {
+ path string
+ info os.FileInfo
+ contentType string
+ varies bool
+}
+
+func selectStaticRepresentation(fp string, fi os.FileInfo, accept http.Header) staticRepresentation {
+ rep := staticRepresentation{path: fp, info: fi}
+ if !fi.Mode().IsRegular() || !strings.HasSuffix(fp, ".html") {
+ return rep
+ }
+ twin := strings.TrimSuffix(fp, ".html") + ".md"
+ ti, err := os.Lstat(twin)
+ if err != nil || !ti.Mode().IsRegular() {
+ return rep
+ }
+ rep.varies = true
+ if prefersMarkdown(accept) {
+ rep.path, rep.info, rep.contentType = twin, ti, staticMarkdownType
+ }
+ return rep
+}
+
+// prefersMarkdown compares the quality of the two UTF-8 representations.
+// Specificity wins before quality: an explicit refusal cannot be undone by
+// a wildcard with a higher qvalue.
+func prefersMarkdown(accept http.Header) bool {
+ type quality struct{ specificity, params, q int }
+ best := [2]quality{{specificity: -1}, {specificity: -1}}
+ for _, field := range accept.Values("Accept") {
+ for _, raw := range splitAccept(field, ',') {
+ parts := splitAccept(raw, ';')
+ q, boundary, valid := 1000, len(parts), true
+ for i, param := range parts[1:] {
+ name, value, _ := strings.Cut(param, "=")
+ name = strings.ToLower(strings.TrimSpace(name))
+ if name == "q" {
+ if boundary != len(parts) {
+ valid = false
+ break
+ }
+ boundary = i + 1
+ q, valid = staticAcceptQuality(strings.TrimSpace(value))
+ if !valid {
+ break
+ }
+ } else if i+1 > boundary {
+ // Extensions have their own parameter namespace. A bare
+ // token is also a valid Accept extension.
+ if !isToken(strings.TrimSpace(param)) {
+ if _, _, err := mime.ParseMediaType("text/plain;" + param); err != nil {
+ valid = false
+ break
+ }
+ }
+ } else if name != "charset" {
+ valid = false
+ break
+ }
+ }
+ if !valid {
+ continue
+ }
+ media, params, err := mime.ParseMediaType(strings.Join(parts[:boundary], ";"))
+ if err != nil {
+ continue
+ }
+ for name, value := range params {
+ if name != "charset" || !strings.EqualFold(value, "utf-8") {
+ valid = false
+ break
+ }
+ }
+ if !valid {
+ continue
+ }
+ for i, target := range []string{"text/markdown", "text/html"} {
+ specificity := -1
+ switch media {
+ case "*/*":
+ specificity = 0
+ case "text/*":
+ specificity = 1
+ case target:
+ specificity = 2
+ }
+ if specificity < 0 {
+ continue
+ }
+ b := &best[i]
+ count := len(params)
+ if specificity > b.specificity || (specificity == b.specificity &&
+ (count > b.params || (count == b.params && q > b.q))) {
+ *b = quality{specificity, count, q}
+ }
+ }
+ }
+ }
+ return best[0].q > 0 && best[0].q > best[1].q
+}
+
+// splitAccept leaves quoted delimiters and escaped quotes inside their value.
+// ParseMediaType rejects malformed ranges after the split.
+func splitAccept(value string, delimiter byte) []string {
+ var parts []string
+ start, quoted, escaped := 0, false, false
+ for i := 0; i < len(value); i++ {
+ switch {
+ case escaped:
+ escaped = false
+ case quoted && value[i] == '\\':
+ escaped = true
+ case value[i] == '"':
+ quoted = !quoted
+ case !quoted && value[i] == delimiter:
+ parts = append(parts, value[start:i])
+ start = i + 1
+ }
+ }
+ return append(parts, value[start:])
+}
+
+// staticAcceptQuality accepts only HTTP's qvalue grammar, in thousandths.
+func staticAcceptQuality(value string) (int, bool) {
+ if len(value) == 0 || (value[0] != '0' && value[0] != '1') {
+ return 0, false
+ }
+ q := int(value[0]-'0') * 1000
+ if len(value) == 1 {
+ return q, true
+ }
+ if value[1] != '.' || len(value) > 5 {
+ return 0, false
+ }
+ place := 100
+ for i := 2; i < len(value); i++ {
+ if value[i] < '0' || value[i] > '9' || (value[0] == '1' && value[i] != '0') {
+ return 0, false
+ }
+ q += int(value[i]-'0') * place
+ place /= 10
+ }
+ return q, true
+}
diff --git a/internal/edge/static_markdown_test.go b/internal/edge/static_markdown_test.go
new file mode 100644
index 000000000..42b9eceb9
--- /dev/null
+++ b/internal/edge/static_markdown_test.go
@@ -0,0 +1,331 @@
+package edge
+
+import (
+ "compress/gzip"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/reqrec"
+)
+
+func TestStaticMarkdownPreference(t *testing.T) {
+ cases := []struct {
+ accept string
+ want bool
+ }{
+ {"", false},
+ {"*/*", false},
+ {"text/*", false},
+ {"text/markdown,text/html", false},
+ {"text/markdown", true},
+ {"text/markdown;q=0.8,text/html;q=0.2", true},
+ {"text/markdown;q=0.2,text/html;q=0.8", false},
+ {"text/markdown;q=0,text/*;q=1", false},
+ {"text/html;q=0,text/*;q=0.5", true},
+ {"text/markdown;q=0,text/html;q=0", false},
+ {"text/markdown;q=NaN,text/html", false},
+ {"text/markdown;q=1.001,text/html", false},
+ {"text/markdown;charset=iso-8859-1,text/html", false},
+ {"text/markdown;q=0.2,text/markdown;q=0.8,text/html;q=0.5", true},
+ {`text/markdown;charset="UTF-8";q=0.8,text/html;q=0.5`, true},
+ {"text/markdown;charset=utf-8;q=0,text/markdown;q=1,text/html;q=0.5", false},
+ {"text/*;charset=utf-8;q=1,text/markdown;q=0,text/html;q=0.5", false},
+ {"text/markdown;q=0.8;charset=iso-8859-1,text/html;q=0.5", true},
+ {"text/markdown;charset=utf-8;q=0.8;charset=iso-8859-1,text/html;q=0.5", true},
+ {"text/markdown;q=0.8;extension,text/html;q=0.5", true},
+ {"text/markdown;charset=utf-8;charset=utf-8;q=0.2,text/markdown;charset=utf-8;q=0.8,text/html;q=0.5", true},
+ {"text/markdown;unknown=value,text/html;q=0", false},
+ {"text/markdown;charset*=utf-8''utf-8,text/html;q=0", false},
+ {"application/json,text/html;q=0", false},
+ {"text/html;q=0,*/*;q=0.5", true},
+ {`text/markdown;note="a,text/html";q=1,text/html;q=0`, false},
+ {`text/markdown;q=1;note="a,\";b",text/html;q=0`, true},
+ {"text/markdown;q=0.001,text/html;q=0", true},
+ {"text/markdown;q=1.,text/html;q=0.", true},
+ }
+ for _, bad := range []string{"NaN", "Inf", "-1", "2", "1.001", "0.0001", ".5", "+0.5", "1e0", "", `"1"`} {
+ cases = append(cases, struct {
+ accept string
+ want bool
+ }{"text/markdown;q=" + bad + ",text/html;q=0", false})
+ }
+ for i, tc := range cases {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ // These quoted-comma cases stay whole; the remaining cases also
+ // exercise separate field lines and reversed range order.
+ variants := [][]string{{tc.accept}, {strings.ToUpper(tc.accept)}}
+ if !strings.Contains(tc.accept, `"`) {
+ parts := strings.Split(tc.accept, ",")
+ variants = append(variants, parts)
+ reversed := append([]string(nil), parts...)
+ for l, r := 0, len(reversed)-1; l < r; l, r = l+1, r-1 {
+ reversed[l], reversed[r] = reversed[r], reversed[l]
+ }
+ variants = append(variants, reversed, []string{strings.Join(reversed, ",")})
+ }
+ for _, fields := range variants {
+ h := make(http.Header)
+ for _, field := range fields {
+ if field != "" {
+ h.Add("Accept", field)
+ }
+ }
+ if got := prefersMarkdown(h); got != tc.want {
+ t.Errorf("Accept %q = %v, want %v", fields, got, tc.want)
+ }
+ }
+ })
+ }
+}
+
+func markdownTree(t *testing.T, files map[string]string) servedTree {
+ t.Helper()
+ tree := servedTree{dir: t.TempDir()}
+ for name, body := range files {
+ fp := filepath.Join(tree.dir, name)
+ if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(fp, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var err error
+ tree.redirects, err = parseRedirects([]byte(files[redirectsFile]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ tree.headers, err = parseHeaders([]byte(files[headersFile]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tree
+}
+
+func markdownRequest(tree servedTree, method, target string, headers http.Header, guard bool) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "http://example.com"+target, nil)
+ r.Header = headers.Clone()
+ if guard {
+ out := &outcome{guard: &guardState{mode: guardBlock, mint: func(reqrec.Tier, string) string { return "test" }}}
+ r = r.WithContext(context.WithValue(r.Context(), answeredKey{}, out))
+ }
+ w := httptest.NewRecorder()
+ var dest http.ResponseWriter = w
+ if gw := newGzipWriter(w, r); gw != nil {
+ dest = gw
+ defer gw.finish()
+ }
+ dest.Header().Set("Cache-Control", "no-cache")
+ dest.Header().Add("Vary", "Origin")
+ (&staticSite{app: "shop"}).serveTree(tree, dest, r)
+ return w
+}
+
+func markdownVary(t *testing.T, w *httptest.ResponseRecorder, want bool) {
+ t.Helper()
+ values := strings.Split(strings.Join(w.Header().Values("Vary"), ","), ",")
+ found, origin := false, false
+ for _, v := range values {
+ found = found || strings.EqualFold(strings.TrimSpace(v), "Accept")
+ origin = origin || strings.EqualFold(strings.TrimSpace(v), "Origin")
+ }
+ if found != want || !origin {
+ t.Errorf("Vary = %q, want Accept=%v and preserved Origin", values, want)
+ }
+}
+
+func TestStaticMarkdownResolution(t *testing.T) {
+ tree := markdownTree(t, map[string]string{
+ "shop/index.html": "<p>shop</p>", "shop/index.md": "# shop",
+ "page.html": "<p>page</p>", "page.md": "# page",
+ "only.html": "HTML only", "directory.html": "HTML directory", "directory.md/child": "child",
+ "link.html": "HTML link", "orphan/index.md": "orphan",
+ ".git/index.html": "secret HTML", ".git/index.md": "secret Markdown",
+ redirectsFile: "/rewrite /page.html 200\n/missing /page.html 404\n/blocked /.git/index.html 200\n/blocked-dir /.git 200\n",
+ headersFile: "/rewrite\n Cache-Control: public, max-age=60\n/page.html\n Cache-Control: public, max-age=120\n",
+ })
+ if err := os.Symlink(filepath.Join(tree.dir, "page.md"), filepath.Join(tree.dir, "link.md")); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ path, html, markdown string
+ twin bool
+ }{
+ {"/shop/", "<p>shop</p>", "# shop", true},
+ {"/page.html", "<p>page</p>", "# page", true},
+ {"/only.html", "HTML only", "HTML only", false},
+ {"/directory.html", "HTML directory", "HTML directory", false},
+ {"/link.html", "HTML link", "HTML link", false},
+ {"/page.md", "# page", "# page", false},
+ {"/rewrite?x=1", "<p>page</p>", "# page", true},
+ } {
+ for _, accept := range []string{"", "text/html", "text/markdown"} {
+ t.Run(tc.path+accept, func(t *testing.T) {
+ w := markdownRequest(tree, "GET", tc.path, http.Header{"Accept": {accept}}, false)
+ want := tc.html
+ if accept == "text/markdown" {
+ want = tc.markdown
+ }
+ if w.Code != 200 || w.Body.String() != want {
+ t.Fatalf("response = %d %q, want 200 %q", w.Code, w.Body.String(), want)
+ }
+ if tc.twin && accept == "text/markdown" && w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" {
+ t.Errorf("Content-Type = %q", w.Header().Get("Content-Type"))
+ }
+ markdownVary(t, w, tc.twin)
+ wantCache := "no-cache"
+ if strings.HasPrefix(tc.path, "/rewrite") {
+ wantCache = "public, max-age=60"
+ } else if tc.path == "/page.html" {
+ wantCache = "public, max-age=120"
+ }
+ if got := w.Header().Get("Cache-Control"); got != wantCache {
+ t.Errorf("Cache-Control = %q, want %q", got, wantCache)
+ }
+ })
+ }
+ }
+ for _, tc := range []struct{ path, location string }{{"/shop?x=1", "./shop/?x=1"}, {"/shop/index.html?x=1", "./?x=1"}} {
+ w := markdownRequest(tree, "GET", tc.path, http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 301 || w.Header().Get("Location") != tc.location {
+ t.Errorf("%s = %d %q, want 301 %q", tc.path, w.Code, w.Header().Get("Location"), tc.location)
+ }
+ }
+ for _, target := range []string{"/orphan/", "/orphan", "/orphan/index.html"} {
+ w := markdownRequest(tree, "GET", target, http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 404 || strings.Contains(w.Body.String(), "orphan") {
+ t.Errorf("%s = %d %q, want missing HTML", target, w.Code, w.Body.String())
+ }
+ }
+ for _, target := range []string{"/blocked", "/blocked-dir"} {
+ w := markdownRequest(tree, "GET", target, http.Header{"Accept": {"text/markdown"}}, true)
+ if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "secret") {
+ t.Errorf("hard-tier rewrite %s = %d %q", target, w.Code, w.Body.String())
+ }
+ }
+ w := markdownRequest(tree, "GET", "/missing", http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 404 || w.Body.String() != "# page" || w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" || w.Header().Get("ETag") != "" {
+ t.Errorf("404 rewrite = %d %q %v", w.Code, w.Body.String(), w.Header())
+ }
+ markdownVary(t, w, true)
+ only := markdownTree(t, map[string]string{"index.html": "HTML only"})
+ w = markdownRequest(only, "GET", "/", http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 200 || w.Body.String() != "HTML only" || w.Header().Get("Content-Type") != "text/html; charset=utf-8" {
+ t.Errorf("HTML-only tree = %d %q %v", w.Code, w.Body.String(), w.Header())
+ }
+ markdownVary(t, w, false)
+ t.Run("selected file disappears", func(t *testing.T) {
+ fp := filepath.Join(tree.dir, "page.html")
+ fi, err := os.Stat(fp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rep := selectStaticRepresentation(fp, fi, http.Header{"Accept": {"text/markdown"}})
+ if rep.path != filepath.Join(tree.dir, "page.md") {
+ t.Fatalf("selected %q, want Markdown sibling", rep.path)
+ }
+ if err := os.Remove(rep.path); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ (&staticSite{app: "shop"}).serveFile(rep.path, "/page.html", rep.info, rep.contentType, 200, nil, w, httptest.NewRequest("GET", "http://example.com/page.html", nil))
+ if w.Code != 404 || strings.Contains(w.Body.String(), "<p>page</p>") {
+ t.Errorf("removed twin = %d %q, want refusal", w.Code, w.Body.String())
+ }
+ })
+}
+
+func TestStaticMarkdownValidators(t *testing.T) {
+ body := strings.Repeat("same bytes for both representations\n", 100)
+ tree := markdownTree(t, map[string]string{"page.html": body, "page.md": body})
+ tags := make(map[string]string)
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}}, false)
+ if w.Code != 200 || w.Body.String() != body || w.Header().Get("ETag") == "" {
+ t.Fatalf("%s = %d %v", accept, w.Code, w.Header())
+ }
+ tags[accept] = w.Header().Get("ETag")
+ }
+ if tags["text/html"] == tags["text/markdown"] {
+ t.Error("identical bytes with different types share an ETag")
+ }
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ for tagType, tag := range tags {
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}, "If-None-Match": {tag}}, false)
+ want := 200
+ if tagType == accept {
+ want = 304
+ }
+ if w.Code != want || (want == 200 && w.Body.String() != body) || (want == 304 && w.Body.Len() != 0) {
+ t.Errorf("%s with %s tag = %d, want %d", accept, tagType, w.Code, want)
+ }
+ markdownVary(t, w, true)
+ }
+ for _, method := range []string{"GET", "HEAD"} {
+ w := markdownRequest(tree, method, "/page.html", http.Header{"Accept": {accept}, "Range": {"bytes=0-3"}}, false)
+ if w.Code != 206 || (method == "GET" && w.Body.String() != body[:4]) || (method == "HEAD" && w.Body.Len() != 0) {
+ t.Errorf("%s range %s = %d %q", accept, method, w.Code, w.Body.String())
+ }
+ if w.Header().Get("Content-Type") != accept+"; charset=utf-8" {
+ t.Errorf("range Content-Type = %q", w.Header().Get("Content-Type"))
+ }
+ markdownVary(t, w, true)
+ }
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}, "Accept-Encoding": {"gzip"}}, false)
+ if w.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(joinHeader(w.Header(), "Vary"), "Accept-Encoding") {
+ t.Fatalf("gzip headers = %v", w.Header())
+ }
+ markdownVary(t, w, true)
+ gz, err := gzip.NewReader(w.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded, err := io.ReadAll(gz)
+ gz.Close()
+ if err != nil || string(decoded) != body {
+ t.Fatalf("gzip body = %q, %v", decoded, err)
+ }
+ }
+ t.Run("forced type has its own memo and flight", func(t *testing.T) {
+ c := newTagCache()
+ fp, f, fi := openTagged(t, t.TempDir(), "page.html", body)
+ plain, _, err := c.tag(context.Background(), fp, f, fi, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ forced, ctype, err := c.tag(context.Background(), fp, f, fi, "text/markdown; charset=utf-8")
+ if err != nil || plain == forced || ctype != "text/markdown; charset=utf-8" || c.hashed.Load() != 2 {
+ t.Fatalf("forced tag = %q %q %v, ordinary %q, hashes %d", forced, ctype, err, plain, c.hashed.Load())
+ }
+ c = newTagCache()
+ c.wait = time.Millisecond
+ c.flights[staticTagKey{path: fp}] = make(chan struct{})
+ if _, _, err := c.tag(context.Background(), fp, f, fi, "text/markdown; charset=utf-8"); err != nil {
+ t.Fatalf("forced type waited on ordinary flight: %v", err)
+ }
+ })
+ t.Run("tag budget", func(t *testing.T) {
+ previous := staticTags
+ staticTags = newTagCache()
+ t.Cleanup(func() { staticTags = previous })
+ staticTags.wait = time.Millisecond
+ for i := 0; i < tagHashers; i++ {
+ staticTags.sem <- struct{}{}
+ }
+ large := strings.Repeat("x", tagInline+1)
+ tree := markdownTree(t, map[string]string{"page.html": "HTML", "page.md": large})
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {"text/markdown"}, "If-None-Match": {tags["text/html"]}}, false)
+ if w.Code != 200 || w.Body.String() != large || w.Header().Get("ETag") != "" || w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" {
+ t.Errorf("busy tag = %d, body length %d, headers %v", w.Code, w.Body.Len(), w.Header())
+ }
+ markdownVary(t, w, true)
+ })
+}