package server import ( "errors" "io" "net/http" "os" "path/filepath" "regexp" "strings" "sync" "time" "pageswiki/internal/kunstzeal" ) var diagramSourceCache = map[string]diagramCacheEntry{} var diagramSourceMu sync.Mutex type diagramCacheEntry struct { Type string Source string At time.Time Domain string Path string } func (s *Server) diagramCachePath(kind, hash string) string { root := s.diagramRoot if root == "" { root = "/data/cache/diagram" } return filepath.Join(root, kind, hash+".svg") } func readDiagramCache(path string) ([]byte, error) { return kunstzeal.ReadDiagramCache(path) } func diagramHash(kind, source, format string) string { return kunstzeal.DiagramHash(kind, source, format) } func allowedDiagramType(kind string) bool { return kunstzeal.AllowedDiagramType(kind) } func normalizeDiagramType(kind string) string { return kunstzeal.NormalizeDiagramType(kind) } func krokiURL() string { v := strings.TrimSpace( os.Getenv("KROKI_URL"), ) if v == "" { return "http://kroki:8000" } return strings.TrimRight( v, "/", ) } func (s *Server) renderDiagramsInHTML( r *http.Request, path string, html string, ) string { re := regexp.MustCompile(`(?s)
(.+?)
`) return re.ReplaceAllStringFunc( html, func(block string) string { m := re.FindStringSubmatch( block, ) if len(m) != 3 { return block } diagramType := normalizeDiagramType( m[1], ) source := htmlUnescapeString( m[2], ) if len(source) > kunstzeal.DiagramInlineLimit || path == "" { return block } hash := diagramHash( diagramType, htmlProjectionVersion+"\x00"+s.domainUUIDForRequest(r)+"\x00"+path+"\x00"+source, "svg", ) diagramSourceMu.Lock() if len(diagramSourceCache) >= 128 { oldest, key := time.Now(), "" for k, v := range diagramSourceCache { if v.At.Before(oldest) { oldest, key = v.At, k } } delete(diagramSourceCache, key) } diagramSourceCache[hash] = diagramCacheEntry{ Type: diagramType, Source: source, At: time.Now(), Domain: s.domainUUIDForRequest(r), Path: path, } diagramSourceMu.Unlock() return `
` + `` + diagramType + ` diagram` + `
` }, ) } func htmlUnescapeString( s string, ) string { r := strings.NewReplacer( "<", "<", ">", ">", "&", "&", """, `"`, "'", "'", ) return r.Replace( s, ) } func (s *Server) handleCompileDiagram( w http.ResponseWriter, r *http.Request, ) { // Apply also to disk-cache hits and direct navigation, not only new renders. w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Cache-Control", "private, no-store") if r.Method == http.MethodPost { s.handleCompileDiagramPost( w, r, ) return } rest := strings.TrimPrefix( r.URL.Path, "/:/compile/diagram/", ) parts := strings.Split( rest, "/", ) if len(parts) != 2 { http.NotFound(w, r) return } diagramType := normalizeDiagramType( parts[0], ) if !allowedDiagramType(diagramType) { http.NotFound(w, r) return } hashFile := parts[1] if !strings.HasSuffix(hashFile, ".svg") { http.NotFound(w, r) return } hash := strings.TrimSuffix( hashFile, ".svg", ) if !regexp.MustCompile(`^[a-f0-9]{64}$`).MatchString(hash) { http.NotFound(w, r) return } cachePath := s.diagramCachePath(diagramType, hash) diagramSourceMu.Lock() entry, ok := diagramSourceCache[hash] diagramSourceMu.Unlock() if !ok || entry.Type != diagramType || entry.Domain != s.domainUUIDForRequest(r) || time.Since(entry.At) > 30*time.Minute || !s.pathReadFilter(r)(entry.Path) { http.NotFound(w, r) return } if b, err := readDiagramCache(cachePath); err == nil { w.Header().Set( "Content-Type", "image/svg+xml; charset=utf-8", ) _, _ = w.Write(b) return } s.renderDiagramSVG( w, r, diagramType, entry.Source, cachePath, ) } func (s *Server) handleCompileDiagramPost( w http.ResponseWriter, r *http.Request, ) { rest := strings.TrimPrefix( r.URL.Path, "/:/compile/diagram/", ) diagramType := normalizeDiagramType( strings.Trim(rest, "/"), ) if !allowedDiagramType(diagramType) { http.NotFound(w, r) return } defer r.Body.Close() sourceBytes, err := io.ReadAll( io.LimitReader( r.Body, kunstzeal.DiagramSourceLimit+1, ), ) if err != nil || len(sourceBytes) > kunstzeal.DiagramSourceLimit { http.Error(w, "diagram source exceeds limit", http.StatusRequestEntityTooLarge) return } source := string(sourceBytes) hash := diagramHash( diagramType, source, "svg", ) cachePath := s.diagramCachePath(diagramType, hash) if b, err := readDiagramCache(cachePath); err == nil { w.Header().Set( "Content-Type", "image/svg+xml; charset=utf-8", ) _, _ = w.Write(b) return } s.renderDiagramSVG( w, r, diagramType, source, cachePath, ) } // The configured service may be private (Compose), but it may not redirect // source content to another destination. Authorization is checked before this. func diagramHTTPClient() *http.Client { return &http.Client{Timeout: kunstzeal.DiagramTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } func (s *Server) renderDiagramSVG(w http.ResponseWriter, r *http.Request, diagramType, source, cachePath string) { provider := kunstzeal.Kroki{Endpoint: krokiURL(), Client: diagramHTTPClient()} b, err := provider.Render(r.Context(), diagramType, source) if err != nil { status := http.StatusBadGateway if errors.Is(err, kunstzeal.ErrProviderConfig) { status = http.StatusInternalServerError } http.Error(w, err.Error(), status) return } // Cache failure must not discard a successfully generated projection. _ = kunstzeal.WriteDiagramCache(cachePath, b) w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8") w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:") _, _ = w.Write(b) }