Files
CyberStrikeAI/internal/handler/vulnerability_workspace_test.go
T

79 lines
2.8 KiB
Go

package handler
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"cyberstrike-ai/internal/database"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestVulnerabilityWorkspaceHTTPFlow(t *testing.T) {
db, err := database.NewDB(filepath.Join(t.TempDir(), "workspace.db"), zap.NewNop())
if err != nil {
t.Fatal(err)
}
defer db.Close()
h := NewVulnerabilityHandler(db, zap.NewNop())
router := gin.New()
router.POST("/vulnerabilities/cases", h.MergeVulnerabilities)
router.POST("/vulnerabilities/cases/:caseID/split", h.DissolveVulnerabilityCase)
router.GET("/vulnerabilities/:id/context", h.VulnerabilityContext)
router.GET("/vulnerabilities", h.ListVulnerabilities)
a, _ := db.CreateVulnerability(&database.Vulnerability{Title: "one", Severity: "high", Target: "https://a.example.com", Evidence: "full proof"})
b, _ := db.CreateVulnerability(&database.Vulnerability{Title: "two", Severity: "high", Target: "https://b.example.com", Evidence: "other proof"})
request := func(method, path string, payload any) map[string]json.RawMessage {
t.Helper()
body, _ := json.Marshal(payload)
req := httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
var result map[string]json.RawMessage
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
result := request("POST", "/vulnerabilities/cases", map[string]any{"ids": []string{a.ID, b.ID}, "title": "shared issue", "reason": "same root cause"})
var id string
json.Unmarshal(result["id"], &id)
if id == "" {
t.Fatal("missing case ID")
}
result = request("GET", "/vulnerabilities?group_by=case&limit=1&summary=true", nil)
var list []*database.Vulnerability
if err := json.Unmarshal(result["vulnerabilities"], &list); err != nil {
t.Fatal(err)
}
if len(list) != 2 || list[0].Evidence != "" {
t.Fatal("summary response includes evidence")
}
context := request("GET", "/vulnerabilities/"+a.ID+"/context", nil)
var detail database.Vulnerability
json.Unmarshal(context["vulnerability"], &detail)
if detail.Evidence != "full proof" || detail.CaseID != id {
t.Fatalf("detail: %+v", detail)
}
var members []database.Vulnerability
json.Unmarshal(context["members"], &members)
if len(members) != 2 {
t.Fatalf("members: %d", len(members))
}
request("POST", "/vulnerabilities/cases/"+id+"/split", map[string]string{"reason": "distinct causes"})
context = request("GET", "/vulnerabilities/"+a.ID+"/context", nil)
var history []database.VulnerabilityHistoryItem
json.Unmarshal(context["history"], &history)
if len(history) != 2 {
t.Fatalf("history: %+v", history)
}
}