package server import ( "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "pageswiki/internal/compiler" "pageswiki/internal/kunstzeal" ) func TestKunstzealCompatibility(t *testing.T) { var d contentDescriptor = kunstzeal.Descriptor{MediaType: "application/json", Filename: "scene.excalidraw"} var adapter projectionAdapter = kunstzeal.SelectAdapter(d) if adapter.ID != selectProjectionAdapter(d).ID || adapter.Delivery != deliveryText || inlineTextWindowThreshold != kunstzeal.InlineTextWindowThreshold { t.Fatal("adapter compatibility changed") } if len(builtinAdapterManifest()) != len(kunstzeal.Catalog()) { t.Fatal("discovery catalog diverged") } for _, kind := range []string{"mermaid", "dot", "graphviz", "d2", "unknown"} { if diagramHash(kind, "source", "svg") != compiler.DiagramHash(kind, "source", "svg") || diagramHash(kind, "source", "svg") != kunstzeal.DiagramHash(kind, "source", "svg") { t.Fatal("hash diverged") } if allowedDiagramType(kind) != kunstzeal.AllowedDiagramType(kind) || normalizeDiagramType(kind) != kunstzeal.NormalizeDiagramType(kind) { t.Fatal("kind facade diverged") } } client := diagramHTTPClient() if client.Timeout != kunstzeal.DiagramTimeout || client.CheckRedirect(nil, nil) != http.ErrUseLastResponse { t.Fatal("unsafe provider defaults") } } func TestKunstzealRedirectAndErrorIsolation(t *testing.T) { s, token, _ := configFixture(t) s.diagramRoot = t.TempDir() s.mux.HandleFunc("/:/compile/diagram/", s.handleCompileDiagram) var leaked atomic.Int32 other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { leaked.Add(1); io.WriteString(w, "") })) defer other.Close() var status atomic.Int32 status.Store(http.StatusTemporaryRedirect) renderer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Location", other.URL+"/collect-source") w.WriteHeader(int(status.Load())) io.WriteString(w, "PRIVATE RENDERER DIAGNOSTICS") })) defer renderer.Close() t.Setenv("KROKI_URL", renderer.URL) for _, code := range []int{301, 302, 307, 308, 400, 500} { status.Store(int32(code)) r := httptest.NewRequest("POST", "http://localhost/:/compile/diagram/mermaid", strings.NewReader("private diagram source")) r.Header.Set("Authorization", "Bearer "+token) w := httptest.NewRecorder() s.withAuthorization(s.mux).ServeHTTP(w, r) if w.Code != 502 || leaked.Load() != 0 || strings.Contains(w.Body.String(), "PRIVATE") || strings.Contains(w.Body.String(), renderer.URL) || w.Header().Get("Cache-Control") != "private, no-store" || !strings.Contains(w.Header().Get("Content-Security-Policy"), "sandbox") { t.Fatalf("status=%d response=%d leaked=%d body=%s", code, w.Code, leaked.Load(), w.Body.String()) } } files, err := filepath.Glob(filepath.Join(s.diagramRoot, "mermaid", "*.svg")) if err != nil || len(files) != 0 { t.Fatal("failure cached", files, err) } } func TestKunstzealPostCacheBoundsAndFailureFallback(t *testing.T) { s, token, _ := configFixture(t) s.diagramRoot = t.TempDir() s.mux.HandleFunc("/:/compile/diagram/", s.handleCompileDiagram) var calls atomic.Int32 renderer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) if r.URL.Path != "/graphviz/svg" { t.Error("dot not normalized", r.URL.Path) } io.WriteString(w, `fixture`) })) defer renderer.Close() t.Setenv("KROKI_URL", renderer.URL) post := func(source string) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", "http://localhost/:/compile/diagram/dot", strings.NewReader(source)) r.Header.Set("Authorization", "Bearer "+token) w := httptest.NewRecorder() s.withAuthorization(s.mux).ServeHTTP(w, r) return w } if w := post(strings.Repeat("x", kunstzeal.DiagramSourceLimit+1)); w.Code != 413 || calls.Load() != 0 { t.Fatal("oversized input sent", w.Code, calls.Load()) } for i := 0; i < 2; i++ { w := post("digraph { a -> b }") if w.Code != 200 || !strings.HasPrefix(w.Body.String(), " d }"); w.Code != 200 || calls.Load() != 2 { t.Fatal("cache failure broke rendering", w.Code, calls.Load()) } } func TestKunstzealDiskCacheNeedsLiveProvenance(t *testing.T) { s, token, domain := configFixture(t) s.diagramRoot = t.TempDir() s.mux.HandleFunc("/:/compile/diagram/", s.handleCompileDiagram) hash := diagramHash("mermaid", t.Name(), "svg") if err := kunstzeal.WriteDiagramCache(s.diagramCachePath("mermaid", hash), []byte("")); err != nil { t.Fatal(err) } url := "/:/compile/diagram/mermaid/" + hash + ".svg" if w := configRequest(s, token, "GET", url, nil); w.Code != 404 { t.Fatal("orphan cache was served", w.Code) } diagramSourceMu.Lock() diagramSourceCache[hash] = diagramCacheEntry{Type: "mermaid", Domain: domain, Path: "/guide", Source: "source", At: time.Now().Add(-31 * time.Minute)} diagramSourceMu.Unlock() t.Cleanup(func() { diagramSourceMu.Lock(); delete(diagramSourceCache, hash); diagramSourceMu.Unlock() }) if w := configRequest(s, token, "GET", url, nil); w.Code != 404 { t.Fatal("expired provenance was served", w.Code) } diagramSourceMu.Lock() entry := diagramSourceCache[hash] entry.At = time.Now() diagramSourceCache[hash] = entry diagramSourceMu.Unlock() if w := configRequest(s, token, "GET", url, nil); w.Code != 200 || w.Body.String() != "" { t.Fatal("authorized cache not served", w.Code, w.Body.String()) } }