diff --git a/internal/server/handlers.go b/internal/server/handlers.go index a04047f..f85af1f 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -145,7 +145,7 @@ func (s *Server) isHTTPS(r *http.Request) bool { } func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) { - renderTemplate(w, "index.html", pageData{BaseURL: s.baseURL(r), LoggedIn: s.isLoggedIn(r), CSRFToken: csrfToken(w, r)}) + renderTemplate(w, "index.html", pageData{BaseURL: s.baseURL(r), LoggedIn: s.isLoggedIn(r), CSRFToken: s.csrfToken(w, r)}) } func (s *Server) handleShorten(w http.ResponseWriter, r *http.Request) { @@ -256,7 +256,7 @@ func (s *Server) renderIndex(w http.ResponseWriter, r *http.Request, errMsg, sho OriginalURL: originalURL, QRSVG: qrsvg, LoggedIn: s.isLoggedIn(r), - CSRFToken: csrfToken(w, r), + CSRFToken: s.csrfToken(w, r), }) } @@ -291,14 +291,14 @@ func (s *Server) handleRedirect(w http.ResponseWriter, r *http.Request) { // Admin handlers func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) { - renderTemplate(w, "admin_login.html", pageData{BaseURL: s.baseURL(r), CSRFToken: csrfToken(w, r)}) + renderTemplate(w, "admin_login.html", pageData{BaseURL: s.baseURL(r), CSRFToken: s.csrfToken(w, r)}) } func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { // Throttle login attempts per IP to slow brute force. if !s.authLimiter.Allow(clientIP(r, s.cfg.Server.TrustProxy)) { w.WriteHeader(http.StatusTooManyRequests) - renderTemplate(w, "admin_login.html", pageData{Error: "Too many attempts. Please wait a moment.", CSRFToken: csrfToken(w, r)}) + renderTemplate(w, "admin_login.html", pageData{Error: "Too many attempts. Please wait a moment.", CSRFToken: s.csrfToken(w, r)}) return } @@ -313,12 +313,12 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { if !available { w.Header().Set("Retry-After", "1") w.WriteHeader(http.StatusServiceUnavailable) - renderTemplate(w, "admin_login.html", pageData{Error: "Server busy. Please try again.", CSRFToken: csrfToken(w, r)}) + renderTemplate(w, "admin_login.html", pageData{Error: "Server busy. Please try again.", CSRFToken: s.csrfToken(w, r)}) return } if !userOK || !pwOK { w.WriteHeader(http.StatusUnauthorized) - renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: csrfToken(w, r)}) + renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: s.csrfToken(w, r)}) return } @@ -362,7 +362,7 @@ func (s *Server) adminPage(w http.ResponseWriter, r *http.Request, nav string) p BaseURL: s.baseURL(r), LoggedIn: true, ActiveNav: nav, - CSRFToken: csrfToken(w, r), + CSRFToken: s.csrfToken(w, r), UploadMaxMB: s.cfg.Upload.MaxSize, } } @@ -814,6 +814,36 @@ func scaleImage(src image.Image, maxDim int) image.Image { return dst } +// maxDecodePixels caps the pixel count of images we are willing to fully +// decode. A small compressed file can declare enormous dimensions (a +// decompression bomb): 24 MP decodes to ~96 MB of NRGBA, which is already a +// big bite on an RPi Zero — anything larger is rejected before decode. +const maxDecodePixels = 24 << 20 + +// decodeImageBounded decodes an image file, but reads only the header first +// and refuses files whose decoded size would exceed maxDecodePixels. The +// dimension product uses int64 so a malicious header cannot overflow 32-bit +// int on ARMv5. +func decodeImageBounded(path string) (image.Image, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + cfg, _, err := image.DecodeConfig(f) + if err != nil { + return nil, err + } + if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxDecodePixels { + return nil, fmt.Errorf("image dimensions too large (%dx%d, max %d megapixels)", cfg.Width, cfg.Height, maxDecodePixels>>20) + } + if _, err := f.Seek(0, io.SeekStart); err != nil { + return nil, err + } + src, _, err := image.Decode(f) + return src, err +} + // ---- Thumbnails ---- const thumbMaxDim = 512 // long-side size of generated thumbnails, in pixels @@ -838,12 +868,7 @@ func (s *Server) generateThumbnail(filename string) error { if !isImageFile(filename) { return fmt.Errorf("not an image") } - f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, filename)) - if err != nil { - return err - } - src, _, err := image.Decode(f) - f.Close() + src, err := decodeImageBounded(filepath.Join(s.cfg.Upload.Dir, filename)) if err != nil { return err } @@ -1108,15 +1133,13 @@ func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request) } path := filepath.Join(s.cfg.Upload.Dir, filename) - f, err := os.Open(path) - if err != nil { + if _, err := os.Stat(path); err != nil { jsonError(w, "File not found", http.StatusNotFound) return } - src, _, err := image.Decode(f) - f.Close() + src, err := decodeImageBounded(path) if err != nil { - jsonError(w, "Failed to decode image", http.StatusInternalServerError) + jsonError(w, "Failed to decode image: "+err.Error(), http.StatusUnprocessableEntity) return } diff --git a/internal/server/handlers_test.go b/internal/server/handlers_test.go new file mode 100644 index 0000000..14e2b7d --- /dev/null +++ b/internal/server/handlers_test.go @@ -0,0 +1,367 @@ +package server + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "image" + "image/png" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "glimmer/internal/config" + "glimmer/internal/db" + "golang.org/x/crypto/bcrypt" +) + +// webTestServer builds a Server wired like production (DB, sessions, upload +// dir, templates) for exercising the web handlers. mutate can adjust the +// config before the server is built. +func webTestServer(t *testing.T, mutate func(*config.Config)) *Server { + t.Helper() + initTemplates() + database, err := db.Open(filepath.Join(t.TempDir(), "urls.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = database.Close() }) + + cfg := &config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8888"}, + Admin: config.AdminConfig{Username: "admin", SessionHours: 1}, + Slugs: config.SlugConfig{Length: 3}, + Upload: config.UploadConfig{Dir: t.TempDir(), MaxSize: 50}, + } + if mutate != nil { + mutate(cfg) + } + return &Server{ + cfg: cfg, + db: database, + sessions: newSessionStore(database, time.Hour), + limiter: newRateLimiter(0), + authLimiter: newRateLimiter(0), + bcryptSem: make(chan struct{}, 1), + } +} + +func sessionCookie(t *testing.T, s *Server) *http.Cookie { + t.Helper() + token, err := s.sessions.Create() + if err != nil { + t.Fatalf("create session: %v", err) + } + return &http.Cookie{Name: "session", Value: token} +} + +// ---- Auth ---- + +func TestRequireAuthRedirectsAnonymous(t *testing.T) { + s := webTestServer(t, nil) + handler := s.requireAuth(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("handler must not run without a session") + }) + + req := httptest.NewRequest(http.MethodGet, "/admin", nil) + rec := httptest.NewRecorder() + handler(rec, req) + + if rec.Code != http.StatusSeeOther { + t.Fatalf("expected 303, got %d", rec.Code) + } + if loc := rec.Header().Get("Location"); loc != "/admin/login" { + t.Fatalf("expected redirect to /admin/login, got %q", loc) + } +} + +func TestRequireAuthAcceptsValidSession(t *testing.T) { + s := webTestServer(t, nil) + called := false + handler := s.requireAuth(func(w http.ResponseWriter, r *http.Request) { called = true }) + + req := httptest.NewRequest(http.MethodGet, "/admin", nil) + req.AddCookie(sessionCookie(t, s)) + handler(httptest.NewRecorder(), req) + + if !called { + t.Fatal("handler should run with a valid session") + } +} + +func TestLoginWrongPasswordRejected(t *testing.T) { + hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse"), bcrypt.MinCost) + if err != nil { + t.Fatalf("bcrypt: %v", err) + } + s := webTestServer(t, func(cfg *config.Config) { + cfg.Admin.PasswordHash = string(hash) + }) + + form := url.Values{"username": {"admin"}, "password": {"wrong"}} + req := httptest.NewRequest(http.MethodPost, "/admin/login", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rec := httptest.NewRecorder() + s.handleLogin(rec, req) + + if rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", rec.Code) + } + for _, c := range rec.Result().Cookies() { + if c.Name == "session" { + t.Fatal("no session cookie may be set on failed login") + } + } +} + +func TestLoginSuccessSetsSessionCookie(t *testing.T) { + hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse"), bcrypt.MinCost) + if err != nil { + t.Fatalf("bcrypt: %v", err) + } + s := webTestServer(t, func(cfg *config.Config) { + cfg.Admin.PasswordHash = string(hash) + }) + + form := url.Values{"username": {"admin"}, "password": {"correct-horse"}} + req := httptest.NewRequest(http.MethodPost, "/admin/login", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rec := httptest.NewRecorder() + s.handleLogin(rec, req) + + if rec.Code != http.StatusSeeOther { + t.Fatalf("expected 303, got %d body=%s", rec.Code, rec.Body.String()) + } + var session *http.Cookie + for _, c := range rec.Result().Cookies() { + if c.Name == "session" { + session = c + } + } + if session == nil || session.Value == "" { + t.Fatal("expected a session cookie on successful login") + } + if !session.HttpOnly { + t.Fatal("session cookie must be HttpOnly") + } + if !s.sessions.Valid(session.Value) { + t.Fatal("issued session token should validate") + } +} + +// ---- CSRF ---- + +func TestRequireCSRFRejectsMissingToken(t *testing.T) { + s := webTestServer(t, nil) + handler := s.requireCSRF(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("handler must not run without a CSRF token") + }) + + req := httptest.NewRequest(http.MethodPost, "/admin/delete/1", nil) + rec := httptest.NewRecorder() + handler(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403, got %d", rec.Code) + } +} + +func TestRequireCSRFAcceptsMatchingToken(t *testing.T) { + s := webTestServer(t, nil) + called := false + handler := s.requireCSRF(func(w http.ResponseWriter, r *http.Request) { called = true }) + + token := strings.Repeat("a", 64) + form := url.Values{"csrf_token": {token}} + req := httptest.NewRequest(http.MethodPost, "/admin/delete/1", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.AddCookie(&http.Cookie{Name: "csrf", Value: token}) + handler(httptest.NewRecorder(), req) + + if !called { + t.Fatal("handler should run with matching CSRF cookie and form token") + } +} + +func TestResizeRejectsMissingCSRF(t *testing.T) { + s := webTestServer(t, nil) + + req := httptest.NewRequest(http.MethodPost, "/admin/uploads/resize/x", strings.NewReader("max_dim=512")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.SetPathValue("filename", strings.Repeat("a", 32)+".png") + rec := httptest.NewRecorder() + s.handleAdminUploadResize(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 without CSRF token, got %d", rec.Code) + } +} + +func TestCSRFCookieSecureFollowsBaseURL(t *testing.T) { + s := webTestServer(t, func(cfg *config.Config) { + cfg.Server.BaseURL = "https://luci.ooo" + }) + rec := httptest.NewRecorder() + s.csrfToken(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + + var csrf *http.Cookie + for _, c := range rec.Result().Cookies() { + if c.Name == "csrf" { + csrf = c + } + } + if csrf == nil { + t.Fatal("expected a csrf cookie to be set") + } + if !csrf.Secure { + t.Fatal("csrf cookie must be Secure when base_url is https") + } +} + +// ---- Upload serving ---- + +func writeUploadFile(t *testing.T, s *Server, name string, content []byte) { + t.Helper() + if err := os.WriteFile(filepath.Join(s.cfg.Upload.Dir, name), content, 0644); err != nil { + t.Fatalf("write upload: %v", err) + } +} + +func TestUploadsServeRejectsInvalidNames(t *testing.T) { + s := webTestServer(t, nil) + for _, name := range []string{ + "../config.toml", + "..%2f..%2fconfig.toml", + "notahash.txt", + strings.Repeat("a", 32), // no extension + strings.Repeat("a", 32) + ".html/extra", + } { + req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil) + rec := httptest.NewRecorder() + s.handleUploadsServe(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("name %q: expected 404, got %d", name, rec.Code) + } + } +} + +func TestUploadsServeForcesAttachmentForNonImages(t *testing.T) { + s := webTestServer(t, nil) + name := strings.Repeat("ab", 16) + ".html" + writeUploadFile(t, s, name, []byte("")) + + req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil) + rec := httptest.NewRecorder() + s.handleUploadsServe(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/octet-stream" { + t.Fatalf("expected octet-stream, got %q", ct) + } + if cd := rec.Header().Get("Content-Disposition"); !strings.HasPrefix(cd, "attachment") { + t.Fatalf("expected attachment disposition, got %q", cd) + } +} + +func TestUploadsServeImagesInline(t *testing.T) { + s := webTestServer(t, nil) + name := strings.Repeat("cd", 16) + ".png" + writeUploadFile(t, s, name, smallPNG(t)) + + req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil) + rec := httptest.NewRecorder() + s.handleUploadsServe(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", rec.Code) + } + if cd := rec.Header().Get("Content-Disposition"); cd != "" { + t.Fatalf("images should be served inline, got disposition %q", cd) + } +} + +// ---- Decompression-bomb guard ---- + +func smallPNG(t *testing.T) []byte { + t.Helper() + var buf bytes.Buffer + if err := png.Encode(&buf, image.NewNRGBA(image.Rect(0, 0, 10, 10))); err != nil { + t.Fatalf("encode png: %v", err) + } + return buf.Bytes() +} + +// bombPNGHeader builds a syntactically valid PNG signature + IHDR chunk that +// declares the given dimensions. DecodeConfig succeeds on it; a full decode +// of real data at this size would allocate width*height*4 bytes. +func bombPNGHeader(width, height uint32) []byte { + var buf bytes.Buffer + buf.Write([]byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}) + ihdr := make([]byte, 13) + binary.BigEndian.PutUint32(ihdr[0:4], width) + binary.BigEndian.PutUint32(ihdr[4:8], height) + ihdr[8] = 8 // bit depth + ihdr[9] = 6 // color type RGBA + chunk := append([]byte("IHDR"), ihdr...) + binary.Write(&buf, binary.BigEndian, uint32(13)) + buf.Write(chunk) + binary.Write(&buf, binary.BigEndian, crc32.ChecksumIEEE(chunk)) + return buf.Bytes() +} + +func TestDecodeImageBoundedRejectsHugeDimensions(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bomb.png") + // 50000x50000 = 2.5 gigapixels — would decode to ~10 GB of NRGBA. + if err := os.WriteFile(path, bombPNGHeader(50000, 50000), 0644); err != nil { + t.Fatalf("write bomb: %v", err) + } + if _, err := decodeImageBounded(path); err == nil { + t.Fatal("expected oversized image to be rejected before decode") + } else if !strings.Contains(err.Error(), "too large") { + t.Fatalf("expected dimension error, got: %v", err) + } +} + +func TestDecodeImageBoundedAcceptsNormalImage(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "ok.png") + if err := os.WriteFile(path, smallPNG(t), 0644); err != nil { + t.Fatalf("write png: %v", err) + } + img, err := decodeImageBounded(path) + if err != nil { + t.Fatalf("expected small image to decode, got: %v", err) + } + if b := img.Bounds(); b.Dx() != 10 || b.Dy() != 10 { + t.Fatalf("unexpected bounds: %v", b) + } +} + +func TestThumbRouteRefusesBombViaFallback(t *testing.T) { + // A bomb header upload must not OOM the public thumb route: generation + // fails the bounds check and the handler falls back to serving the + // original bytes without decoding them. + s := webTestServer(t, nil) + name := strings.Repeat("ef", 16) + ".png" + writeUploadFile(t, s, name, bombPNGHeader(50000, 50000)) + + req := httptest.NewRequest(http.MethodGet, "/uploads/thumb/"+name, nil) + req.SetPathValue("filename", name) + rec := httptest.NewRecorder() + s.handleThumb(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200 fallback, got %d", rec.Code) + } + if _, err := os.Stat(s.thumbPath(name)); !os.IsNotExist(err) { + t.Fatal("no thumbnail may be generated for an oversized image") + } +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 329030d..52cbc0c 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -73,7 +73,7 @@ func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { // Uses a separate cookie (not HttpOnly so JS can read it, but SameSite=Lax // already blocks cross-site POSTs for most cases). The token is also embedded // in each form and verified server-side on every state-changing POST. -func csrfToken(w http.ResponseWriter, r *http.Request) string { +func (srv *Server) csrfToken(w http.ResponseWriter, r *http.Request) string { if c, err := r.Cookie("csrf"); err == nil && len(c.Value) == 64 { return c.Value } @@ -85,6 +85,7 @@ func csrfToken(w http.ResponseWriter, r *http.Request) string { Value: token, Path: "/", SameSite: http.SameSiteLaxMode, + Secure: srv.isHTTPS(r), MaxAge: 86400, }) return token diff --git a/internal/server/server.go b/internal/server/server.go index 0c15949..c8ebb65 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1,13 +1,17 @@ package server import ( + "context" + "errors" "fmt" "io/fs" "log" "net/http" "os" + "os/signal" "runtime" "strings" + "syscall" "time" "glimmer/internal/config" @@ -175,5 +179,26 @@ func (s *Server) Start() error { } log.Printf("Starting server on %s (base URL: %s)", addr, s.cfg.Server.BaseURL) - return srv.ListenAndServe() + + // Graceful shutdown: on SIGINT/SIGTERM stop accepting connections, let + // in-flight requests drain (bounded), then return so deferred cleanup + // (e.g. closing the SQLite DB) runs instead of being killed mid-write. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + errCh := make(chan error, 1) + go func() { errCh <- srv.ListenAndServe() }() + + select { + case err := <-errCh: + return err + case <-ctx.Done(): + log.Printf("Shutting down...") + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, context.DeadlineExceeded) { + return err + } + return nil + } } diff --git a/plan.md b/plan.md new file mode 100644 index 0000000..977a947 --- /dev/null +++ b/plan.md @@ -0,0 +1,60 @@ +# Hardening / Robustness Plan + +> Progress: items 1–4 done (build/vet/tests green, ARMv5 cross-compile +> verified). Item 5 remains — large template refactor, best done as its own +> piece of work. + +Follow-ups from the 2026-06-09 security review (fixes from that review already +landed in `962f5d9`). Status legend: ☐ todo · ◐ in progress · ☑ done + +## 1. ☑ Image decompression-bomb guard + +`generateThumbnail` and `handleAdminUploadResize` call `image.Decode` with no +dimension check. A valid small PNG can declare huge pixel dimensions and OOM +the RPi Zero (512 MB) on decode. `GET /uploads/thumb/{filename}` is public and +triggers generation on first request. + +- Add a bounded decode helper: `image.DecodeConfig` first (header only), + reject anything over 24 MP, use `int64` math so the width×height product + cannot overflow 32-bit `int` on ARMv5. +- Use it in both `generateThumbnail` and the resize handler. + +## 2. ☑ Graceful shutdown + +`Start()` calls `ListenAndServe` directly; SIGTERM/Ctrl-C kills in-flight +requests and gives SQLite no chance to close cleanly. + +- `signal.NotifyContext` for SIGINT/SIGTERM, then `srv.Shutdown` with a 10 s + timeout. + +## 3. ☑ `Secure` flag on the CSRF cookie + +The session cookie sets `Secure` via `isHTTPS()`; the `csrf` cookie never +does. Make `csrfToken` a `*Server` method and set `Secure: s.isHTTPS(r)`. +(Stays non-HttpOnly on purpose — `upload.js` reads it.) + +## 4. ☑ Handler test coverage + +`api_test.go` / `mcp_test.go` are thorough but the web handlers (auth, CSRF, +upload serving) have zero tests. Add `handlers_test.go` covering at least: + +- unauthenticated `/admin/*` requests redirect to login +- state-changing POSTs without a CSRF token are rejected (incl. the resize + route fixed in `962f5d9`) +- `/uploads/{filename}`: invalid/traversal names 404; non-image files get + `Content-Disposition: attachment` + octet-stream +- login: wrong password → 401, correct → session cookie + redirect +- oversized-image rejection from item 1 + +## 5. ☐ Drop `'unsafe-inline'` from `script-src` (CSP) + +All template JS is inline, so the CSP doesn't actually block injected +scripts. Move inline blocks into embedded static files (the `upload.js` +pattern) and tighten `script-src` to `'self'`. Touches every template — +deliberately last, and large enough that it may warrant its own session. + +--- + +**Verification for each item:** `go build ./...`, `go vet ./...`, +`go test ./...` must pass; CLAUDE.md conventions apply (no new deps, +RPi-Zero-friendly memory use).