CyberStrikeAI/internal/handler/vulnerability_archive_test.go

281 lines
12 KiB
Go

package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/deepassessment"
"cyberstrike-ai/internal/project"
"cyberstrike-ai/internal/security"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestProjectArchiveFollowsProjectAndPreservesManualVulnerabilityArchive(t *testing.T) {
logger := zap.NewNop()
db, err := database.NewDB(filepath.Join(t.TempDir(), "archive.db"), logger)
if err != nil {
t.Fatal(err)
}
defer db.Close()
p, err := db.CreateProject(&database.Project{Name: "Archive example"})
if err != nil {
t.Fatal(err)
}
conv, err := db.CreateConversation("Example", database.ConversationCreateMeta{ProjectID: p.ID})
if err != nil {
t.Fatal(err)
}
memory := &database.ProjectFact{ProjectID: p.ID, FactKey: "note/context-example", Summary: "Original memory", SourceConversationID: conv.ID}
if err := db.SaveContextCheckpoint(memory); err != nil {
t.Fatal(err)
}
for _, v := range []*database.Vulnerability{
{ID: "linked", ConversationID: conv.ID, Title: "Linked record", Description: "Saved description", Severity: "medium", Status: "confirmed", TaskTag: "linked-task"},
{ID: "manual", ProjectID: p.ID, Title: "Manual archive", Severity: "low"},
{ID: "unbound", Title: "Independent record", Severity: "low", TaskTag: "unbound-task"},
} {
if _, err := db.CreateVulnerability(v); err != nil {
t.Fatal(err)
}
}
vulns := NewVulnerabilityHandler(db, logger)
projects := NewProjectHandler(db, logger)
router := gin.New()
router.PUT("/projects/:id", projects.UpdateProject)
router.GET("/vulnerabilities/:id", vulns.GetVulnerability)
router.GET("/vulnerabilities", vulns.ListVulnerabilities)
router.GET("/vulnerabilities/stats", vulns.GetVulnerabilityStats)
router.GET("/vulnerabilities/filter-options", vulns.GetVulnerabilityFilterOptions)
router.GET("/vulnerabilities/export", vulns.ExportVulnerabilities)
router.PUT("/vulnerabilities/:id/archive", vulns.SetVulnerabilityArchived)
request := func(method, path, body string, status int, into any) {
t.Helper()
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
if w.Code != status {
t.Fatalf("%s %s: got %d, want %d, body %s", method, path, w.Code, status, w.Body)
}
if into != nil {
if err := json.Unmarshal(w.Body.Bytes(), into); err != nil {
t.Fatal(err)
}
}
}
request(http.MethodPut, "/vulnerabilities/manual/archive", `{}`, http.StatusBadRequest, nil)
request(http.MethodPut, "/vulnerabilities/manual/archive", `{"archived":true}`, http.StatusOK, nil)
request(http.MethodPut, "/projects/"+p.ID, `{"status":"archived"}`, http.StatusOK, nil)
request(http.MethodPut, "/projects/"+p.ID, `{"description":"Retained"}`, http.StatusOK, nil)
request(http.MethodPut, "/vulnerabilities/linked/archive", `{"archived":false}`, http.StatusOK, nil)
cfg := config.ProjectConfig{Enabled: true}
block, err := project.BuildFactIndexBlock(db, p.ID, cfg, conv.ID)
if err != nil || block != "" {
t.Fatalf("archived memory was injected: %q, %v", block, err)
}
memory.Summary = "New checkpoint after archive"
if err := db.SaveContextCheckpoint(memory); err == nil {
t.Fatal("archived project accepted a new automatic checkpoint")
}
var active, archived ListVulnerabilitiesResponse
const listURL = "/vulnerabilities?pagination=records&group_by=task"
request(http.MethodGet, listURL, "", http.StatusOK, &active)
request(http.MethodGet, listURL+"&archived=true", "", http.StatusOK, &archived)
if active.Total != 1 || len(active.Vulnerabilities) != 1 || active.Vulnerabilities[0].ID != "unbound" ||
len(active.Navigation) != 1 || active.Navigation[0].Key != "tag:unbound-task" || archived.Total != 2 || len(archived.Vulnerabilities) != 2 {
t.Fatalf("archive listing or grouping mismatch: active %+v, archived %+v", active, archived)
}
for _, v := range archived.Vulnerabilities {
if !v.Archived || !v.ProjectArchived {
t.Fatalf("missing archive fields on %s", v.ID)
}
}
var linked database.Vulnerability
request(http.MethodGet, "/vulnerabilities/linked", "", http.StatusOK, &linked)
if !linked.Archived || !linked.ProjectArchived || linked.Status != "confirmed" || linked.Description != "Saved description" {
t.Fatalf("archiving changed the finding or lost its status: %+v", linked)
}
var count struct{ Total int }
request(http.MethodGet, "/vulnerabilities/stats", "", http.StatusOK, &count)
if count.Total != 1 {
t.Fatalf("active stats include archived findings: %+v", count)
}
request(http.MethodGet, "/vulnerabilities/export?archived=true&project_id="+p.ID, "", http.StatusOK, &count)
if count.Total != 2 {
t.Fatalf("project archive export omitted findings: %+v", count)
}
var options map[string][]string
request(http.MethodGet, "/vulnerabilities/filter-options?archived=true", "", http.StatusOK, &options)
if tags := options["task_tags"]; len(tags) != 1 || tags[0] != "linked-task" {
t.Fatalf("archive filters show unrelated tags: %v", tags)
}
request(http.MethodPut, "/projects/"+p.ID, `{"status":"active"}`, http.StatusOK, nil)
var restored ListVulnerabilitiesResponse
request(http.MethodGet, listURL+"&archived=true", "", http.StatusOK, &restored)
if restored.Total != 1 || len(restored.Vulnerabilities) != 1 || restored.Vulnerabilities[0].ID != "manual" || restored.Vulnerabilities[0].ProjectArchived {
t.Fatalf("project restoration did not preserve the manual archive: %+v", restored)
}
block, err = project.BuildFactIndexBlock(db, p.ID, cfg, conv.ID)
if err != nil || !strings.Contains(block, "Original memory") || strings.Contains(block, memory.Summary) || strings.Contains(block, "Manual archive") {
t.Fatalf("restored project memory mismatch: %q, %v", block, err)
}
request(http.MethodPut, "/vulnerabilities/manual/archive", `{"archived":false}`, http.StatusOK, nil)
request(http.MethodGet, "/vulnerabilities/stats", "", http.StatusOK, &count)
if count.Total != 3 {
t.Fatalf("manual restoration did not return the finding to active stats: %+v", count)
}
}
func TestProjectArchiveSyncsLateConversationBindingAssetsAndDeepAssessment(t *testing.T) {
h, task := deepAssessmentFixture(t)
db := h.db
logger := zap.NewNop()
proj, err := db.CreateProject(&database.Project{Name: "Late Bound Project"})
if err != nil {
t.Fatal(err)
}
if _, err := db.SaveProjectFact(&database.ProjectFact{
ProjectID: proj.ID,
FactKey: "finding/secret-fact",
Category: "finding",
Summary: "Confirmed SQLi on admin endpoint",
Body: "POST /admin/login",
}, nil, nil, false, false); err != nil {
t.Fatal(err)
}
lateConv, err := db.CreateConversation("Unbound scan", database.ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
if _, err := db.CreateVulnerability(&database.Vulnerability{
ID: "late-vuln",
ConversationID: lateConv.ID,
Title: "Late bound RCE",
Severity: "high",
Status: "open",
Target: "https://asset.example.com",
}); err != nil {
t.Fatal(err)
}
asset := &database.Asset{Host: "https://asset.example.com"}
if _, err := db.UpsertAssets([]*database.Asset{asset}, task.OwnerID, true); err != nil {
t.Fatal(err)
}
if err := db.MarkAssetScanned(asset.ID, lateConv.ID, "", "", database.RBACListAccess{Scope: database.RBACScopeAll}); err != nil {
t.Fatal(err)
}
assertAssetRisk := func(wantCount int, wantLevel string) {
t.Helper()
items, _, err := db.ListAssets(10, 0, database.AssetListFilter{ID: asset.ID}, database.RBACListAccess{Scope: database.RBACScopeAll})
if err != nil || len(items) != 1 {
t.Fatalf("ListAssets failed: %v, len=%d", err, len(items))
}
if items[0].VulnerabilityCount != wantCount || items[0].RiskLevel != wantLevel {
t.Fatalf("asset risk mismatch: got count=%d level=%s, want count=%d level=%s", items[0].VulnerabilityCount, items[0].RiskLevel, wantCount, wantLevel)
}
}
assertAssetRisk(1, "high")
convHandler := NewConversationHandler(db, logger)
projects := NewProjectHandler(db, logger)
vulns := NewVulnerabilityHandler(db, logger)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(security.ContextSessionKey, security.Session{
UserID: task.OwnerID,
Scope: database.RBACScopeAll,
Permissions: map[string]bool{"project:read": true, "project:write": true, "assessments:read": true, "assessments:write": true, "asset:read": true, "vulnerability:read": true},
})
c.Next()
})
router.POST("/conversations", convHandler.CreateConversation)
router.PUT("/conversations/:id/project", convHandler.SetConversationProject)
router.PUT("/projects/:id", projects.UpdateProject)
router.PUT("/vulnerabilities/:id/archive", vulns.SetVulnerabilityArchived)
router.POST("/api/deep-assessments", h.CreateDeepAssessment)
callJSON := func(method, path, body string, wantStatus int) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != wantStatus {
t.Fatalf("%s %s: got %d, want %d, body=%s", method, path, w.Code, wantStatus, w.Body.String())
}
return w
}
// Bind previously unbound conversation to active project -> backfills late-vuln.project_id.
callJSON(http.MethodPut, "/conversations/"+lateConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusOK)
gotVuln, err := db.GetVulnerability("late-vuln")
if err != nil || gotVuln.ProjectID != proj.ID {
t.Fatalf("expected late-vuln to inherit project %s after SetConversationProject, got %+v (%v)", proj.ID, gotVuln, err)
}
// Create deep assessment while active, verify active context includes project_facts but excludes checkpoints.
checkpoint := &database.ProjectFact{ProjectID: proj.ID, FactKey: "note/context-chat", Summary: "Private chat checkpoint", SourceConversationID: lateConv.ID}
if err := db.SaveContextCheckpoint(checkpoint); err != nil {
t.Fatal(err)
}
createdResp := callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Active","objective":"评估 https://asset.example.com","project_id":"`+proj.ID+`"}`, http.StatusCreated)
var createdTask struct {
Task deepassessment.Task `json:"task"`
}
if err := json.Unmarshal(createdResp.Body.Bytes(), &createdTask); err != nil {
t.Fatal(err)
}
activeCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
if err != nil || !strings.Contains(activeCtx, "Confirmed SQLi on admin endpoint") || strings.Contains(activeCtx, "Private chat checkpoint") {
t.Fatalf("unexpected active deep assessment context: %q (%v)", activeCtx, err)
}
// Archive project -> late-vuln archives, asset risk drops to 0/normal, new bindings rejected, deep assessment stops injecting facts.
callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"archived"}`, http.StatusOK)
gotVuln, err = db.GetVulnerability("late-vuln")
if err != nil || !gotVuln.Archived || !gotVuln.ProjectArchived {
t.Fatalf("expected late-vuln to archive with project: %+v (%v)", gotVuln, err)
}
assertAssetRisk(0, "normal")
otherConv, err := db.CreateConversation("Other", database.ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
callJSON(http.MethodPost, "/conversations", `{"title":"Blocked","projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
callJSON(http.MethodPut, "/conversations/"+otherConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Blocked","objective":"评估目标","project_id":"`+proj.ID+`"}`, http.StatusBadRequest)
archivedCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
if err != nil || strings.Contains(archivedCtx, "Confirmed SQLi on admin endpoint") || !strings.Contains(archivedCtx, `"project_archived":true`) {
t.Fatalf("archived project facts leaked into deep assessment context: %q (%v)", archivedCtx, err)
}
// Restore project -> asset risk returns to 1/high; manual archive/restore also refreshes asset risk cache.
callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"active"}`, http.StatusOK)
assertAssetRisk(1, "high")
callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":true}`, http.StatusOK)
assertAssetRisk(0, "normal")
callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":false}`, http.StatusOK)
assertAssetRisk(1, "high")
}