Files
steveandClaude Opus 4.8 0f3dedab73 Address Gadfly review findings on Phase 0
Applied the fixes warranted by the adversarial review of PR #21 (all
findings graded in the gadfly store):

Store (highest impact):
- buildDSN always merges busy_timeout/journal_mode/foreign_keys pragmas
  into the DSN, even for file: URIs or paths with a query string — the
  prior passthrough silently disabled FK enforcement for those PANSY_DB
  values. Also escape '#' in the path and tighten in-memory detection to
  an exact ':memory:' token or mode=memory param (no substring misfire).
- migrate.go: detect duplicate migration versions with a clear error;
  wrap appliedVersions' rows.Err() with the store: prefix.

API:
- SetTrustedProxies failure now falls back to trust-none instead of
  leaving gin's trust-everyone default (X-Forwarded-For spoofing).
- SPA: 404 embedded directories (was a directory listing), 404 bare /api,
  add X-Content-Type-Options: nosniff, cache index.html bytes once at
  startup, single fs.Stat existence check, shared writeAPIError helper.
- Move gin.SetMode out of package init() into New().

Config: validate PANSY_PORT range (fall back to 8080 with a warning).

Web:
- api.ts: serialize the request body before the fetch try so a
  JSON.stringify failure isn't misreported as a network error.
- AppShell: move state-specific/conflicting utilities into
  active/inactiveProps so concatenated Tailwind classes don't collide.

Tests: added store DSN-pragma/memory-detection cases and SPA
directory-404 case. go build/vet/test clean (CGO off); web tsc + build
clean; re-verified in a browser (SPA, deep links, /assets 404, nav).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
2026-07-18 15:19:30 -04:00

106 lines
3.2 KiB
Go

package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/gin-gonic/gin"
)
func testEngine() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
// A real API route so unmatched /api/* paths reach NoRoute (as in production).
r.GET("/api/v1/healthz", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
dist := fstest.MapFS{
"index.html": &fstest.MapFile{Data: []byte(`<!doctype html><div id="root"></div>`)},
"assets/app-abc123.js": &fstest.MapFile{Data: []byte(`console.log(1)`)},
}
RegisterSPA(r, dist)
return r
}
func do(t *testing.T, r *gin.Engine, method, path string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(method, path, nil))
return w
}
func TestSPAServesHashedAssetImmutable(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/assets/app-abc123.js")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if cc := w.Header().Get("Cache-Control"); !strings.Contains(cc, "immutable") {
t.Errorf("Cache-Control = %q, want immutable", cc)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "javascript") {
t.Errorf("Content-Type = %q, want javascript", ct)
}
}
func TestSPAServesIndexNoCache(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if cc := w.Header().Get("Cache-Control"); cc != "no-cache" {
t.Errorf("Cache-Control = %q, want no-cache", cc)
}
}
func TestSPAFallbackForClientRoute(t *testing.T) {
// A deep link with no matching file returns index.html so client routing works.
w := do(t, testEngine(), http.MethodGet, "/gardens/42")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if !strings.Contains(w.Body.String(), `id="root"`) {
t.Errorf("expected index.html body, got %q", w.Body.String())
}
}
func TestSPAMissingAssetIs404(t *testing.T) {
// A missing asset must NOT fall back to index.html (which would be a 200 of
// HTML for a .js request — a MIME-type error in the browser).
w := do(t, testEngine(), http.MethodGet, "/assets/missing-xyz.js")
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
t.Errorf("Content-Type = %q, want json", ct)
}
}
func TestSPADirectoryIs404NotListing(t *testing.T) {
// A request that resolves to an embedded directory must 404, never a listing.
for _, p := range []string{"/assets", "/assets/"} {
w := do(t, testEngine(), http.MethodGet, p)
if w.Code != http.StatusNotFound {
t.Errorf("GET %s status = %d, want 404", p, w.Code)
}
}
}
func TestSPAUnmatchedAPIIs404JSON(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/api/v1/nope")
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
t.Errorf("Content-Type = %q, want json (not the SPA HTML)", ct)
}
}
func TestSPARejectsNonGET(t *testing.T) {
w := do(t, testEngine(), http.MethodPost, "/gardens")
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", w.Code)
}
}