projects

showcase

A public git mirror

feat: add server with routing, security headers and raw content types

daniel daum committed parent 0ca2425 commit 4e72aad

Showing 10 changed files with 478 additions and 15 deletions.

README.md +4 −1
@@ -19,6 +19,8 @@ just test        # run tests1919just lint        # gofmt + go vet2020just golden      # rewrite golden files after an intended output change2121just render      # render the site once into ./out from ./config.json22just demo        # render the test fixtures and serve them on localhost:800023just run         # build from real Gitea every 10 min and serve on localhost:80002224```23252426## Configure@@ -34,7 +36,8 @@ just render      # render the site once into ./out from ./config.json3436    "repos": ["repo-a", "repo-b"],3537    "images": ["repo-a"],3638    "max_commits": 50,37    "theme": "moss"39    "theme": "moss",40    "trusted_proxies": ["100.64.0.10"]3841}3942```4043
cmd/daumdev/main.go +13 −2
@@ -13,6 +13,7 @@ import (13131414	"daum.dev/showcase/internal/build"1515	"daum.dev/showcase/internal/config"16	"daum.dev/showcase/internal/server"1617)17181819func main() {@@ -21,6 +22,8 @@ func main() {2122	out := flag.String("out", "", "output directory for -once (must not exist)")2223	data := flag.String("data", "/data", "data directory (git mirrors, site builds)")2324	every := flag.Duration("interval", 10*time.Minute, "time between builds")25	listen := flag.String("listen", ":8080", "address to serve on")26	serveDir := flag.String("serve-dir", "", "dev: serve this finished build instead of building")2427	flag.Parse()25282629	cfg, err := config.Load(*cfgPath)@@ -32,8 +35,16 @@ func main() {32353336	b := build.New(cfg, *data)3437	if !*once {35		slog.Warn("server not implemented yet; only building", "site", b.Current())36		b.Run(ctx, *every)38		srv := &server.Server{Cfg: cfg, Root: b.Current, Ready: b.Ready, Log: slog.Default()}39		if *serveDir != "" {40			srv.Root, srv.Ready = func() string { return *serveDir }, func() bool { return true }41		} else {42			go b.Run(ctx, *every)43		}44		slog.Info("listening", "addr", *listen)45		if err := srv.ListenAndServe(ctx, *listen); err != nil {46			fatal(err)47		}3748		return3849	}3950	if *out == "" {
docs/decisions.md +21 −0
@@ -106,3 +106,24 @@ details are in `docs/theme.md`. This replaces the spec's original106106  (so every `docker pull` shown actually works), and untagged `sha256:`107107  versions are hidden. Other package types are listed with no install command,108108  because their registries aren't proxied.109110## Server111112- Routes: `/`, `/healthz`, `/static/…` and `/<repo>/…` for allowlisted repos.113  Inside a repo, `raw/` serves files, `blob/<p>` serves `<p>.html`, paths114  ending in `/` serve `index.html`, and a folder without the slash redirects.115  Everything else, including any path with dot segments, `//`, `\` or NUL, is116  a 404 using the built `404.html`. `/index.html` itself is a 404 too.117- Methods other than GET and HEAD get a 404, and a GET or HEAD with a body118  gets a 400. Step 8 adds the git `POST` route.119- Raw files: png, jpg, gif and webp keep their image types. Files with a NUL120  in the first 512 bytes are `application/octet-stream` with121  `Content-Disposition: attachment`. Everything else, SVG and HTML included,122  is `text/plain`.123- Page responses get a 30s write deadline through `http.ResponseController`.124  The server itself has no `WriteTimeout`, so proxied clones can stream.125- Logs: for peers in `trusted_proxies`, the client IP comes from126  `CF-Connecting-IP`, or else the last `X-Forwarded-For` entry. Otherwise it's127  the TCP peer.128- `-serve-dir DIR` (dev only) serves a finished build without building; `just129  serve` and `just demo` use it.
internal/build/build.go +3 −0
@@ -107,6 +107,9 @@ func (b *Builder) Render(ctx context.Context, dir string) error {107107	if err := rd.Write(dir, "index.html", "profile", render.Page{Title: title, D: p}); err != nil {108108		return fmt.Errorf("profile: %w", err)109109	}110	if err := rd.Write(dir, "404.html", "notfound", render.Page{Title: "not found"}); err != nil {111		return err112	}110113	for _, rp := range repos {111114		if err := b.renderRepo(ctx, rd, dir, rp); err != nil {112115			return fmt.Errorf("%s: %w", rp.Name, err)
internal/config/config.go +11 −1
@@ -5,6 +5,7 @@ import (55	"bytes"66	"encoding/json"77	"fmt"8	"net/netip"89	"net/url"910	"os"1011	"regexp"@@ -21,13 +22,15 @@ type Config struct {2122	Images     []string          `json:"images"`2223	MaxCommits int               `json:"max_commits"`2324	Theme      string            `json:"theme"` // saturn palette, default moss25	// Proxies (IPs or CIDRs) whose X-Forwarded-For is believed, for logs only.26	TrustedProxies []string `json:"trusted_proxies"`2427}25282629var (2730	nameRe  = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)2831	imageRe = regexp.MustCompile(`^[a-z0-9]+([._-][a-z0-9]+)*(/[a-z0-9]+([._-][a-z0-9]+)*)*$`)2932	// Top-level names the site or router uses for itself.30	reserved = []string{"static", "v2", "healthz", "api", "user", "index.html"}33	reserved = []string{"static", "v2", "healthz", "api", "user", "index.html", "404.html"}3134	themes   = []string{"moss", "ink", "wine", "plum", "teal", "flexoki"}3235)3336@@ -78,6 +81,13 @@ func (c *Config) validate() error {7881			return fmt.Errorf("link %q must be an https url", k)7982		}8083	}84	for _, p := range c.TrustedProxies {85		if _, err := netip.ParsePrefix(p); err != nil {86			if _, err := netip.ParseAddr(p); err != nil {87				return fmt.Errorf("bad trusted proxy %q", p)88			}89		}90	}8191	if c.Theme == "" {8292		c.Theme = "moss"8393	}
internal/server/server.goadded +259 −0
@@ -0,0 +1,259 @@1// Package server serves the built site and, later, the git and registry2// pass-through. Anything not explicitly routed is a 404.3package server45import (6	"bytes"7	"context"8	"errors"9	"io"10	"log/slog"11	"net"12	"net/http"13	"net/netip"14	"os"15	"path"16	"path/filepath"17	"strings"18	"time"1920	"daum.dev/showcase/internal/config"21)2223const csp = "default-src 'none'; style-src 'self'; img-src 'self' https:; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"2425type Server struct {26	Cfg   *config.Config27	Root  func() string // directory of the current build28	Ready func() bool29	Log   *slog.Logger30}3132// ListenAndServe serves until ctx ends, then shuts down gracefully.33func (s *Server) ListenAndServe(ctx context.Context, addr string) error {34	srv := &http.Server{35		Addr:              addr,36		Handler:           s,37		ReadHeaderTimeout: 10 * time.Second,38		IdleTimeout:       60 * time.Second,39		// no WriteTimeout: clones and image layers can take long. Page routes40		// set their own 30s deadline.41	}42	go func() {43		<-ctx.Done()44		sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)45		defer cancel()46		srv.Shutdown(sctx)47	}()48	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {49		return err50	}51	return nil52}5354func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {55	start := time.Now()56	rec := &recorder{ResponseWriter: w, status: 200}57	s.route(rec, r)58	s.Log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.status,59		"took", time.Since(start).Round(time.Millisecond), "ip", s.clientIP(r))60}6162func (s *Server) route(w http.ResponseWriter, r *http.Request) {63	h := w.Header()64	h.Set("X-Content-Type-Options", "nosniff")65	h.Set("Referrer-Policy", "no-referrer")66	h.Set("Content-Security-Policy", csp)6768	if r.Method != http.MethodGet && r.Method != http.MethodHead {69		http.NotFound(w, r)70		return71	}72	if r.ContentLength != 0 || len(r.TransferEncoding) > 0 {73		http.Error(w, "request body not allowed", http.StatusBadRequest)74		return75	}76	http.NewResponseController(w).SetWriteDeadline(time.Now().Add(30 * time.Second))7778	p := r.URL.Path79	if p == "/healthz" {80		if !s.Ready() {81			http.Error(w, "no build yet", http.StatusServiceUnavailable)82			return83		}84		io.WriteString(w, "ok\n")85		return86	}87	if !clean(p) {88		s.notFound(w, r)89		return90	}91	if !s.Ready() {92		http.Error(w, "the site is being built, try again in a minute", http.StatusServiceUnavailable)93		return94	}9596	first, rest, _ := strings.Cut(strings.TrimPrefix(p, "/"), "/")97	switch {98	case p == "/":99		s.file(w, r, "index.html", "text/html; charset=utf-8")100	case first == "static" && rest != "":101		s.file(w, r, p, staticType(p))102	case !s.Cfg.HasRepo(first):103		s.notFound(w, r)104	case r.URL.Query().Has("go-get"): // `go get daum.dev/<repo>/sub/pkg`105		s.file(w, r, first+"/index.html", "text/html; charset=utf-8")106	case strings.HasPrefix(rest, "raw/"):107		s.raw(w, r, p)108	case strings.HasPrefix(rest, "blob/"):109		s.file(w, r, p+".html", "text/html; charset=utf-8")110	case rest == "" && !strings.HasSuffix(p, "/"), !strings.HasSuffix(p, "/") && s.isDir(p):111		http.Redirect(w, r, p+"/", http.StatusMovedPermanently)112	case strings.HasSuffix(p, "/"):113		s.file(w, r, p+"index.html", "text/html; charset=utf-8")114	default:115		s.notFound(w, r)116	}117}118119// clean rejects paths with dot segments, doubled slashes or NULs, so file120// lookups can't leave the build directory.121func clean(p string) bool {122	if !strings.HasPrefix(p, "/") || strings.ContainsRune(p, 0) || strings.Contains(p, "\\") {123		return false124	}125	c := path.Clean(p)126	return c == p || c+"/" == p127}128129func (s *Server) isDir(p string) bool {130	fi, err := os.Stat(filepath.Join(s.Root(), filepath.FromSlash(p)))131	return err == nil && fi.IsDir()132}133134// open returns a regular file inside the current build, or nil.135func (s *Server) open(p string) (*os.File, os.FileInfo) {136	f, err := os.Open(filepath.Join(s.Root(), filepath.FromSlash(p)))137	if err != nil {138		return nil, nil139	}140	fi, err := f.Stat()141	if err != nil || !fi.Mode().IsRegular() {142		f.Close()143		return nil, nil144	}145	return f, fi146}147148func (s *Server) file(w http.ResponseWriter, r *http.Request, p, ctype string) {149	f, fi := s.open(p)150	if f == nil {151		s.notFound(w, r)152		return153	}154	defer f.Close()155	w.Header().Set("Content-Type", ctype)156	cache := "public, max-age=60"157	if strings.HasPrefix(p, "/static/") {158		cache = "public, max-age=86400"159	}160	w.Header().Set("Cache-Control", cache)161	http.ServeContent(w, r, "", fi.ModTime(), f)162}163164// raw serves repo files: allowed image types as themselves, text as165// text/plain, anything else as a download. Never as HTML, SVG or script.166func (s *Server) raw(w http.ResponseWriter, r *http.Request, p string) {167	f, fi := s.open(p)168	if f == nil {169		s.notFound(w, r)170		return171	}172	defer f.Close()173	ctype := staticType(p)174	if !strings.HasPrefix(ctype, "image/") {175		head := make([]byte, 512)176		n, _ := io.ReadFull(f, head)177		f.Seek(0, io.SeekStart)178		ctype = "text/plain; charset=utf-8"179		if bytes.IndexByte(head[:n], 0) >= 0 {180			ctype = "application/octet-stream"181			w.Header().Set("Content-Disposition", "attachment")182		}183	}184	w.Header().Set("Content-Type", ctype)185	w.Header().Set("Cache-Control", "public, max-age=60")186	http.ServeContent(w, r, "", fi.ModTime(), f)187}188189func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {190	f, _ := s.open("404.html")191	if f == nil {192		http.NotFound(w, r)193		return194	}195	defer f.Close()196	w.Header().Set("Content-Type", "text/html; charset=utf-8")197	w.WriteHeader(http.StatusNotFound)198	if r.Method != http.MethodHead {199		io.Copy(w, f)200	}201}202203// staticType is the content type for files we produced or allow as images.204func staticType(p string) string {205	switch strings.ToLower(path.Ext(p)) {206	case ".css":207		return "text/css; charset=utf-8"208	case ".woff2":209		return "font/woff2"210	case ".png":211		return "image/png"212	case ".jpg", ".jpeg":213		return "image/jpeg"214	case ".gif":215		return "image/gif"216	case ".webp":217		return "image/webp"218	}219	return "text/plain; charset=utf-8"220}221222// clientIP uses X-Forwarded-For only when the peer is a trusted proxy.223func (s *Server) clientIP(r *http.Request) string {224	host, _, _ := net.SplitHostPort(r.RemoteAddr)225	peer, err := netip.ParseAddr(host)226	if err != nil {227		return host228	}229	for _, t := range s.Cfg.TrustedProxies {230		pre, err := netip.ParsePrefix(t)231		if err != nil {232			a := netip.MustParseAddr(t) // validated by config233			pre = netip.PrefixFrom(a, a.BitLen())234		}235		if !pre.Contains(peer.Unmap()) {236			continue237		}238		if cf := r.Header.Get("CF-Connecting-IP"); cf != "" {239			return cf240		}241		if xff := r.Header.Get("X-Forwarded-For"); xff != "" {242			parts := strings.Split(xff, ",")243			return strings.TrimSpace(parts[len(parts)-1])244		}245	}246	return host247}248249type recorder struct {250	http.ResponseWriter251	status int252}253254func (r *recorder) WriteHeader(code int) {255	r.status = code256	r.ResponseWriter.WriteHeader(code)257}258259func (r *recorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
internal/server/server_test.goadded +140 −0
@@ -0,0 +1,140 @@1package server23import (4	"io"5	"log/slog"6	"net/http"7	"net/http/httptest"8	"os"9	"path/filepath"10	"strings"11	"testing"1213	"daum.dev/showcase/internal/config"14)1516func testServer(t *testing.T, ready bool) *Server {17	t.Helper()18	root := t.TempDir()19	files := map[string]string{20		"index.html":                  "home",21		"404.html":                    "<h1>not found</h1>",22		"static/style.css":            "body{}",23		"static/fonts/x.woff2":        "font",24		"repo-a/index.html":           "repo page",25		"repo-a/tree/docs/index.html": "docs dir",26		"repo-a/blob/main.go.html":    "main.go page",27		"repo-a/raw/main.go":          "package main",28		"repo-a/raw/logo.png":         "\x89PNG",29		"repo-a/raw/evil.svg":         "<svg onload=alert(1)>",30		"repo-a/raw/page.html":        "<script>alert(1)</script>",31		"repo-a/raw/data.bin":         "bin\x00ary",32		"repo-a/log/index.html":       "log",33		"secret/index.html":           "unlisted repo left on disk",34	}35	for name, body := range files {36		p := filepath.Join(root, name)37		os.MkdirAll(filepath.Dir(p), 0o755)38		os.WriteFile(p, []byte(body), 0o644)39	}40	return &Server{41		Cfg:   &config.Config{Repos: []string{"repo-a"}, TrustedProxies: []string{"10.0.0.1"}},42		Root:  func() string { return root },43		Ready: func() bool { return ready },44		Log:   slog.New(slog.NewTextHandler(io.Discard, nil)),45	}46}4748func do(s *Server, method, target string, body io.Reader) *httptest.ResponseRecorder {49	w := httptest.NewRecorder()50	req := httptest.NewRequest(method, target, body)51	s.ServeHTTP(w, req)52	return w53}5455func TestRoutes(t *testing.T) {56	s := testServer(t, true)57	cases := []struct {58		method, path string59		status       int60		ctype, body  string61	}{62		{"GET", "/", 200, "text/html", "home"},63		{"HEAD", "/", 200, "text/html", ""},64		{"GET", "/healthz", 200, "", "ok"},65		{"GET", "/static/style.css", 200, "text/css", "body{}"},66		{"GET", "/static/fonts/x.woff2", 200, "font/woff2", ""},67		{"GET", "/repo-a/", 200, "text/html", "repo page"},68		{"GET", "/repo-a", 301, "", ""},69		{"GET", "/repo-a/tree/docs", 301, "", ""},70		{"GET", "/repo-a/tree/docs/", 200, "text/html", "docs dir"},71		{"GET", "/repo-a/blob/main.go", 200, "text/html", "main.go page"},72		{"GET", "/repo-a/log/", 200, "text/html", "log"},73		{"GET", "/repo-a/sub/pkg?go-get=1", 200, "text/html", "repo page"},74		// raw: images as images, everything else as text or a download75		{"GET", "/repo-a/raw/main.go", 200, "text/plain", "package main"},76		{"GET", "/repo-a/raw/logo.png", 200, "image/png", ""},77		{"GET", "/repo-a/raw/evil.svg", 200, "text/plain", ""},78		{"GET", "/repo-a/raw/page.html", 200, "text/plain", ""},79		{"GET", "/repo-a/raw/data.bin", 200, "application/octet-stream", ""},80		// default 404: Gitea's UI and API, unlisted repos, odd paths81		{"GET", "/repo-a/blob/missing", 404, "text/html", "not found"},82		{"GET", "/secret/", 404, "", ""},83		{"GET", "/api/v1/users/daniel", 404, "", ""},84		{"GET", "/user/login", 404, "", ""},85		{"GET", "/daniel/repo-a", 404, "", ""},86		{"GET", "/repo-a/raw/../../secret/index.html", 404, "", ""},87		{"GET", "/repo-a//index.html", 404, "", ""},88		{"GET", "/static/", 404, "", ""},89		{"GET", "/index.html", 404, "", ""},90		{"POST", "/", 404, "", ""},91		{"PUT", "/repo-a/", 404, "", ""},92		{"DELETE", "/repo-a/", 404, "", ""},93	}94	for _, c := range cases {95		w := do(s, c.method, c.path, nil)96		if w.Code != c.status {97			t.Errorf("%s %s: status %d, want %d", c.method, c.path, w.Code, c.status)98			continue99		}100		if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, c.ctype) {101			t.Errorf("%s %s: content type %q, want %q", c.method, c.path, ct, c.ctype)102		}103		if !strings.Contains(w.Body.String(), c.body) {104			t.Errorf("%s %s: body %q lacks %q", c.method, c.path, w.Body.String(), c.body)105		}106		if w.Header().Get("Content-Security-Policy") != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" ||107			w.Header().Get("Referrer-Policy") != "no-referrer" {108			t.Errorf("%s %s: missing security headers", c.method, c.path)109		}110	}111}112113func TestBodyRejected(t *testing.T) {114	if w := do(testServer(t, true), "GET", "/", strings.NewReader("x")); w.Code != http.StatusBadRequest {115		t.Errorf("GET with body: %d", w.Code)116	}117}118119func TestNotReady(t *testing.T) {120	s := testServer(t, false)121	for _, p := range []string{"/", "/healthz", "/repo-a/"} {122		if w := do(s, "GET", p, nil); w.Code != http.StatusServiceUnavailable {123			t.Errorf("%s before first build: %d, want 503", p, w.Code)124		}125	}126}127128func TestClientIP(t *testing.T) {129	s := testServer(t, true)130	req := httptest.NewRequest("GET", "/", nil)131	req.Header.Set("X-Forwarded-For", "1.2.3.4")132	req.RemoteAddr = "192.0.2.9:5555"133	if ip := s.clientIP(req); ip != "192.0.2.9" {134		t.Errorf("untrusted peer: got %s", ip)135	}136	req.RemoteAddr = "10.0.0.1:5555"137	if ip := s.clientIP(req); ip != "1.2.3.4" {138		t.Errorf("trusted peer: got %s", ip)139	}140}
justfile +9 −11
@@ -25,19 +25,17 @@ render config="config.json":2525    rm -rf out2626    go run ./cmd/daumdev -config {{config}} -data .data -once -out out272728# Serve ./out on localhost:8000 (stand-in until the real server exists; maps /blob/<path> to <path>.html)29serve:30    #!/usr/bin/env python331    import http.server, os32    class H(http.server.SimpleHTTPRequestHandler):33        def translate_path(self, path):34            p = super().translate_path(path)35            return p + ".html" if "/blob/" in path and os.path.isfile(p + ".html") else p36    os.chdir("out")37    http.server.ThreadingHTTPServer(("127.0.0.1", 8000), H).serve_forever()28# Serve the finished build in ./out on localhost:8000 with the real server29serve config="testdata/demo.json":30    go run ./cmd/daumdev -config {{config}} -serve-dir out -listen 127.0.0.1:80003132# Build from real Gitea every 10 minutes and serve on localhost:8000 (needs ./config.json)33run config="config.json":34    go run ./cmd/daumdev -config {{config}} -data .data -listen 127.0.0.1:800038353936# Render from real Gitea (needs ./config.json) and serve it40preview config="config.json": (render config) serve37preview config="config.json": (render config)38    just serve {{config}}41394240# Render the test fixtures (no Gitea needed) and serve them4341demo:
testdata/demo.jsonadded +12 −0
@@ -0,0 +1,12 @@1{2    "gitea_url": "http://127.0.0.1:1",3    "user": "daniel",4    "site_url": "https://daum.dev",5    "links": {6        "website": "https://danieldaum.net",7        "atproto": "https://bsky.app/profile/daum.dev",8        "github": "https://github.com/example"9    },10    "repos": ["repo-a", "repo-b"],11    "images": ["repo-a"]12}
web/templates/notfound.htmladded +6 −0
@@ -0,0 +1,6 @@1{{define "content" -}}2<header class="page-header">3  <h1>not found</h1>4  <p class="meta">nothing lives at this address. <a href="/">back to the repositories</a>.</p>5</header>6{{- end}}