showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
server.go
8.4 KB · 301 lines
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/http/httputil"14 "net/netip"15 "os"16 "path"17 "path/filepath"18 "strings"19 "time"2021 "daum.dev/showcase/internal/config"22)2324// script-src 'self' is only for /static/theme.js (palette) and copy.js (copy25// buttons); nothing inline. connect-src 'self' lets copy.js fetch the raw26// file it copies, from this origin only.27const csp = "default-src 'none'; connect-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' https:; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"2829type Server struct {30 Cfg *config.Config31 Root func() string // directory of the current build32 Ready func() bool33 Log *slog.Logger34 proxy *httputil.ReverseProxy35 // gitSlots caps concurrent git proxy requests at maxGitProxied36 gitSlots chan struct{}37}3839func New(cfg *config.Config, root func() string, ready func() bool, log *slog.Logger) *Server {40 s := &Server{Cfg: cfg, Root: root, Ready: ready, Log: log, gitSlots: make(chan struct{}, maxGitProxied)}41 s.proxy = s.newProxy()42 return s43}4445// ListenAndServe serves until ctx ends, then shuts down gracefully.46func (s *Server) ListenAndServe(ctx context.Context, addr string) error {47 srv := &http.Server{48 Addr: addr,49 Handler: s,50 ReadHeaderTimeout: 10 * time.Second,51 IdleTimeout: 60 * time.Second,52 // no WriteTimeout: clones and image layers can take long. Page routes53 // set their own 30s deadline.54 }55 go func() {56 <-ctx.Done()57 sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)58 defer cancel()59 srv.Shutdown(sctx)60 }()61 if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {62 return err63 }64 return nil65}6667func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {68 start := time.Now()69 rec := &recorder{ResponseWriter: w, status: 200}70 s.route(rec, r)71 s.Log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.status,72 "took", time.Since(start).Round(time.Millisecond), "ip", s.clientIP(r))73}7475func (s *Server) route(w http.ResponseWriter, r *http.Request) {76 h := w.Header()77 h.Set("X-Content-Type-Options", "nosniff")78 h.Set("Referrer-Policy", "no-referrer")79 h.Set("Content-Security-Policy", csp)80 if s.proxyRoute(w, r) { // works before the first build, too81 return82 }8384 if r.Method != http.MethodGet && r.Method != http.MethodHead {85 http.NotFound(w, r)86 return87 }88 if r.ContentLength != 0 || len(r.TransferEncoding) > 0 {89 http.Error(w, "request body not allowed", http.StatusBadRequest)90 return91 }92 http.NewResponseController(w).SetWriteDeadline(time.Now().Add(30 * time.Second))9394 p := r.URL.Path95 if p == "/healthz" {96 if !s.Ready() {97 http.Error(w, "no build yet", http.StatusServiceUnavailable)98 return99 }100 io.WriteString(w, "ok\n")101 return102 }103 if !clean(p) {104 s.notFound(w, r)105 return106 }107 // Under a base_path the pages live at base/…; old root URLs redirect108 // there. `go get` keeps asking at the root (the module path doesn't move).109 base := s.Cfg.BasePath110 if base != "" {111 switch {112 case strings.HasPrefix(p, base+"/"):113 p = strings.TrimPrefix(p, base)114 case r.URL.Query().Has("go-get"):115 case p == base:116 http.Redirect(w, r, base+"/", http.StatusMovedPermanently)117 return118 default:119 http.Redirect(w, r, base+p, http.StatusMovedPermanently)120 return121 }122 }123 if !s.Ready() {124 http.Error(w, "the site is being built, try again in a minute", http.StatusServiceUnavailable)125 return126 }127128 first, rest, _ := strings.Cut(strings.TrimPrefix(p, "/"), "/")129 switch {130 case p == "/":131 s.file(w, r, "index.html", "text/html; charset=utf-8")132 case p == "/repos/": // every repo; the profile shows the featured ones133 s.file(w, r, "repos/index.html", "text/html; charset=utf-8")134 case p == "/repos":135 http.Redirect(w, r, base+"/repos/", http.StatusMovedPermanently)136 case first == "static" && rest != "":137 s.file(w, r, p, staticType(p))138 case !s.Cfg.HasRepo(first):139 s.notFound(w, r)140 case r.URL.Query().Has("go-get"): // `go get daum.dev/<repo>/sub/pkg`141 s.file(w, r, first+"/index.html", "text/html; charset=utf-8")142 case strings.HasPrefix(rest, "raw/"):143 s.raw(w, r, p)144 case strings.HasPrefix(rest, "blob/"):145 s.file(w, r, p+".html", "text/html; charset=utf-8")146 case rest == "" && !strings.HasSuffix(p, "/"), !strings.HasSuffix(p, "/") && s.isDir(p):147 http.Redirect(w, r, base+p+"/", http.StatusMovedPermanently)148 case strings.HasSuffix(p, "/"):149 s.file(w, r, p+"index.html", "text/html; charset=utf-8")150 default:151 s.notFound(w, r)152 }153}154155// clean rejects paths with dot segments, doubled slashes or NULs, so file156// lookups can't leave the build directory.157func clean(p string) bool {158 if !strings.HasPrefix(p, "/") || strings.ContainsRune(p, 0) || strings.Contains(p, "\\") {159 return false160 }161 c := path.Clean(p)162 return c == p || c+"/" == p163}164165func (s *Server) isDir(p string) bool {166 fi, err := os.Stat(filepath.Join(s.Root(), filepath.FromSlash(p)))167 return err == nil && fi.IsDir()168}169170// open returns a regular file inside the current build, or nil.171func (s *Server) open(p string) (*os.File, os.FileInfo) {172 f, err := os.Open(filepath.Join(s.Root(), filepath.FromSlash(p)))173 if err != nil {174 return nil, nil175 }176 fi, err := f.Stat()177 if err != nil || !fi.Mode().IsRegular() {178 f.Close()179 return nil, nil180 }181 return f, fi182}183184func (s *Server) file(w http.ResponseWriter, r *http.Request, p, ctype string) {185 f, fi := s.open(p)186 if f == nil {187 s.notFound(w, r)188 return189 }190 defer f.Close()191 w.Header().Set("Content-Type", ctype)192 cache := "public, max-age=60"193 if strings.HasPrefix(p, "/static/") {194 cache = "public, max-age=86400"195 }196 w.Header().Set("Cache-Control", cache)197 http.ServeContent(w, r, "", fi.ModTime(), f)198}199200// raw serves repo files: allowed image types as themselves, text as201// text/plain, anything else as a download. Never as HTML, SVG or script.202func (s *Server) raw(w http.ResponseWriter, r *http.Request, p string) {203 f, fi := s.open(p)204 if f == nil {205 s.notFound(w, r)206 return207 }208 defer f.Close()209 ctype := staticType(p)210 if !strings.HasPrefix(ctype, "image/") || ctype == "image/svg+xml" { // repo SVGs are never images here211 head := make([]byte, 512)212 n, _ := io.ReadFull(f, head)213 f.Seek(0, io.SeekStart)214 ctype = "text/plain; charset=utf-8"215 if bytes.IndexByte(head[:n], 0) >= 0 {216 ctype = "application/octet-stream"217 w.Header().Set("Content-Disposition", "attachment")218 }219 }220 w.Header().Set("Content-Type", ctype)221 w.Header().Set("Cache-Control", "public, max-age=60")222 http.ServeContent(w, r, "", fi.ModTime(), f)223}224225func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {226 f, _ := s.open("404.html")227 if f == nil {228 http.NotFound(w, r)229 return230 }231 defer f.Close()232 w.Header().Set("Content-Type", "text/html; charset=utf-8")233 w.WriteHeader(http.StatusNotFound)234 if r.Method != http.MethodHead {235 io.Copy(w, f)236 }237}238239// staticType is the content type for files we produced or allow as images.240func staticType(p string) string {241 switch strings.ToLower(path.Ext(p)) {242 case ".css":243 return "text/css; charset=utf-8"244 case ".woff2":245 return "font/woff2"246 case ".js":247 return "text/javascript; charset=utf-8"248 case ".svg":249 return "image/svg+xml"250 case ".webmanifest":251 return "application/manifest; charset=utf-8"252 case ".png":253 return "image/png"254 case ".jpg", ".jpeg":255 return "image/jpeg"256 case ".gif":257 return "image/gif"258 case ".webp":259 return "image/webp"260 }261 return "text/plain; charset=utf-8"262}263264// clientIP uses X-Forwarded-For only when the peer is a trusted proxy.265func (s *Server) clientIP(r *http.Request) string {266 host, _, _ := net.SplitHostPort(r.RemoteAddr)267 peer, err := netip.ParseAddr(host)268 if err != nil {269 return host270 }271 for _, t := range s.Cfg.TrustedProxies {272 pre, err := netip.ParsePrefix(t)273 if err != nil {274 a := netip.MustParseAddr(t) // validated by config275 pre = netip.PrefixFrom(a, a.BitLen())276 }277 if !pre.Contains(peer.Unmap()) {278 continue279 }280 if cf := r.Header.Get("CF-Connecting-IP"); cf != "" {281 return cf282 }283 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {284 parts := strings.Split(xff, ",")285 return strings.TrimSpace(parts[len(parts)-1])286 }287 }288 return host289}290291type recorder struct {292 http.ResponseWriter293 status int294}295296func (r *recorder) WriteHeader(code int) {297 r.status = code298 r.ResponseWriter.WriteHeader(code)299}300301func (r *recorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }