Teststand
Some checks failed
Deploy KubeViz / deploy (push) Has been cancelled

This commit is contained in:
2026-03-01 07:40:49 +01:00
commit 1a0bbe9dfd
58 changed files with 7756 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
package httpserver
import "embed"
//go:embed ui/templates/*.html
var templateFS embed.FS
//go:embed ui/static/*
var staticFS embed.FS

View File

@@ -0,0 +1,217 @@
package httpserver
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"net/http"
"sort"
"strings"
"kubeviz/internal/analyze"
"kubeviz/internal/graph"
"kubeviz/internal/model"
)
type point struct {
X float64
Y float64
}
func (s *Server) handleExportSVG(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
resp, ok := s.exportGraph(w, r)
if !ok {
return
}
svg := renderSVG(resp)
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Content-Disposition", "inline; filename=graph.svg")
_, _ = w.Write([]byte(svg))
}
func (s *Server) handleExportPNG(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
resp, ok := s.exportGraph(w, r)
if !ok {
return
}
img := renderPNG(resp)
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Disposition", "inline; filename=graph.png")
_ = png.Encode(w, img)
}
func (s *Server) exportGraph(w http.ResponseWriter, r *http.Request) (model.GraphResponse, bool) {
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return model.GraphResponse{}, false
}
dataset := s.store.GetDataset(sid)
if dataset == nil {
http.Error(w, "no manifests uploaded", http.StatusNotFound)
return model.GraphResponse{}, false
}
filters := graph.Filters{
Namespace: r.URL.Query().Get("namespace"),
Kind: r.URL.Query().Get("kind"),
Query: r.URL.Query().Get("q"),
FocusID: r.URL.Query().Get("focus"),
Relations: parseRelations(r.URL.Query().Get("relations")),
GroupBy: r.URL.Query().Get("groupBy"),
CollapsedGroups: parseCSVSet(r.URL.Query().Get("collapsed")),
}
checkCfg := analyze.DefaultConfig()
if raw := r.URL.Query().Get("checkRules"); raw != "" {
checkCfg = analyze.ConfigFromEnabled(parseCSVSet(raw))
}
_, healthHints := analyze.AnalyzeDataset(dataset, checkCfg)
return graph.BuildGraph(dataset, filters, healthHints), true
}
func layout(nodes []model.GraphNode) map[string]point {
out := map[string]point{}
sorted := make([]model.GraphNode, len(nodes))
copy(sorted, nodes)
sort.Slice(sorted, func(i, j int) bool { return sorted[i].ID < sorted[j].ID })
n := len(sorted)
if n == 0 {
return out
}
centerX, centerY := 640.0, 360.0
radius := 220.0
if n > 40 {
radius = 280
}
for i, node := range sorted {
angle := 2 * math.Pi * float64(i) / float64(n)
out[node.ID] = point{
X: centerX + radius*math.Cos(angle),
Y: centerY + radius*math.Sin(angle),
}
}
return out
}
func renderSVG(resp model.GraphResponse) string {
coords := layout(resp.Nodes)
var b strings.Builder
b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720">`)
b.WriteString(`<rect width="100%" height="100%" fill="#f5f7fb"/>`)
for _, edge := range resp.Edges {
s, sok := coords[edge.Source]
t, tok := coords[edge.Target]
if !sok || !tok {
continue
}
b.WriteString(fmt.Sprintf(`<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#9ca3af" stroke-width="1.5"/>`, s.X, s.Y, t.X, t.Y))
}
for _, node := range resp.Nodes {
p := coords[node.ID]
fill := "#2563eb"
if node.IsSensitive {
fill = "#dc2626"
}
label := escapeXML(fmt.Sprintf("%s/%s", node.Kind, node.Name))
b.WriteString(fmt.Sprintf(`<circle cx="%.1f" cy="%.1f" r="20" fill="%s" opacity="0.9"/>`, p.X, p.Y, fill))
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="11" fill="#111827" text-anchor="middle">%s</text>`, p.X, p.Y+34, label))
}
b.WriteString(`</svg>`)
return b.String()
}
func renderPNG(resp model.GraphResponse) image.Image {
img := image.NewRGBA(image.Rect(0, 0, 1280, 720))
draw.Draw(img, img.Bounds(), &image.Uniform{C: color.RGBA{245, 247, 251, 255}}, image.Point{}, draw.Src)
coords := layout(resp.Nodes)
edgeColor := color.RGBA{156, 163, 175, 255}
for _, edge := range resp.Edges {
s, sok := coords[edge.Source]
t, tok := coords[edge.Target]
if !sok || !tok {
continue
}
drawLine(img, int(s.X), int(s.Y), int(t.X), int(t.Y), edgeColor)
}
for _, node := range resp.Nodes {
p := coords[node.ID]
fill := color.RGBA{37, 99, 235, 255}
if node.IsSensitive {
fill = color.RGBA{220, 38, 38, 255}
}
drawCircle(img, int(p.X), int(p.Y), 20, fill)
}
return img
}
func drawLine(img *image.RGBA, x0, y0, x1, y1 int, c color.Color) {
dx := abs(x1 - x0)
sx := -1
if x0 < x1 {
sx = 1
}
dy := -abs(y1 - y0)
sy := -1
if y0 < y1 {
sy = 1
}
err := dx + dy
for {
if image.Pt(x0, y0).In(img.Bounds()) {
img.Set(x0, y0, c)
}
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 >= dy {
err += dy
x0 += sx
}
if e2 <= dx {
err += dx
y0 += sy
}
}
}
func drawCircle(img *image.RGBA, cx, cy, r int, c color.Color) {
for y := -r; y <= r; y++ {
for x := -r; x <= r; x++ {
if x*x+y*y <= r*r {
px := cx + x
py := cy + y
if image.Pt(px, py).In(img.Bounds()) {
img.Set(px, py, c)
}
}
}
}
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
func escapeXML(s string) string {
replacer := strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;")
return replacer.Replace(s)
}

View File

@@ -0,0 +1,783 @@
package httpserver
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
"kubeviz/internal/analyze"
"kubeviz/internal/graph"
"kubeviz/internal/model"
"kubeviz/internal/parser"
)
var manifestExts = []string{".yaml", ".yml", ".json"}
const (
maxValuesYAMLBytes = 256 * 1024
maxDiffFieldBytes = 2 * 1024 * 1024
maxManifestFiles = 2000
maxManifestBytes = 20 * 1024 * 1024
)
var defaultGitAllowedHosts = []string{"github.com", "gitlab.com", "bitbucket.org"}
type indexData struct {
Title string
Now string
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if _, err := s.sessionID(w, r); err != nil {
http.Error(w, "session initialization failed", http.StatusInternalServerError)
return
}
if err := s.templates.ExecuteTemplate(w, "index.html", indexData{Title: "KubeViz", Now: time.Now().Format(time.RFC3339)}); err != nil {
http.Error(w, "template render error", http.StatusInternalServerError)
}
}
func (s *Server) handleParseManifests(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadSize)
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
var (
body []byte
dataset *model.Dataset
)
ct := r.Header.Get("Content-Type")
switch {
case strings.HasPrefix(ct, "multipart/form-data"):
if err := r.ParseMultipartForm(s.cfg.MaxUploadSize); err != nil {
http.Error(w, "invalid multipart form", http.StatusBadRequest)
return
}
dataset, err = parseMultipartManifestInput(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
default:
var req struct {
Manifest string `json:"manifest"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
body = []byte(req.Manifest)
}
if dataset == nil {
if len(strings.TrimSpace(string(body))) == 0 {
http.Error(w, "manifest input is empty", http.StatusBadRequest)
return
}
dataset, err = parser.ParseManifests(body)
if err != nil {
http.Error(w, fmt.Sprintf("parse error: %v", err), http.StatusBadRequest)
return
}
}
s.store.SetDataset(sid, dataset)
writeJSON(w, http.StatusOK, map[string]any{
"datasetID": sid,
"summary": dataset.Summary,
})
}
type helmRenderRequest struct {
RepoURL string `json:"repoURL"`
Ref string `json:"ref"`
ChartPath string `json:"chartPath"`
ValuesYAML string `json:"valuesYAML"`
ReleaseName string `json:"releaseName"`
Namespace string `json:"namespace"`
}
type gitImportRequest struct {
RepoURL string `json:"repoURL"`
Ref string `json:"ref"`
Path string `json:"path"`
SourceType string `json:"sourceType"`
ValuesYAML string `json:"valuesYAML"`
ReleaseName string `json:"releaseName"`
Namespace string `json:"namespace"`
}
func (s *Server) handleHelmRender(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadSize)
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
var req helmRenderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if strings.TrimSpace(req.RepoURL) == "" {
http.Error(w, "repoURL is required", http.StatusBadRequest)
return
}
if err := validateRepoURL(req.RepoURL, s.cfg.GitAllowedHosts); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(req.ValuesYAML) > maxValuesYAMLBytes {
http.Error(w, "valuesYAML exceeds maximum allowed size", http.StatusBadRequest)
return
}
rendered, err := renderHelmFromGit(r.Context(), req.RepoURL, req.Ref, req.ChartPath, req.ValuesYAML, req.ReleaseName, req.Namespace)
if err != nil {
writeExecError(w, err)
return
}
dataset, err := parser.ParseManifests(rendered)
if err != nil {
http.Error(w, fmt.Sprintf("parse error: %v", err), http.StatusBadRequest)
return
}
s.store.SetDataset(sid, dataset)
writeJSON(w, http.StatusOK, map[string]any{
"datasetID": sid,
"mode": "helm",
"summary": dataset.Summary,
})
}
func (s *Server) handleGitImport(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadSize)
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
var req gitImportRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if strings.TrimSpace(req.RepoURL) == "" {
http.Error(w, "repoURL is required", http.StatusBadRequest)
return
}
if err := validateRepoURL(req.RepoURL, s.cfg.GitAllowedHosts); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(req.ValuesYAML) > maxValuesYAMLBytes {
http.Error(w, "valuesYAML exceeds maximum allowed size", http.StatusBadRequest)
return
}
sourceType := strings.ToLower(strings.TrimSpace(req.SourceType))
if sourceType == "" {
sourceType = "manifests"
}
var body []byte
switch sourceType {
case "manifests":
body, err = importManifestsFromGit(r.Context(), req.RepoURL, req.Ref, req.Path)
case "helm":
body, err = renderHelmFromGit(r.Context(), req.RepoURL, req.Ref, req.Path, req.ValuesYAML, req.ReleaseName, req.Namespace)
default:
http.Error(w, "sourceType must be manifests or helm", http.StatusBadRequest)
return
}
if err != nil {
writeExecError(w, err)
return
}
dataset, err := parser.ParseManifests(body)
if err != nil {
http.Error(w, fmt.Sprintf("parse error: %v", err), http.StatusBadRequest)
return
}
s.store.SetDataset(sid, dataset)
writeJSON(w, http.StatusOK, map[string]any{
"datasetID": sid,
"mode": sourceType,
"summary": dataset.Summary,
})
}
func collectMultipartManifestInput(r *http.Request) ([]byte, error) {
var combined bytes.Buffer
appendDoc := func(doc []byte) {
trimmed := bytes.TrimSpace(doc)
if len(trimmed) == 0 {
return
}
if combined.Len() > 0 {
combined.WriteString("\n---\n")
}
combined.Write(trimmed)
combined.WriteByte('\n')
}
files := r.MultipartForm.File["manifestFile"]
for _, fh := range files {
f, err := fh.Open()
if err != nil {
return nil, fmt.Errorf("failed to open uploaded file %q", fh.Filename)
}
content, err := io.ReadAll(f)
_ = f.Close()
if err != nil {
return nil, fmt.Errorf("failed to read uploaded file %q", fh.Filename)
}
appendDoc(content)
}
appendDoc([]byte(r.FormValue("manifestText")))
if combined.Len() == 0 {
return nil, fmt.Errorf("manifest input is empty")
}
return combined.Bytes(), nil
}
func parseMultipartManifestInput(r *http.Request) (*model.Dataset, error) {
parts, err := collectMultipartManifestParts(r)
if err != nil {
return nil, err
}
if len(parts) == 0 {
return nil, fmt.Errorf("manifest input is empty")
}
merged := &model.Dataset{
Resources: make(map[string]*model.Resource),
CreatedAt: time.Now(),
}
for idx, part := range parts {
ds, parseErr := parser.ParseManifests(part.Content)
if parseErr != nil {
merged.Summary.Issues = append(merged.Summary.Issues, model.ParseIssue{
Document: idx + 1,
Message: fmt.Sprintf("%s: %s", part.Source, friendlyParseIssueMessage(part.Source, parseErr.Error(), part.Content)),
})
continue
}
for _, issue := range ds.Summary.Issues {
issue.Message = fmt.Sprintf("%s: %s", part.Source, friendlyParseIssueMessage(part.Source, issue.Message, part.Content))
merged.Summary.Issues = append(merged.Summary.Issues, issue)
}
for id, res := range ds.Resources {
if _, exists := merged.Resources[id]; exists {
merged.Duplicates = append(merged.Duplicates, id)
merged.Summary.Issues = append(merged.Summary.Issues, model.ParseIssue{
Document: idx + 1,
Message: fmt.Sprintf("%s: duplicate resource id %q detected", part.Source, id),
})
}
merged.Resources[id] = res
}
}
merged.Summary.Resources = len(merged.Resources)
merged.ModifiedAt = time.Now()
return merged, nil
}
func friendlyParseIssueMessage(source, raw string, content []byte) string {
msg := strings.TrimSpace(raw)
if msg == "" {
msg = "failed to parse input"
}
if looksLikeHelmSource(source, content) {
return fmt.Sprintf("%s (Helm source detected: upload rendered manifests or use Import From Git/Helm)", msg)
}
return msg
}
func looksLikeHelmSource(source string, content []byte) bool {
name := strings.ToLower(filepath.Base(strings.TrimSpace(source)))
if name == "chart.yaml" || name == "values.yaml" || name == "values.yml" {
return true
}
text := string(content)
return strings.Contains(text, "{{") && strings.Contains(text, "}}")
}
type manifestPart struct {
Source string
Content []byte
}
func collectMultipartManifestParts(r *http.Request) ([]manifestPart, error) {
parts := make([]manifestPart, 0)
for _, files := range r.MultipartForm.File {
for _, fh := range files {
f, err := fh.Open()
if err != nil {
return nil, fmt.Errorf("failed to open uploaded file %q", fh.Filename)
}
content, err := io.ReadAll(f)
_ = f.Close()
if err != nil {
return nil, fmt.Errorf("failed to read uploaded file %q", fh.Filename)
}
trimmed := bytes.TrimSpace(content)
if len(trimmed) == 0 {
continue
}
parts = append(parts, manifestPart{Source: fh.Filename, Content: append(trimmed, '\n')})
}
}
if inline := bytes.TrimSpace([]byte(r.FormValue("manifestText"))); len(inline) > 0 {
parts = append(parts, manifestPart{Source: "pasted manifest", Content: append(inline, '\n')})
}
return parts, nil
}
func importManifestsFromGit(ctx context.Context, repoURL, ref, manifestPath string) ([]byte, error) {
repoDir, cleanup, err := cloneRepo(ctx, repoURL, ref)
if err != nil {
return nil, err
}
defer cleanup()
root := repoDir
if manifestPath = strings.TrimSpace(manifestPath); manifestPath != "" {
safe, err := safeJoin(repoDir, manifestPath)
if err != nil {
return nil, err
}
root = safe
}
return collectManifestFiles(root)
}
func renderHelmFromGit(ctx context.Context, repoURL, ref, chartPath, valuesYAML, releaseName, namespace string) ([]byte, error) {
repoDir, cleanup, err := cloneRepo(ctx, repoURL, ref)
if err != nil {
return nil, err
}
defer cleanup()
if strings.TrimSpace(chartPath) == "" {
chartPath = "."
}
chartDir, err := safeJoin(repoDir, chartPath)
if err != nil {
return nil, err
}
return runHelmTemplate(ctx, chartDir, valuesYAML, releaseName, namespace)
}
func cloneRepo(ctx context.Context, repoURL, ref string) (string, func(), error) {
if _, err := exec.LookPath("git"); err != nil {
return "", nil, fmt.Errorf("git executable not found in runtime image")
}
tmpDir, err := os.MkdirTemp("", "kubeviz-git-*")
if err != nil {
return "", nil, fmt.Errorf("failed creating temp directory: %w", err)
}
cleanup := func() { _ = os.RemoveAll(tmpDir) }
args := []string{"clone", "--quiet", "--depth", "1", "--filter=blob:none", "--no-tags"}
ref = strings.TrimSpace(ref)
if ref != "" {
args = append(args, "--branch", ref, "--single-branch")
}
args = append(args, repoURL, tmpDir)
cloneCmd := exec.CommandContext(ctx, "git", args...)
cloneCmd.Env = append(os.Environ(),
"GIT_TERMINAL_PROMPT=0",
"GIT_ALLOW_PROTOCOL=https",
"GIT_CONFIG_GLOBAL=/dev/null",
"GIT_CONFIG_NOSYSTEM=1",
)
if out, err := cloneCmd.CombinedOutput(); err != nil {
cleanup()
log.Printf("git clone failed for %q: %s", repoURL, strings.TrimSpace(string(out)))
return "", nil, fmt.Errorf("git clone failed")
}
return tmpDir, cleanup, nil
}
func collectManifestFiles(root string) ([]byte, error) {
info, err := os.Stat(root)
if err != nil {
return nil, fmt.Errorf("path does not exist: %w", err)
}
if !info.IsDir() {
return nil, fmt.Errorf("path %q is not a directory", root)
}
var files []string
var totalBytes int64
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() {
base := strings.ToLower(d.Name())
if base == ".git" || base == "node_modules" || base == "vendor" {
return filepath.SkipDir
}
return nil
}
if isManifestFile(path) {
if len(files) >= maxManifestFiles {
return fmt.Errorf("too many manifest files (limit: %d)", maxManifestFiles)
}
info, err := d.Info()
if err != nil {
return err
}
totalBytes += info.Size()
if totalBytes > maxManifestBytes {
return fmt.Errorf("manifest file size budget exceeded (limit: %d bytes)", maxManifestBytes)
}
files = append(files, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to collect manifest files: %w", err)
}
if len(files) == 0 {
return nil, fmt.Errorf("no manifest files found in selected path")
}
slices.Sort(files)
var out bytes.Buffer
appendDoc := func(doc []byte) {
trimmed := bytes.TrimSpace(doc)
if len(trimmed) == 0 {
return
}
if out.Len() > 0 {
out.WriteString("\n---\n")
}
out.Write(trimmed)
out.WriteByte('\n')
}
for _, path := range files {
content, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read %q: %w", path, err)
}
appendDoc(content)
}
if out.Len() == 0 {
return nil, fmt.Errorf("manifest files were empty")
}
return out.Bytes(), nil
}
func runHelmTemplate(ctx context.Context, chartDir, valuesYAML, releaseName, namespace string) ([]byte, error) {
if _, err := exec.LookPath("helm"); err != nil {
return nil, fmt.Errorf("helm executable not found in runtime image")
}
if releaseName = strings.TrimSpace(releaseName); releaseName == "" {
releaseName = "kubeviz"
}
if namespace = strings.TrimSpace(namespace); namespace == "" {
namespace = "default"
}
args := []string{"template", releaseName, chartDir, "--namespace", namespace}
var cleanupFiles []string
if trimmed := strings.TrimSpace(valuesYAML); trimmed != "" {
valuesFile, err := os.CreateTemp("", "kubeviz-values-*.yaml")
if err != nil {
return nil, fmt.Errorf("failed creating temp values file: %w", err)
}
if _, err := valuesFile.WriteString(trimmed); err != nil {
_ = valuesFile.Close()
_ = os.Remove(valuesFile.Name())
return nil, fmt.Errorf("failed writing values file: %w", err)
}
_ = valuesFile.Close()
args = append(args, "--values", valuesFile.Name())
cleanupFiles = append(cleanupFiles, valuesFile.Name())
}
defer func() {
for _, f := range cleanupFiles {
_ = os.Remove(f)
}
}()
cmd := exec.CommandContext(ctx, "helm", args...)
cmd.Env = append(os.Environ(),
"HELM_NO_PLUGINS=1",
"HELM_REGISTRY_CONFIG=/tmp/helm-registry.json",
)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("helm template failed for chart %q: %s", chartDir, strings.TrimSpace(string(out)))
return nil, fmt.Errorf("helm template failed")
}
trimmed := bytes.TrimSpace(out)
if len(trimmed) == 0 {
return nil, fmt.Errorf("helm template produced no output")
}
return append(trimmed, '\n'), nil
}
func safeJoin(root, subpath string) (string, error) {
cleanRoot := filepath.Clean(root)
candidate := filepath.Join(cleanRoot, filepath.Clean(subpath))
rel, err := filepath.Rel(cleanRoot, candidate)
if err != nil {
return "", fmt.Errorf("invalid path: %w", err)
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("path escapes repository root")
}
return candidate, nil
}
func validateRepoURL(raw string, allowedHosts []string) error {
parsed, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return fmt.Errorf("repoURL is invalid")
}
if parsed.Scheme != "https" {
return fmt.Errorf("repoURL must use https")
}
if parsed.Host == "" {
return fmt.Errorf("repoURL host is required")
}
if parsed.User != nil {
return fmt.Errorf("repoURL must not contain credentials")
}
host := strings.ToLower(parsed.Hostname())
if len(allowedHosts) == 0 {
allowedHosts = defaultGitAllowedHosts
}
for _, allowed := range allowedHosts {
allowed = strings.ToLower(strings.TrimSpace(allowed))
if allowed == "" {
continue
}
if host == allowed || strings.HasSuffix(host, "."+allowed) {
return nil
}
}
return fmt.Errorf("repoURL host is not allowed")
}
func isManifestFile(path string) bool {
ext := strings.ToLower(filepath.Ext(path))
for _, allowed := range manifestExts {
if ext == allowed {
return true
}
}
return false
}
func writeExecError(w http.ResponseWriter, err error) {
if err == nil {
return
}
if errors.Is(err, context.DeadlineExceeded) {
http.Error(w, "operation timed out", http.StatusRequestTimeout)
return
}
log.Printf("external import/render error: %v", err)
msg := err.Error()
switch {
case strings.Contains(msg, "not found in runtime image"):
http.Error(w, msg, http.StatusNotImplemented)
case strings.Contains(msg, "path escapes repository root"):
http.Error(w, msg, http.StatusBadRequest)
case strings.Contains(msg, "repoURL is ") || strings.Contains(msg, "repoURL must"):
http.Error(w, msg, http.StatusBadRequest)
case strings.Contains(msg, "too many manifest files") || strings.Contains(msg, "size budget exceeded"):
http.Error(w, msg, http.StatusBadRequest)
default:
http.Error(w, "external import/render failed", http.StatusBadRequest)
}
}
func (s *Server) handleGraph(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
dataset := s.store.GetDataset(sid)
checkCfg := analyze.DefaultConfig()
if raw := r.URL.Query().Get("checkRules"); raw != "" {
checkCfg = analyze.ConfigFromEnabled(parseCSVSet(raw))
}
findings, healthHints := analyze.AnalyzeDataset(dataset, checkCfg)
filters := graph.Filters{
Namespace: r.URL.Query().Get("namespace"),
Kind: r.URL.Query().Get("kind"),
Query: r.URL.Query().Get("q"),
FocusID: r.URL.Query().Get("focus"),
Relations: parseRelations(r.URL.Query().Get("relations")),
GroupBy: r.URL.Query().Get("groupBy"),
CollapsedGroups: parseCSVSet(r.URL.Query().Get("collapsed")),
}
resp := graph.BuildGraph(dataset, filters, healthHints)
resp.Findings = findings
writeJSON(w, http.StatusOK, resp)
}
func (s *Server) handleDiff(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadSize)
var req struct {
BaseManifest string `json:"baseManifest"`
TargetManifest string `json:"targetManifest"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if strings.TrimSpace(req.BaseManifest) == "" || strings.TrimSpace(req.TargetManifest) == "" {
http.Error(w, "baseManifest and targetManifest are required", http.StatusBadRequest)
return
}
if len(req.BaseManifest) > maxDiffFieldBytes || len(req.TargetManifest) > maxDiffFieldBytes {
http.Error(w, "diff payload exceeds maximum allowed size", http.StatusBadRequest)
return
}
base, err := parser.ParseManifests([]byte(req.BaseManifest))
if err != nil {
http.Error(w, fmt.Sprintf("base parse error: %v", err), http.StatusBadRequest)
return
}
target, err := parser.ParseManifests([]byte(req.TargetManifest))
if err != nil {
http.Error(w, fmt.Sprintf("target parse error: %v", err), http.StatusBadRequest)
return
}
writeJSON(w, http.StatusOK, analyze.DiffDatasets(base, target))
}
func (s *Server) handleResource(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
dataset := s.store.GetDataset(sid)
if dataset == nil {
http.Error(w, "no manifests uploaded", http.StatusNotFound)
return
}
id := strings.TrimPrefix(r.URL.Path, "/api/resources/")
id = strings.TrimSpace(id)
if id == "" {
http.Error(w, "resource id required", http.StatusBadRequest)
return
}
res, ok := dataset.Resources[id]
if !ok {
http.Error(w, "resource not found", http.StatusNotFound)
return
}
payload := map[string]any{
"id": res.ID,
"apiVersion": res.APIVersion,
"kind": res.Kind,
"name": res.Name,
"namespace": res.Namespace,
"labels": res.Labels,
"isSensitive": res.IsSensitive,
"keyNames": res.KeyNames,
"references": res.References,
"ownerRefs": res.OwnerRefs,
"raw": sanitizeRawForResponse(res),
"clusterScoped": res.ClusterScoped,
}
writeJSON(w, http.StatusOK, payload)
}
func sanitizeRawForResponse(res *model.Resource) map[string]any {
raw := map[string]any{}
for k, v := range res.Raw {
raw[k] = v
}
if res.IsSensitive {
raw["data"] = "<redacted>"
raw["stringData"] = "<redacted>"
}
return raw
}
func (s *Server) handleClearSession(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
sid, err := s.sessionID(w, r)
if err != nil {
http.Error(w, "session error", http.StatusInternalServerError)
return
}
s.store.Clear(sid)
writeJSON(w, http.StatusOK, map[string]string{"status": "cleared"})
}

View File

@@ -0,0 +1,143 @@
package httpserver
import (
"context"
"embed"
"encoding/json"
"errors"
"html/template"
"io/fs"
"log"
"net/http"
"strings"
"time"
"kubeviz/internal/config"
"kubeviz/internal/session"
)
const sessionCookieName = "kubeviz_session"
type Server struct {
cfg config.Config
store *session.Store
templates *template.Template
mux *http.ServeMux
}
func New(cfg config.Config) (*Server, error) {
tpls, err := template.ParseFS(templateFS, "ui/templates/*.html")
if err != nil {
return nil, err
}
s := &Server{
cfg: cfg,
store: session.NewStore(cfg.SessionTTL),
templates: tpls,
mux: http.NewServeMux(),
}
s.routes()
return s, nil
}
func (s *Server) routes() {
s.mux.Handle("/", s.middleware(http.HandlerFunc(s.handleIndex)))
s.mux.Handle("/api/manifests/parse", s.middleware(http.HandlerFunc(s.handleParseManifests)))
s.mux.Handle("/api/helm/render", s.middleware(http.HandlerFunc(s.handleHelmRender)))
s.mux.Handle("/api/git/import", s.middleware(http.HandlerFunc(s.handleGitImport)))
s.mux.Handle("/api/graph", s.middleware(http.HandlerFunc(s.handleGraph)))
s.mux.Handle("/api/diff", s.middleware(http.HandlerFunc(s.handleDiff)))
s.mux.Handle("/api/resources/", s.middleware(http.HandlerFunc(s.handleResource)))
s.mux.Handle("/api/export/svg", s.middleware(http.HandlerFunc(s.handleExportSVG)))
s.mux.Handle("/api/export/png", s.middleware(http.HandlerFunc(s.handleExportPNG)))
s.mux.Handle("/api/session/clear", s.middleware(http.HandlerFunc(s.handleClearSession)))
staticSub, _ := fs.Sub(staticFS, "ui/static")
s.mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
}
func (s *Server) Handler() http.Handler {
return s.mux
}
func (s *Server) Shutdown(ctx context.Context) {
s.store.Stop()
_ = ctx
}
func (s *Server) middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
r = r.WithContext(ctx)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' https://unpkg.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';")
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
next.ServeHTTP(w, r)
})
}
func (s *Server) sessionID(w http.ResponseWriter, r *http.Request) (string, error) {
cookie, err := r.Cookie(sessionCookieName)
if err == nil && cookie.Value != "" {
return cookie.Value, nil
}
if !errors.Is(err, http.ErrNoCookie) && err != nil {
return "", err
}
sid, err := s.store.NewSessionID()
if err != nil {
return "", err
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: sid,
Path: "/",
HttpOnly: true,
Secure: s.cfg.CookieSecure,
SameSite: http.SameSiteLaxMode,
MaxAge: int(s.cfg.SessionTTL.Seconds()),
})
return sid, nil
}
func parseRelations(raw string) map[string]bool {
return parseCSVSet(raw)
}
func parseCSVSet(raw string) map[string]bool {
if raw == "" {
return nil
}
out := map[string]bool{}
for _, item := range strings.Split(raw, ",") {
trimmed := strings.TrimSpace(item)
if trimmed == "" {
continue
}
out[trimmed] = true
}
return out
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(payload); err != nil {
log.Printf("failed writing JSON: %v", err)
}
}
func subFS(fsys embed.FS, dir string) fs.FS {
sub, err := fs.Sub(fsys, dir)
if err != nil {
panic(err)
}
return sub
}

View File

@@ -0,0 +1,459 @@
package httpserver
import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"kubeviz/internal/config"
)
func TestParseGraphAndResourceFlow(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
manifest := `apiVersion: v1
kind: ConfigMap
metadata:
name: app-cfg
namespace: demo
`
body := map[string]string{"manifest": manifest}
payload, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/api/manifests/parse", bytes.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusOK {
t.Fatalf("parse status: got %d body=%s", got, w.Body.String())
}
cookies := w.Result().Cookies()
if len(cookies) == 0 {
t.Fatalf("expected session cookie")
}
graphReq := httptest.NewRequest(http.MethodGet, "/api/graph", nil)
graphReq.AddCookie(cookies[0])
graphW := httptest.NewRecorder()
handler.ServeHTTP(graphW, graphReq)
if got := graphW.Result().StatusCode; got != http.StatusOK {
t.Fatalf("graph status: got %d", got)
}
var graph map[string]any
if err := json.NewDecoder(graphW.Result().Body).Decode(&graph); err != nil {
t.Fatalf("graph decode failed: %v", err)
}
nodes, _ := graph["nodes"].([]any)
if len(nodes) != 1 {
t.Fatalf("expected 1 node, got %d", len(nodes))
}
resReq := httptest.NewRequest(http.MethodGet, "/api/resources/demo/ConfigMap/app-cfg", nil)
resReq.AddCookie(cookies[0])
resW := httptest.NewRecorder()
handler.ServeHTTP(resW, resReq)
if got := resW.Result().StatusCode; got != http.StatusOK {
t.Fatalf("resource status: got %d", got)
}
}
func TestParseMultipleUploadedFiles(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
f1, err := writer.CreateFormFile("manifestFile", "deployment.yaml")
if err != nil {
t.Fatalf("failed creating file part 1: %v", err)
}
_, _ = f1.Write([]byte(`apiVersion: apps/v1
kind: Deployment
metadata:
name: kubeviz
namespace: kubeviz
`))
f2, err := writer.CreateFormFile("manifestFile", "service.yaml")
if err != nil {
t.Fatalf("failed creating file part 2: %v", err)
}
_, _ = f2.Write([]byte(`apiVersion: v1
kind: Service
metadata:
name: kubeviz
namespace: kubeviz
spec:
selector:
app: kubeviz
`))
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/manifests/parse", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusOK {
t.Fatalf("parse status: got %d body=%s", got, w.Body.String())
}
cookies := w.Result().Cookies()
if len(cookies) == 0 {
t.Fatalf("expected session cookie")
}
graphReq := httptest.NewRequest(http.MethodGet, "/api/graph", nil)
graphReq.AddCookie(cookies[0])
graphW := httptest.NewRecorder()
handler.ServeHTTP(graphW, graphReq)
if got := graphW.Result().StatusCode; got != http.StatusOK {
t.Fatalf("graph status: got %d", got)
}
var graph map[string]any
if err := json.NewDecoder(graphW.Result().Body).Decode(&graph); err != nil {
t.Fatalf("graph decode failed: %v", err)
}
nodes, _ := graph["nodes"].([]any)
if len(nodes) != 2 {
t.Fatalf("expected 2 nodes from two files, got %d", len(nodes))
}
}
func TestParseMultipleUploadedFilesToleratesSingleInvalidFile(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
valid, err := writer.CreateFormFile("manifestFile", "service.yaml")
if err != nil {
t.Fatalf("failed creating valid file part: %v", err)
}
_, _ = valid.Write([]byte(`apiVersion: v1
kind: Service
metadata:
name: kubeviz
namespace: kubeviz
spec:
selector:
app: kubeviz
`))
invalid, err := writer.CreateFormFile("manifestFile", "broken.yaml")
if err != nil {
t.Fatalf("failed creating invalid file part: %v", err)
}
_, _ = invalid.Write([]byte(`apiVersion: v1
kind Service
metadata:
name: broken
`))
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/manifests/parse", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusOK {
t.Fatalf("parse status: got %d", got)
}
var resp struct {
Summary struct {
Resources int `json:"resources"`
Issues []struct {
Message string `json:"message"`
} `json:"issues"`
} `json:"summary"`
}
if err := json.NewDecoder(w.Result().Body).Decode(&resp); err != nil {
t.Fatalf("parse response decode failed: %v", err)
}
if resp.Summary.Resources != 1 {
t.Fatalf("expected 1 parsed resource, got %d", resp.Summary.Resources)
}
if len(resp.Summary.Issues) == 0 {
t.Fatalf("expected parse issue for invalid file")
}
if !strings.Contains(resp.Summary.Issues[0].Message, "broken.yaml") {
t.Fatalf("expected issue message to include filename, got: %q", resp.Summary.Issues[0].Message)
}
}
func TestParseMultipleUploadedFilesAllInvalidReturnsIssues(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
f1, err := writer.CreateFormFile("manifestFile", "values.yaml")
if err != nil {
t.Fatalf("failed creating file part 1: %v", err)
}
_, _ = f1.Write([]byte(`replicaCount: 2
image:
repository: nginx
`))
f2, err := writer.CreateFormFile("manifestFile", "Chart.yaml")
if err != nil {
t.Fatalf("failed creating file part 2: %v", err)
}
_, _ = f2.Write([]byte(`apiVersion: v2
name: sample-chart
version: 0.1.0
`))
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/manifests/parse", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusOK {
t.Fatalf("parse status: got %d body=%s", got, w.Body.String())
}
var resp struct {
Summary struct {
Resources int `json:"resources"`
Issues []struct {
Message string `json:"message"`
} `json:"issues"`
} `json:"summary"`
}
if err := json.NewDecoder(w.Result().Body).Decode(&resp); err != nil {
t.Fatalf("parse response decode failed: %v", err)
}
if resp.Summary.Resources != 0 {
t.Fatalf("expected 0 parsed resources, got %d", resp.Summary.Resources)
}
if len(resp.Summary.Issues) < 2 {
t.Fatalf("expected issues for all invalid files, got %d", len(resp.Summary.Issues))
}
}
func TestDiffEndpoint(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
body := map[string]string{
"baseManifest": `apiVersion: v1
kind: ConfigMap
metadata:
name: cfg
namespace: demo
data:
a: "1"
`,
"targetManifest": `apiVersion: v1
kind: ConfigMap
metadata:
name: cfg
namespace: demo
data:
a: "2"
---
apiVersion: v1
kind: Service
metadata:
name: svc
namespace: demo
`,
}
payload, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/api/diff", bytes.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusOK {
t.Fatalf("diff status: got %d", got)
}
var diff map[string]any
if err := json.NewDecoder(w.Result().Body).Decode(&diff); err != nil {
t.Fatalf("diff decode failed: %v", err)
}
changed, _ := diff["changed"].([]any)
added, _ := diff["added"].([]any)
if len(changed) != 1 {
t.Fatalf("expected 1 changed item, got %d", len(changed))
}
if len(added) != 1 {
t.Fatalf("expected 1 added item, got %d", len(added))
}
}
func TestGraphEndpointProvidesFindingsAndGroups(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
manifest := `apiVersion: v1
kind: Service
metadata:
name: app
namespace: demo
spec:
selector:
app: no-match
`
body := map[string]string{"manifest": manifest}
payload, _ := json.Marshal(body)
parseReq := httptest.NewRequest(http.MethodPost, "/api/manifests/parse", bytes.NewReader(payload))
parseReq.Header.Set("Content-Type", "application/json")
parseW := httptest.NewRecorder()
handler.ServeHTTP(parseW, parseReq)
if got := parseW.Result().StatusCode; got != http.StatusOK {
t.Fatalf("parse status: got %d", got)
}
cookies := parseW.Result().Cookies()
if len(cookies) == 0 {
t.Fatalf("expected session cookie")
}
graphReq := httptest.NewRequest(http.MethodGet, "/api/graph?groupBy=namespace&collapsed=demo", nil)
graphReq.AddCookie(cookies[0])
graphW := httptest.NewRecorder()
handler.ServeHTTP(graphW, graphReq)
if got := graphW.Result().StatusCode; got != http.StatusOK {
t.Fatalf("graph status: got %d", got)
}
var graph map[string]any
if err := json.NewDecoder(graphW.Result().Body).Decode(&graph); err != nil {
t.Fatalf("graph decode failed: %v", err)
}
if findings, _ := graph["findings"].([]any); len(findings) == 0 {
t.Fatalf("expected findings in graph response")
}
if groups, _ := graph["groups"].([]any); len(groups) == 0 {
t.Fatalf("expected groups in graph response")
}
}
func TestGitImportValidation(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
req := httptest.NewRequest(http.MethodPost, "/api/git/import", bytes.NewBufferString(`{"sourceType":"manifests"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusBadRequest {
t.Fatalf("expected 400 for missing repoURL, got %d", got)
}
}
func TestHelmRenderValidation(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
req := httptest.NewRequest(http.MethodPost, "/api/helm/render", bytes.NewBufferString(`{}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusBadRequest {
t.Fatalf("expected 400 for missing repoURL, got %d", got)
}
}
func TestGitImportRejectsNonHTTPSRepoURL(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
req := httptest.NewRequest(http.MethodPost, "/api/git/import", bytes.NewBufferString(`{"repoURL":"http://github.com/org/repo.git","sourceType":"manifests"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusBadRequest {
t.Fatalf("expected 400 for non-https repoURL, got %d", got)
}
}
func TestGitImportRejectsDisallowedHost(t *testing.T) {
srv, err := New(config.Config{
Addr: ":0",
SessionTTL: 30 * time.Minute,
MaxUploadSize: 1024 * 1024,
GitAllowedHosts: []string{"github.com"},
})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
req := httptest.NewRequest(http.MethodPost, "/api/git/import", bytes.NewBufferString(`{"repoURL":"https://evil.example/repo.git","sourceType":"manifests"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusBadRequest {
t.Fatalf("expected 400 for disallowed host, got %d", got)
}
}
func TestDiffRejectsTooLargePayload(t *testing.T) {
srv, err := New(config.Config{Addr: ":0", SessionTTL: 30 * time.Minute, MaxUploadSize: 8 * 1024 * 1024})
if err != nil {
t.Fatalf("server init failed: %v", err)
}
handler := srv.Handler()
tooLarge := strings.Repeat("a", maxDiffFieldBytes+1)
body := map[string]string{
"baseManifest": tooLarge,
"targetManifest": "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: demo\n",
}
payload, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/api/diff", bytes.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Result().StatusCode; got != http.StatusBadRequest {
t.Fatalf("expected 400 for oversized diff payload, got %d", got)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" role="img" aria-label="KubeViz Logo">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#0f172a"/>
<stop offset="100%" stop-color="#1d4ed8"/>
</linearGradient>
<linearGradient id="node" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#22c3b7"/>
<stop offset="100%" stop-color="#0f766e"/>
</linearGradient>
</defs>
<rect x="4" y="4" width="88" height="88" rx="18" fill="url(#bg)"/>
<g fill="none" stroke="#93c5fd" stroke-width="4" stroke-linecap="round" opacity="0.95">
<path d="M24 66 L48 30 L72 66"/>
<path d="M24 66 L72 66"/>
</g>
<g fill="url(#node)">
<circle cx="24" cy="66" r="7"/>
<circle cx="48" cy="30" r="7"/>
<circle cx="72" cy="66" r="7"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 848 B

View File

@@ -0,0 +1,971 @@
:root {
color-scheme: light dark;
--font-sans: "IBM Plex Sans", "Inter", "Segoe UI", sans-serif;
--radius-xs: 8px;
--radius-sm: 10px;
--radius-md: 14px;
--shadow-sm: 0 2px 10px rgba(15, 23, 42, 0.06);
--shadow-md: 0 8px 24px rgba(15, 23, 42, 0.08);
--bg: #edf2fa;
--bg-elevated: #f7faff;
--panel: #ffffff;
--ink: #12213b;
--muted: #4d5d79;
--line: #c9d6e6;
--line-strong: #aebfd4;
--accent: #0f766e;
--accent-ink: #ffffff;
--chip: #eff5fd;
--canvas-top: #f8fbff;
--canvas-bottom: #edf3fb;
--tooltip-bg: #111827;
--tooltip-ink: #e5e7eb;
--code-bg: #0f172a;
--code-ink: #e2e8f0;
--danger: #b91c1c;
--overlay: rgba(15, 23, 42, 0.45);
--brand-start: #0f172a;
--brand-end: #1d4ed8;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b1220;
--bg-elevated: #101a2e;
--panel: #111c31;
--ink: #e2e8f0;
--muted: #b8c6da;
--line: #274160;
--line-strong: #3b5d87;
--accent: #22c3b7;
--accent-ink: #052323;
--chip: #13253f;
--canvas-top: #0d182b;
--canvas-bottom: #0a1426;
--tooltip-bg: #e2e8f0;
--tooltip-ink: #0b1220;
--code-bg: #0a1426;
--code-ink: #d6e2f4;
--danger: #f87171;
--overlay: rgba(2, 7, 17, 0.58);
--brand-start: #0a1120;
--brand-end: #12326d;
}
}
:root[data-theme="light"] {
--bg: #edf2fa;
--bg-elevated: #f7faff;
--panel: #ffffff;
--ink: #12213b;
--muted: #4d5d79;
--line: #c9d6e6;
--line-strong: #aebfd4;
--accent: #0f766e;
--accent-ink: #ffffff;
--chip: #eff5fd;
--canvas-top: #f8fbff;
--canvas-bottom: #edf3fb;
--tooltip-bg: #111827;
--tooltip-ink: #e5e7eb;
--code-bg: #0f172a;
--code-ink: #e2e8f0;
--danger: #b91c1c;
--overlay: rgba(15, 23, 42, 0.45);
--brand-start: #0f172a;
--brand-end: #1d4ed8;
}
:root[data-theme="dark"] {
--bg: #0b1220;
--bg-elevated: #101a2e;
--panel: #111c31;
--ink: #e2e8f0;
--muted: #b8c6da;
--line: #274160;
--line-strong: #3b5d87;
--accent: #22c3b7;
--accent-ink: #052323;
--chip: #13253f;
--canvas-top: #0d182b;
--canvas-bottom: #0a1426;
--tooltip-bg: #e2e8f0;
--tooltip-ink: #0b1220;
--code-bg: #0a1426;
--code-ink: #d6e2f4;
--danger: #f87171;
--overlay: rgba(2, 7, 17, 0.58);
--brand-start: #0a1120;
--brand-end: #12326d;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: var(--font-sans);
background:
radial-gradient(1200px 500px at top right, color-mix(in srgb, var(--accent) 12%, transparent), transparent),
linear-gradient(180deg, var(--bg-elevated), var(--bg));
color: var(--ink);
}
.topbar {
padding: 0.85rem 1.2rem;
border-bottom: 1px solid color-mix(in srgb, var(--line) 60%, transparent);
background: linear-gradient(90deg, var(--brand-start), var(--brand-end));
color: #fff;
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.8rem;
}
.brand {
display: flex;
align-items: center;
gap: 0.7rem;
}
.brand-logo {
width: 34px;
height: 34px;
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
}
.topbar h1 {
margin: 0;
font-size: 2rem;
line-height: 1;
letter-spacing: -0.03em;
}
.topbar p {
margin: 0.2rem 0 0;
color: #dbeafe;
font-size: 0.97rem;
}
.layout {
display: grid;
grid-template-columns: 330px 1fr 360px;
gap: 0.9rem;
padding: 0.9rem;
min-height: calc(100vh - 84px);
}
.left-panel,
.graph-panel,
.details-panel {
background: color-mix(in srgb, var(--panel) 96%, transparent);
border: 1px solid var(--line);
border-radius: var(--radius-md);
padding: 0.95rem;
box-shadow: var(--shadow-sm);
backdrop-filter: blur(2px);
}
.tabs {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.35rem;
margin-bottom: 0.6rem;
}
.tab-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
padding: 0.5rem 0.65rem;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--panel) 86%, var(--bg));
color: var(--muted);
cursor: pointer;
font-weight: 600;
}
.tab-btn.active {
border-color: color-mix(in srgb, var(--accent) 55%, var(--line));
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, var(--panel));
}
.tab-icon {
width: 0.58rem;
height: 0.58rem;
border-radius: 999px;
border: 1.5px solid currentColor;
opacity: 0.72;
}
.tab-btn.active .tab-icon {
background: currentColor;
opacity: 0.95;
}
.tab-pane {
display: none;
}
.tab-pane.active {
display: block;
}
h2,
h3 {
margin: 0.15rem 0 0.65rem;
}
h2 {
font-size: 2.2rem;
letter-spacing: -0.02em;
}
h3 {
font-size: 1.02rem;
}
label,
legend,
summary {
display: block;
margin-top: 0.55rem;
font-weight: 600;
color: var(--muted);
font-size: 0.92rem;
}
.help-tip {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.05rem;
height: 1.05rem;
margin-left: 0.32rem;
border-radius: 999px;
background: #2563eb;
color: #ffffff;
font-size: 0.72rem;
font-weight: 700;
cursor: help;
position: relative;
vertical-align: middle;
outline: none;
}
.help-tip:focus {
box-shadow: 0 0 0 2px color-mix(in srgb, #2563eb 35%, transparent);
}
.help-tooltip {
position: absolute;
left: 1.45rem;
top: -0.25rem;
width: min(420px, 80vw);
padding: 0.5rem 0.6rem;
border: 1px solid color-mix(in srgb, var(--line) 75%, transparent);
border-radius: var(--radius-xs);
background: color-mix(in srgb, var(--panel) 96%, var(--bg));
color: var(--ink);
font-size: 0.79rem;
line-height: 1.35;
box-shadow: var(--shadow-sm);
opacity: 0;
pointer-events: none;
transform: translateY(4px);
transition: opacity 120ms ease, transform 120ms ease;
z-index: 20;
}
.help-tip:hover .help-tooltip,
.help-tip:focus .help-tooltip {
opacity: 1;
transform: translateY(0);
}
textarea,
input,
select {
width: 100%;
margin-top: 0.2rem;
padding: 0.54rem 0.58rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--panel) 90%, var(--bg));
color: var(--ink);
font-size: 0.97rem;
}
textarea::placeholder,
input::placeholder {
color: color-mix(in srgb, var(--muted) 55%, transparent);
}
textarea {
resize: vertical;
}
textarea:focus,
input:focus,
select:focus,
button:focus,
a:focus {
outline: 2px solid color-mix(in srgb, var(--accent) 45%, transparent);
outline-offset: 1px;
}
.file-upload {
width: 100%;
margin-top: 0.2rem;
padding: 0.45rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-sm);
display: flex;
gap: 0.55rem;
align-items: center;
flex-wrap: wrap;
background: color-mix(in srgb, var(--panel) 88%, var(--bg));
}
#file-picker-btn {
background: color-mix(in srgb, var(--panel) 50%, var(--bg));
color: var(--ink);
border: 1px solid var(--line-strong);
}
#file-count {
color: var(--muted);
font-size: 0.95rem;
font-weight: 600;
}
.visually-hidden-file {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
fieldset {
margin: 0.65rem 0;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
}
fieldset label {
font-weight: 500;
margin-top: 0.3rem;
}
.advanced-filters {
margin-top: 0.55rem;
padding: 0.2rem 0;
}
.advanced-filters > summary,
.check-help > summary {
list-style: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.advanced-filters > summary::-webkit-details-marker,
.check-help > summary::-webkit-details-marker {
display: none;
}
.advanced-filters > summary::after,
.check-help > summary::after {
content: "";
width: 0.5rem;
height: 0.5rem;
border-right: 2px solid currentColor;
border-bottom: 2px solid currentColor;
transform: rotate(45deg);
transition: transform 140ms ease;
opacity: 0.75;
margin-top: -0.15rem;
}
.advanced-filters[open] > summary::after,
.check-help[open] > summary::after {
transform: rotate(225deg);
margin-top: 0.1rem;
}
.summary-title {
display: inline-flex;
align-items: center;
}
.row {
display: flex;
gap: 0.5rem;
align-items: center;
flex-wrap: wrap;
margin-top: 0.6rem;
}
.row.compact {
margin-top: 0.45rem;
}
button,
.exports a,
.chip {
padding: 0.42rem 0.72rem;
border-radius: var(--radius-sm);
text-decoration: none;
cursor: pointer;
font-weight: 600;
transition: background 120ms ease, border-color 120ms ease, color 120ms ease, transform 120ms ease;
}
button:hover,
.exports a:hover {
transform: translateY(-1px);
}
.btn-primary,
button[type="submit"] {
border: 1px solid var(--accent);
background: var(--accent);
color: var(--accent-ink);
}
.exports a {
border: 1px solid var(--accent);
background: var(--accent);
color: var(--accent-ink);
}
.btn-primary:hover,
button[type="submit"]:hover {
background: color-mix(in srgb, var(--accent) 90%, #000);
border-color: color-mix(in srgb, var(--accent) 90%, #000);
}
.btn-secondary,
button[type="button"],
#close-diff,
#close-checks {
border: 1px solid var(--line-strong);
background: color-mix(in srgb, var(--panel) 88%, var(--bg));
color: var(--accent);
}
.toggle-btn {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.btn-icon {
width: 0.62rem;
height: 0.62rem;
border-radius: 2px;
border: 1.5px solid currentColor;
position: relative;
}
.btn-icon::after {
content: "";
position: absolute;
right: -0.26rem;
top: 0.14rem;
width: 0.26rem;
height: 0.26rem;
border-top: 1.5px solid currentColor;
border-right: 1.5px solid currentColor;
transform: rotate(45deg);
}
.btn-secondary:hover,
button[type="button"]:hover,
#close-diff:hover,
#close-checks:hover {
border-color: color-mix(in srgb, var(--accent) 25%, var(--line-strong));
background: color-mix(in srgb, var(--panel) 70%, var(--bg));
}
.theme-toggle {
min-width: 132px;
}
.status {
margin-top: 0.6rem;
font-size: 0.95rem;
border-radius: var(--radius-sm);
padding: 0.25rem 0.1rem;
}
.status-info {
color: var(--muted);
}
.status-ok {
color: color-mix(in srgb, var(--accent) 88%, var(--ink));
}
.status-warn {
color: #b45309;
}
.status-error {
color: var(--danger);
}
.parse-issues {
margin-top: 0.45rem;
padding: 0.5rem 0.55rem;
border: 1px solid color-mix(in srgb, var(--line) 70%, transparent);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--panel) 84%, var(--bg));
}
.parse-issues strong {
display: block;
font-size: 0.86rem;
color: var(--muted);
}
#parse-issues-list {
margin: 0.35rem 0 0;
padding-left: 1rem;
}
#parse-issues-list li {
margin: 0.2rem 0;
font-size: 0.84rem;
color: var(--ink);
word-break: break-word;
}
.tool-actions {
display: flex;
gap: 0.5rem;
margin-top: 0.65rem;
}
.field-hint {
margin: 0.32rem 0 0;
color: var(--muted);
font-size: 0.82rem;
}
.path-result {
margin-top: 0.5rem;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 0.45rem 0.55rem;
background: color-mix(in srgb, var(--panel) 88%, var(--bg));
color: var(--muted);
font-size: 0.84rem;
word-break: break-word;
}
.path-steps {
margin-top: 0.45rem;
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
align-items: center;
}
.path-step {
border: 1px solid var(--line-strong);
background: color-mix(in srgb, var(--panel) 86%, var(--bg));
color: var(--ink);
border-radius: 999px;
padding: 0.2rem 0.48rem;
font-size: 0.78rem;
}
.path-step:hover {
border-color: color-mix(in srgb, var(--accent) 35%, var(--line-strong));
background: color-mix(in srgb, var(--accent) 12%, var(--panel));
}
.path-arrow {
color: var(--muted);
font-size: 0.8rem;
}
.graph-panel {
display: flex;
flex-direction: column;
position: relative;
}
.toolbar {
display: flex;
gap: 0.6rem;
align-items: center;
flex-wrap: wrap;
color: var(--muted);
margin-bottom: 0.4rem;
}
.kbd-hint {
margin-left: auto;
font-size: 0.78rem;
color: var(--muted);
}
.kbd-hint kbd {
border: 1px solid var(--line-strong);
border-bottom-width: 2px;
border-radius: 6px;
padding: 0.08rem 0.3rem;
background: color-mix(in srgb, var(--panel) 85%, var(--bg));
color: var(--ink);
font-family: var(--font-sans);
}
.toolbar select {
width: auto;
margin-top: 0;
padding: 0.25rem 0.4rem;
}
.toolbar button {
padding: 0.25rem 0.55rem;
font-size: 0.85rem;
}
.chips {
display: flex;
gap: 0.35rem;
flex-wrap: wrap;
margin-bottom: 0.45rem;
min-height: 1.7rem;
}
.chip {
background: var(--chip);
color: var(--muted);
border: 1px solid var(--line);
font-weight: 600;
padding: 0.22rem 0.5rem;
}
.legend {
display: flex;
gap: 0.7rem;
flex-wrap: wrap;
color: var(--muted);
font-size: 0.85rem;
margin-bottom: 0.45rem;
}
.dot {
width: 10px;
height: 10px;
display: inline-block;
border-radius: 50%;
margin-right: 0.3rem;
border: 1px solid rgba(15, 23, 42, 0.18);
}
.kind-workload {
background: #0f766e;
}
.kind-network {
background: #2563eb;
}
.kind-config {
background: #14b8a6;
}
.kind-secret {
background: #dc2626;
}
.kind-group {
background: #7c3aed;
}
.health-warning {
background: #f59e0b;
}
#graph-canvas {
width: 100%;
flex: 1;
min-height: 620px;
border: 1px dashed var(--line);
border-radius: var(--radius-sm);
background: linear-gradient(180deg, var(--canvas-top), var(--canvas-bottom));
}
.graph-overlay,
.no-match {
position: absolute;
top: 46%;
left: 50%;
transform: translate(-50%, -50%);
background: color-mix(in srgb, var(--panel) 94%, transparent);
border: 1px solid var(--line-strong);
border-radius: var(--radius-sm);
padding: 0.7rem 0.85rem;
min-width: min(420px, 85%);
display: flex;
flex-direction: column;
gap: 0.45rem;
align-items: flex-start;
box-shadow: var(--shadow-sm);
}
.graph-overlay span,
.no-match span {
color: var(--muted);
font-size: 0.9rem;
}
.details-panel pre {
max-height: 72vh;
overflow: auto;
background: var(--code-bg);
color: var(--code-ink);
padding: 0.7rem;
border-radius: var(--radius-sm);
font-size: 0.8rem;
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--line) 30%, transparent);
}
.sensitive {
color: var(--danger);
font-weight: 700;
}
.hidden {
display: none;
}
.edge-label {
font-size: 10px;
fill: var(--muted);
pointer-events: none;
user-select: none;
}
.findings-list {
list-style: none;
padding: 0;
margin: 0.5rem 0 0;
max-height: 55vh;
overflow: auto;
}
.findings-list li {
padding: 0.35rem 0.45rem;
margin-bottom: 0.35rem;
border: 1px solid var(--line);
border-radius: var(--radius-xs);
font-size: 0.85rem;
background: color-mix(in srgb, var(--panel) 90%, var(--bg));
}
.finding-error {
border-color: #ef4444;
}
.finding-warning {
border-color: #f59e0b;
}
.check-help {
margin-bottom: 0.55rem;
}
.check-help p {
margin: 0.35rem 0 0;
color: var(--muted);
font-size: 0.9rem;
}
.check-config {
max-height: 220px;
overflow: auto;
}
.collapse-controls {
margin-top: 0.5rem;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 0.45rem;
background: color-mix(in srgb, var(--panel) 85%, var(--bg));
}
.collapse-controls label {
display: flex;
align-items: center;
gap: 0.4rem;
margin-top: 0.25rem;
}
.search-suggest {
margin-top: 0.35rem;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--panel) 94%, var(--bg));
padding: 0.25rem;
box-shadow: var(--shadow-sm);
}
.suggest-item {
width: 100%;
text-align: left;
border: 1px solid transparent;
background: transparent;
color: var(--ink);
padding: 0.38rem 0.45rem;
border-radius: var(--radius-xs);
cursor: pointer;
}
.suggest-item:hover,
.suggest-item.active {
border-color: var(--line);
background: color-mix(in srgb, var(--accent) 10%, var(--panel));
}
.edge-tooltip {
position: absolute;
pointer-events: none;
background: var(--tooltip-bg);
color: var(--tooltip-ink);
border: 1px solid color-mix(in srgb, var(--line) 70%, transparent);
border-radius: var(--radius-xs);
padding: 0.35rem 0.45rem;
font-size: 0.78rem;
max-width: 280px;
z-index: 20;
white-space: pre-line;
}
.minimap-wrap {
position: absolute;
right: 0.9rem;
bottom: 0.9rem;
width: 220px;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--panel) 92%, var(--bg));
box-shadow: var(--shadow-sm);
padding: 0.35rem;
}
.minimap-wrap strong {
font-size: 0.78rem;
color: var(--muted);
}
#minimap-canvas {
margin-top: 0.3rem;
width: 100%;
height: 132px;
border-radius: 6px;
border: 1px solid var(--line);
background: color-mix(in srgb, var(--canvas-top) 70%, var(--canvas-bottom));
cursor: crosshair;
}
.modal {
position: fixed;
inset: 0;
background: var(--overlay);
display: flex;
justify-content: center;
align-items: center;
z-index: 40;
}
.modal.hidden {
display: none;
}
.modal-card {
width: min(780px, 92vw);
max-height: 88vh;
overflow: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius-md);
padding: 0.8rem;
box-shadow: var(--shadow-md);
}
.modal-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.diff-output {
margin-top: 0.6rem;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 0.5rem;
font-size: 0.85rem;
max-height: 220px;
overflow: auto;
background: color-mix(in srgb, var(--panel) 88%, var(--bg));
}
@media (max-width: 1280px) {
.layout {
grid-template-columns: 300px 1fr;
}
.details-panel {
grid-column: 1 / -1;
}
}
@media (max-width: 980px) {
.topbar {
flex-direction: column;
align-items: flex-start;
}
.theme-toggle {
align-self: flex-end;
}
.layout {
grid-template-columns: 1fr;
}
#graph-canvas {
min-height: 420px;
}
.kbd-hint {
width: 100%;
margin-left: 0;
}
.minimap-wrap {
position: static;
width: 100%;
margin-top: 0.5rem;
}
}

View File

@@ -0,0 +1,291 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ .Title }}</title>
<link rel="stylesheet" href="/static/styles.css">
<script defer src="https://unpkg.com/htmx.org@1.9.12"></script>
<script defer src="/static/app.js"></script>
</head>
<body>
<header class="topbar">
<div class="brand">
<img src="/static/logo.svg" alt="KubeViz logo" class="brand-logo">
<div>
<h1>KubeViz</h1>
<p>Kubernetes manifest relationship visualizer</p>
</div>
</div>
<button id="theme-toggle" class="btn-secondary theme-toggle" type="button" aria-label="Toggle theme">Theme: System</button>
</header>
<main class="layout">
<section class="left-panel">
<nav class="tabs" aria-label="Sidebar sections">
<button class="tab-btn active" data-tab="tab-data" type="button"><span class="tab-icon" aria-hidden="true"></span>Data</button>
<button class="tab-btn" data-tab="tab-filter" type="button"><span class="tab-icon" aria-hidden="true"></span>Filter</button>
</nav>
<section id="tab-data" class="tab-pane active">
<form id="manifest-form" hx-post="/api/manifests/parse" hx-encoding="multipart/form-data" hx-swap="none">
<label for="manifestText">Paste YAML</label>
<textarea id="manifestText" name="manifestText" rows="10" placeholder="apiVersion: apps/v1&#10;kind: Deployment&#10;..."></textarea>
<label for="manifestFile">
Or upload files
<span class="help-tip" tabindex="0" role="button" aria-label="Input format help">
?
<span class="help-tooltip" role="tooltip">
Expected input: rendered Kubernetes manifests with apiVersion, kind, and metadata.name.
Helm chart source files (Chart.yaml, values.yaml, templates/*.yaml) must be rendered first
(for example via helm template) or loaded via Import From Git / Helm.
</span>
</span>
</label>
<div class="file-upload">
<input id="manifestFile" class="visually-hidden-file" name="manifestFile" type="file" accept=".yaml,.yml,.json,text/yaml,application/x-yaml" multiple>
<button id="file-picker-btn" class="btn-secondary" type="button">Choose files</button>
<span id="file-count">No files selected</span>
</div>
<div class="row compact">
<button class="btn-primary" type="submit">Parse</button>
<button class="btn-secondary" type="button" id="clear-session">Clear</button>
</div>
</form>
<div class="status" id="parse-status"></div>
<div id="parse-issues" class="parse-issues hidden" aria-live="polite">
<strong>Parse Issues</strong>
<ul id="parse-issues-list"></ul>
</div>
<div class="status selected-summary">
<strong>Selected:</strong>
<span id="selected-kind-name">none</span>
</div>
<div class="tool-actions">
<button class="btn-secondary toggle-btn" id="open-checks" type="button"><span class="btn-icon" aria-hidden="true"></span>Checks</button>
<button class="btn-secondary toggle-btn" id="open-diff" type="button"><span class="btn-icon" aria-hidden="true"></span>Diff</button>
</div>
<div class="row exports compact">
<a id="export-svg" href="/api/export/svg" target="_blank" rel="noreferrer">Export SVG</a>
<a id="export-png" href="/api/export/png" target="_blank" rel="noreferrer">Export PNG</a>
</div>
<details class="advanced-filters">
<summary><span class="summary-title">Import From Git / Helm</span></summary>
<label for="git-repo-url">Git Repo URL</label>
<input id="git-repo-url" type="text" placeholder="https://github.com/org/repo.git">
<label for="git-ref">Git Ref (optional)</label>
<input id="git-ref" type="text" placeholder="main, tag, or commit">
<label for="git-path">Path In Repo (optional)</label>
<input id="git-path" type="text" placeholder="deploy/k8s or charts/my-app">
<label for="helm-values">Helm values YAML (optional)</label>
<textarea id="helm-values" rows="4" placeholder="replicaCount: 2"></textarea>
<div class="row compact">
<button class="btn-secondary" id="git-import-manifests" type="button">Import Manifests</button>
<button class="btn-secondary" id="git-import-helm" type="button">Render Helm</button>
</div>
</details>
</section>
<section id="tab-filter" class="tab-pane">
<form id="filter-form" hx-get="/api/graph" hx-swap="none">
<h3>Quick Filters</h3>
<label for="query">Search</label>
<input id="query" name="q" type="text" placeholder="name, kind, namespace or id">
<p class="field-hint">Search by name, kind, namespace, or full ID (for example: <code>default/Service/web</code>).</p>
<div id="search-suggest" class="search-suggest hidden" role="listbox" aria-label="Search suggestions"></div>
<div class="row compact">
<button class="btn-secondary" id="jump-to-search" type="button">Jump To Match</button>
</div>
<label for="groupBy">Group By</label>
<select id="groupBy" name="groupBy">
<option value="">None</option>
<option value="namespace">Namespace</option>
<option value="kind">Kind</option>
</select>
<fieldset>
<legend>Relations</legend>
<label><input type="checkbox" name="relations" value="selects" checked> selects</label>
<label><input type="checkbox" name="relations" value="mounts" checked> mounts</label>
<label><input type="checkbox" name="relations" value="references" checked> references</label>
<label><input type="checkbox" name="relations" value="owns" checked> owns</label>
<label><input type="checkbox" name="relations" value="routesTo" checked> routesTo</label>
<label><input type="checkbox" name="relations" value="scales" checked> scales</label>
</fieldset>
<details class="advanced-filters">
<summary><span class="summary-title">Advanced Filters</span></summary>
<label for="namespace">Namespace</label>
<input id="namespace" name="namespace" type="text" placeholder="default">
<label for="kind">Kind</label>
<input id="kind" name="kind" type="text" placeholder="Service">
<label for="focus">Focus Resource ID</label>
<input id="focus" name="focus" type="text" placeholder="default/Service/web">
<div id="collapse-controls" class="collapse-controls hidden">
<strong>Collapse Groups</strong>
<div id="collapse-list"></div>
</div>
</details>
<div class="row compact">
<button class="btn-secondary" type="button" id="reset-view">Reset Filters</button>
</div>
<h3>Saved Views</h3>
<label for="view-name">View Name</label>
<input id="view-name" type="text" placeholder="production-overview">
<div class="row compact">
<button class="btn-secondary" type="button" id="save-view">Save Current View</button>
</div>
<label for="saved-views">Saved</label>
<select id="saved-views">
<option value="">No saved views</option>
</select>
<div class="row compact">
<button class="btn-secondary" type="button" id="load-view">Load</button>
<button class="btn-secondary" type="button" id="delete-view">Delete</button>
</div>
<div class="row compact">
<button class="btn-secondary" type="button" id="export-views">Export JSON</button>
<button class="btn-secondary" type="button" id="import-views">Import JSON</button>
<input id="import-views-file" type="file" accept=".json,application/json" class="visually-hidden-file">
</div>
<h3>Path Finder</h3>
<label for="path-source">Source Node ID</label>
<input id="path-source" type="text" placeholder="default/Ingress/web">
<div id="path-source-suggest" class="search-suggest hidden" role="listbox" aria-label="Path source suggestions"></div>
<label for="path-target">Target Node ID</label>
<input id="path-target" type="text" placeholder="default/Secret/web-secret">
<div id="path-target-suggest" class="search-suggest hidden" role="listbox" aria-label="Path target suggestions"></div>
<label><input id="path-bidirectional" type="checkbox"> Allow reverse traversal</label>
<div class="row compact">
<button class="btn-secondary" type="button" id="run-path">Find Path</button>
<button class="btn-secondary" type="button" id="clear-path">Clear Path</button>
</div>
<div id="path-result" class="path-result">No path calculated.</div>
</form>
</section>
</section>
<section class="graph-panel">
<div class="toolbar">
<span>Total Nodes: <strong id="total-nodes">0</strong></span>
<span>Total Edges: <strong id="total-edges">0</strong></span>
<select id="layout-mode" title="Layout mode">
<option value="circular">Circular</option>
<option value="hierarchical">Hierarchical</option>
<option value="grid">Grid</option>
<option value="radial">Radial</option>
</select>
<button class="btn-secondary" id="zoom-out" type="button" title="Zoom out">-</button>
<button class="btn-secondary" id="zoom-in" type="button" title="Zoom in">+</button>
<button class="btn-secondary" id="zoom-reset" type="button" title="Reset zoom">Fit</button>
<span class="kbd-hint">Shortcuts: <kbd>/</kbd> Search, <kbd>d</kbd> Diff, <kbd>c</kbd> Checks</span>
</div>
<div id="active-filters" class="chips"></div>
<div class="legend" id="legend">
<span><i class="dot kind-workload"></i>Workload</span>
<span><i class="dot kind-network"></i>Network</span>
<span><i class="dot kind-config"></i>Config</span>
<span><i class="dot kind-secret"></i>Sensitive</span>
<span><i class="dot kind-group"></i>Group</span>
<span><i class="dot health-warning"></i>Warning</span>
</div>
<svg id="graph-canvas" viewBox="0 0 1200 720" aria-label="Resource graph"></svg>
<div id="graph-empty" class="graph-overlay hidden">
<strong>No manifests loaded yet.</strong>
<span>Paste YAML or upload files in <em>Data</em>, then click Parse.</span>
<button class="btn-secondary" id="open-data-tab" type="button">Go To Data</button>
</div>
<div id="no-match" class="no-match hidden">
<strong>No nodes match current filters.</strong>
<span>Try broader search terms or reset all filters.</span>
<button class="btn-secondary" id="open-filter-tab" type="button">Open Filters</button>
<button class="btn-secondary" id="clear-filters-inline" type="button">Reset Filters</button>
</div>
<div id="edge-tooltip" class="edge-tooltip hidden"></div>
<div class="minimap-wrap">
<strong>Minimap</strong>
<svg id="minimap-canvas" viewBox="0 0 1200 720" aria-label="Graph minimap"></svg>
</div>
</section>
<aside class="details-panel">
<h2>Resource Details</h2>
<p id="details-empty">Select a node to inspect details.</p>
<div id="details-content" class="hidden">
<p><strong id="details-kind"></strong> <span id="details-name"></span></p>
<p>Namespace: <span id="details-namespace"></span></p>
<p id="details-sensitive" class="sensitive hidden">Sensitive resource: values redacted</p>
<pre id="details-raw"></pre>
</div>
</aside>
</main>
<div id="diff-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="diff-title">
<div class="modal-card">
<div class="modal-head">
<h3 id="diff-title">Manifest Diff</h3>
<button class="btn-secondary" id="close-diff" type="button">Close</button>
</div>
<label for="diff-base">Base manifests</label>
<textarea id="diff-base" rows="6" placeholder="Current state YAML"></textarea>
<label for="diff-target">Target manifests</label>
<textarea id="diff-target" rows="6" placeholder="New state YAML"></textarea>
<div class="row compact">
<button class="btn-primary" id="run-diff" type="button">Run Diff</button>
</div>
<div id="diff-output" class="diff-output">No diff executed.</div>
</div>
</div>
<div id="checks-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="checks-title">
<div class="modal-card">
<div class="modal-head">
<h3 id="checks-title">Manifest Checks</h3>
<button class="btn-secondary" id="close-checks" type="button">Close</button>
</div>
<details class="check-help">
<summary><span class="summary-title">What is checked?</span></summary>
<p>Security and validation checks run on loaded manifests. Disable rules you do not want to evaluate.</p>
</details>
<fieldset class="check-config">
<legend>Enabled Rules</legend>
<label><input type="checkbox" name="checkRules" value="privileged_container" checked> Privileged container</label>
<label><input type="checkbox" name="checkRules" value="run_as_non_root_false" checked> runAsNonRoot=false</label>
<label><input type="checkbox" name="checkRules" value="missing_resource_requests" checked> Missing resource requests</label>
<label><input type="checkbox" name="checkRules" value="missing_resource_limits" checked> Missing resource limits</label>
<label><input type="checkbox" name="checkRules" value="ingress_wildcard_host" checked> Ingress wildcard/empty host</label>
<label><input type="checkbox" name="checkRules" value="unresolved_reference" checked> Unresolved references</label>
<label><input type="checkbox" name="checkRules" value="selector_mismatch" checked> Service selector mismatch</label>
<label><input type="checkbox" name="checkRules" value="duplicate_resource_id" checked> Duplicate resource IDs</label>
</fieldset>
<div class="row compact">
<button class="btn-secondary" id="reset-checks" type="button">Reset Check Defaults</button>
</div>
<div id="findings-summary">No checks yet.</div>
<ul id="findings-list" class="findings-list"></ul>
</div>
</div>
</body>
</html>