485 lines
16 KiB
Go
485 lines
16 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"cyberstrike-ai/internal/surfaceingest"
|
|
)
|
|
|
|
const (
|
|
maxProjectSyncFacts = 500
|
|
maxProjectSyncExecutions = 80
|
|
maxProjectSyncUserPrompts = 40
|
|
maxProjectSyncVulns = 500
|
|
maxProjectSyncChainNodes = 500
|
|
)
|
|
|
|
type projectScopeJSON struct {
|
|
Targets []string `json:"targets"`
|
|
Exclude []string `json:"exclude"`
|
|
}
|
|
|
|
func parseProjectScopeTargets(raw string) (targets, exclude string) {
|
|
var payload projectScopeJSON
|
|
if json.Unmarshal([]byte(strings.TrimSpace(raw)), &payload) != nil {
|
|
return "", ""
|
|
}
|
|
return strings.Join(payload.Targets, "\n"), strings.Join(payload.Exclude, "\n")
|
|
}
|
|
|
|
func isStructuredTargetFact(category, factKey string) bool {
|
|
cat := strings.ToLower(strings.TrimSpace(category))
|
|
key := strings.ToLower(strings.TrimSpace(factKey))
|
|
return cat == "target" || cat == "infra" ||
|
|
strings.HasPrefix(key, "target/") || strings.HasPrefix(key, "infra/")
|
|
}
|
|
|
|
func isArtifactOnlyFactKey(factKey string) bool {
|
|
key := strings.ToLower(strings.TrimSpace(factKey))
|
|
return strings.HasPrefix(key, "artifact/")
|
|
}
|
|
|
|
func extractAttackChainTargetMetadata(raw string) string {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" || !strings.HasPrefix(raw, "{") {
|
|
return ""
|
|
}
|
|
var meta map[string]any
|
|
if json.Unmarshal([]byte(raw), &meta) != nil {
|
|
return ""
|
|
}
|
|
var parts []string
|
|
for _, k := range []string{"target", "host", "url", "domain", "ip"} {
|
|
if v, ok := meta[k].(string); ok && strings.TrimSpace(v) != "" {
|
|
parts = append(parts, strings.TrimSpace(v))
|
|
}
|
|
}
|
|
return strings.Join(parts, "\n")
|
|
}
|
|
|
|
func unwrapStoredToolExecutionText(raw string) string {
|
|
trimmed := strings.TrimSpace(raw)
|
|
if trimmed == "" {
|
|
return ""
|
|
}
|
|
if strings.HasPrefix(trimmed, "{") {
|
|
var envelope struct {
|
|
Content []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
} `json:"content"`
|
|
}
|
|
if json.Unmarshal([]byte(trimmed), &envelope) == nil && len(envelope.Content) > 0 {
|
|
var b strings.Builder
|
|
for _, item := range envelope.Content {
|
|
if item.Text != "" {
|
|
if b.Len() > 0 {
|
|
b.WriteByte('\n')
|
|
}
|
|
b.WriteString(item.Text)
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|
|
}
|
|
return trimmed
|
|
}
|
|
|
|
func surfaceHitHost(hit surfaceingest.SurfaceHit) string {
|
|
if hit.Domain != "" {
|
|
return hit.Domain
|
|
}
|
|
return hit.IP
|
|
}
|
|
|
|
func clipSurfaceSource(value string, max int) string {
|
|
value = strings.TrimSpace(value)
|
|
runes := []rune(value)
|
|
if len(runes) <= max {
|
|
return value
|
|
}
|
|
return string(runes[:max])
|
|
}
|
|
|
|
func isEndpointValidationError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
text := err.Error()
|
|
return strings.Contains(text, "invalid HTTP method") || strings.Contains(text, "endpoint path")
|
|
}
|
|
|
|
// CountSharedProjectFacts counts non-deprecated project facts excluding automatic session checkpoints.
|
|
func (db *DB) CountSharedProjectFacts(projectID string) (int, error) {
|
|
projectID = strings.TrimSpace(projectID)
|
|
if db == nil || projectID == "" {
|
|
return 0, nil
|
|
}
|
|
var count int
|
|
err := db.QueryRow(
|
|
`SELECT COUNT(*) FROM project_facts WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'`,
|
|
projectID,
|
|
).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
func (db *DB) applyProjectSurfaceHits(projectID, source, sourceQuery, ownerUserID string, allowGlobal bool, hits []surfaceingest.SurfaceHit) ([]string, error) {
|
|
projectID = strings.TrimSpace(projectID)
|
|
if db == nil || projectID == "" || len(hits) == 0 {
|
|
return nil, nil
|
|
}
|
|
scope := RBACScopeAssigned
|
|
if allowGlobal || strings.TrimSpace(ownerUserID) == "" {
|
|
scope = RBACScopeAll
|
|
}
|
|
access := RBACListAccess{UserID: ownerUserID, Scope: scope}
|
|
var applied []string
|
|
for _, hit := range hits {
|
|
asset := &Asset{
|
|
ProjectID: projectID,
|
|
Host: surfaceHitHost(hit),
|
|
IP: hit.IP,
|
|
Domain: hit.Domain,
|
|
Port: hit.Port,
|
|
Protocol: hit.Protocol,
|
|
Source: source,
|
|
SourceQuery: clipSurfaceSource(sourceQuery, 500),
|
|
Status: "active",
|
|
}
|
|
res, err := db.UpsertAssetsInProject([]*Asset{asset}, ownerUserID, allowGlobal, projectID)
|
|
if err != nil {
|
|
var invalid *AssetValidationError
|
|
if errors.As(err, &invalid) {
|
|
continue
|
|
}
|
|
return applied, err
|
|
}
|
|
if len(res.AppliedIDs) == 0 {
|
|
continue
|
|
}
|
|
id := res.AppliedIDs[0]
|
|
applied = append(applied, id)
|
|
for _, ep := range hit.Endpoints {
|
|
epErr := db.PutAssetEndpoint(&AssetEndpoint{AssetID: id, Method: ep.Method, Path: ep.Path}, access)
|
|
if epErr != nil && !isEndpointValidationError(epErr) {
|
|
return applied, epErr
|
|
}
|
|
}
|
|
}
|
|
return applied, nil
|
|
}
|
|
|
|
func (db *DB) projectSeedsAndExclusions(projectID string) ([]surfaceingest.ScopeSeed, []surfaceingest.ScopeSeed, string) {
|
|
var scopeTargets, scopeExclude string
|
|
if proj, err := db.GetProject(projectID); err == nil && proj != nil {
|
|
scopeTargets, scopeExclude = parseProjectScopeTargets(proj.ScopeJSON)
|
|
}
|
|
excluded := surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeExclude))
|
|
rows, err := db.ListAssetScopeSeeds(5000, AssetListFilter{ProjectID: projectID}, RBACListAccess{Scope: RBACScopeAll})
|
|
var seeds []surfaceingest.ScopeSeed
|
|
if err == nil {
|
|
for _, r := range rows {
|
|
seeds = append(seeds, surfaceingest.ScopeSeed{Host: r.Host, IP: r.IP, Domain: r.Domain})
|
|
}
|
|
}
|
|
if scopeTargets != "" {
|
|
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeTargets))...)
|
|
}
|
|
return seeds, excluded, scopeTargets
|
|
}
|
|
|
|
// SyncFactTargetsToAssets materializes targets referenced in a saved project fact into the project's asset library.
|
|
func (db *DB) SyncFactTargetsToAssets(projectID string, fact *ProjectFact, ownerUserID string, allowGlobal bool) ([]string, error) {
|
|
projectID = strings.TrimSpace(projectID)
|
|
if db == nil || projectID == "" || fact == nil || fact.Confidence == "deprecated" || IsContextCheckpointKey(fact.FactKey) || isArtifactOnlyFactKey(fact.FactKey) {
|
|
return nil, nil
|
|
}
|
|
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
|
return nil, nil
|
|
}
|
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
|
var structured, prose []string
|
|
if isStructuredTargetFact(fact.Category, fact.FactKey) {
|
|
structured = append(structured, fact.Summary, fact.Body)
|
|
} else {
|
|
structured = append(structured, fact.Summary)
|
|
prose = append(prose, fact.Body)
|
|
}
|
|
hits := surfaceingest.ExtractPrecipitatedTargets(structured, prose, seeds, excluded)
|
|
return db.applyProjectSurfaceHits(projectID, "project_fact", fact.FactKey, ownerUserID, allowGlobal, hits)
|
|
}
|
|
|
|
// SyncVulnerabilityTargetToAssets materializes a recorded vulnerability's target into the project's asset library.
|
|
func (db *DB) SyncVulnerabilityTargetToAssets(projectID, target, ownerUserID string, allowGlobal bool) ([]string, error) {
|
|
projectID = strings.TrimSpace(projectID)
|
|
target = strings.TrimSpace(target)
|
|
if db == nil || projectID == "" || target == "" {
|
|
return nil, nil
|
|
}
|
|
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
|
return nil, nil
|
|
}
|
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
|
hits := surfaceingest.ExtractPrecipitatedTargets([]string{target}, nil, seeds, excluded)
|
|
return db.applyProjectSurfaceHits(projectID, "vulnerability", target, ownerUserID, allowGlobal, hits)
|
|
}
|
|
|
|
// IngestBoundConversationSurface writes in-scope discoveries from classic chat or batch tool outputs
|
|
// into the bound project's shared asset library.
|
|
func (db *DB) IngestBoundConversationSurface(conversationID, toolName, content, ownerUserID string, allowGlobal bool) (int, error) {
|
|
conversationID = strings.TrimSpace(conversationID)
|
|
if db == nil || conversationID == "" || strings.TrimSpace(content) == "" {
|
|
return 0, nil
|
|
}
|
|
projectID, err := db.GetConversationProjectID(conversationID)
|
|
if err != nil || strings.TrimSpace(projectID) == "" {
|
|
return 0, nil
|
|
}
|
|
projectID = strings.TrimSpace(projectID)
|
|
proj, err := db.GetProject(projectID)
|
|
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
|
return 0, nil
|
|
}
|
|
if ownerUserID == "" {
|
|
_ = db.QueryRow(`SELECT COALESCE(owner_user_id, '') FROM conversations WHERE id = ?`, conversationID).Scan(&ownerUserID)
|
|
ownerUserID = strings.TrimSpace(ownerUserID)
|
|
}
|
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
|
// Also seed from explicit targets declared in this conversation's user prompts or target facts.
|
|
promptRows, err := db.Query(
|
|
`SELECT content FROM messages WHERE conversation_id = ? AND role = 'user' ORDER BY created_at DESC LIMIT 10`,
|
|
conversationID,
|
|
)
|
|
if err == nil {
|
|
var userTexts []string
|
|
for promptRows.Next() {
|
|
var body string
|
|
if promptRows.Scan(&body) == nil && strings.TrimSpace(body) != "" {
|
|
userTexts = append(userTexts, body)
|
|
}
|
|
}
|
|
_ = promptRows.Close()
|
|
if len(userTexts) > 0 {
|
|
promptHits := surfaceingest.ExtractPrecipitatedTargets(userTexts, nil, seeds, excluded)
|
|
if len(promptHits) > 0 {
|
|
_, _ = db.applyProjectSurfaceHits(projectID, "chat", "conversation_prompt", ownerUserID, allowGlobal, promptHits)
|
|
seeds = append(seeds, surfaceingest.SeedsFromHits(promptHits)...)
|
|
}
|
|
}
|
|
}
|
|
factRows, err := db.Query(
|
|
`SELECT category, fact_key, summary, COALESCE(body, '') FROM project_facts
|
|
WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'
|
|
ORDER BY updated_at DESC LIMIT 60`,
|
|
projectID,
|
|
)
|
|
if err == nil {
|
|
var structured []string
|
|
for factRows.Next() {
|
|
var cat, key, summary, body string
|
|
if factRows.Scan(&cat, &key, &summary, &body) == nil && !isArtifactOnlyFactKey(key) {
|
|
structured = append(structured, summary)
|
|
if isStructuredTargetFact(cat, key) {
|
|
structured = append(structured, body)
|
|
}
|
|
}
|
|
}
|
|
_ = factRows.Close()
|
|
if len(structured) > 0 {
|
|
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractPrecipitatedTargets(structured, nil, nil, excluded))...)
|
|
}
|
|
}
|
|
if len(seeds) == 0 {
|
|
return 0, nil
|
|
}
|
|
hits, _ := surfaceingest.Ingest(content, seeds, excluded)
|
|
applied, err := db.applyProjectSurfaceHits(projectID, "chat", toolName, ownerUserID, allowGlobal, hits)
|
|
return len(applied), err
|
|
}
|
|
|
|
// SyncProjectPrecipitatedAssets backfills and synchronizes targets precipitated in classic
|
|
// conversations (project facts, promoted/cached attack-chain target nodes, vulnerabilities,
|
|
// scope_json targets, unassigned conversation-scanned assets, and in-scope tool outputs)
|
|
// into the project's shared asset library.
|
|
func (db *DB) SyncProjectPrecipitatedAssets(projectID, ownerUserID string, allowGlobal bool) (int, error) {
|
|
projectID = strings.TrimSpace(projectID)
|
|
if db == nil || projectID == "" {
|
|
return 0, nil
|
|
}
|
|
proj, err := db.GetProject(projectID)
|
|
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
|
return 0, nil
|
|
}
|
|
ownerUserID = strings.TrimSpace(ownerUserID)
|
|
adopted := 0
|
|
|
|
// 1. Adopt unassigned assets that were scanned in conversations bound to this project.
|
|
now := time.Now()
|
|
var adoptRes sql.Result
|
|
if allowGlobal || ownerUserID == "" {
|
|
adoptRes, _ = db.Exec(
|
|
`UPDATE assets SET project_id = ?, updated_at = ?
|
|
WHERE COALESCE(project_id, '') = '' AND COALESCE(last_scan_conversation_id, '') <> ''
|
|
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
|
|
projectID, now, projectID,
|
|
)
|
|
} else {
|
|
adoptRes, _ = db.Exec(
|
|
`UPDATE assets SET project_id = ?, updated_at = ?
|
|
WHERE COALESCE(project_id, '') = '' AND COALESCE(owner_user_id, '') = ?
|
|
AND COALESCE(last_scan_conversation_id, '') <> ''
|
|
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
|
|
projectID, now, ownerUserID, projectID,
|
|
)
|
|
}
|
|
if adoptRes != nil {
|
|
if n, nErr := adoptRes.RowsAffected(); nErr == nil {
|
|
adopted += int(n)
|
|
}
|
|
}
|
|
|
|
seeds, excluded, scopeTargets := db.projectSeedsAndExclusions(projectID)
|
|
var structuredTexts []string
|
|
var proseTexts []string
|
|
if scopeTargets != "" {
|
|
structuredTexts = append(structuredTexts, scopeTargets)
|
|
}
|
|
|
|
// 2. Collect recorded vulnerabilities in this project.
|
|
vulnRows, err := db.Query(
|
|
`SELECT COALESCE(target, ''), COALESCE(targets_json, '') FROM vulnerabilities
|
|
WHERE project_id = ? AND manually_archived = 0 ORDER BY updated_at DESC LIMIT ?`,
|
|
projectID, maxProjectSyncVulns,
|
|
)
|
|
if err == nil {
|
|
for vulnRows.Next() {
|
|
var target, targetsJSON string
|
|
if vulnRows.Scan(&target, &targetsJSON) != nil {
|
|
continue
|
|
}
|
|
if strings.TrimSpace(target) != "" {
|
|
structuredTexts = append(structuredTexts, target)
|
|
}
|
|
if strings.TrimSpace(targetsJSON) != "" && targetsJSON != "[]" {
|
|
var list []string
|
|
if json.Unmarshal([]byte(targetsJSON), &list) == nil && len(list) > 0 {
|
|
structuredTexts = append(structuredTexts, strings.Join(list, "\n"))
|
|
}
|
|
}
|
|
}
|
|
_ = vulnRows.Close()
|
|
}
|
|
|
|
// 3. Collect target nodes from conversation attack chains bound to this project.
|
|
chainRows, err := db.Query(
|
|
`SELECT acn.node_name, COALESCE(acn.metadata, '')
|
|
FROM attack_chain_nodes acn
|
|
INNER JOIN conversations c ON c.id = acn.conversation_id
|
|
WHERE c.project_id = ? AND LOWER(acn.node_type) = 'target'
|
|
ORDER BY acn.created_at DESC LIMIT ?`,
|
|
projectID, maxProjectSyncChainNodes,
|
|
)
|
|
if err == nil {
|
|
for chainRows.Next() {
|
|
var name, metadata string
|
|
if chainRows.Scan(&name, &metadata) != nil {
|
|
continue
|
|
}
|
|
if strings.TrimSpace(name) != "" {
|
|
structuredTexts = append(structuredTexts, name)
|
|
}
|
|
if metaTargets := extractAttackChainTargetMetadata(metadata); metaTargets != "" {
|
|
structuredTexts = append(structuredTexts, metaTargets)
|
|
}
|
|
}
|
|
_ = chainRows.Close()
|
|
}
|
|
|
|
// 4. Collect project blackboard facts.
|
|
factRows, err := db.Query(
|
|
`SELECT category, fact_key, summary, COALESCE(body, '')
|
|
FROM project_facts
|
|
WHERE project_id = ? AND confidence != 'deprecated'
|
|
ORDER BY pinned DESC, updated_at DESC LIMIT ?`,
|
|
projectID, maxProjectSyncFacts,
|
|
)
|
|
if err == nil {
|
|
for factRows.Next() {
|
|
var cat, key, summary, body string
|
|
if factRows.Scan(&cat, &key, &summary, &body) != nil {
|
|
continue
|
|
}
|
|
if IsContextCheckpointKey(key) {
|
|
if strings.TrimSpace(body) != "" {
|
|
proseTexts = append(proseTexts, body)
|
|
}
|
|
continue
|
|
}
|
|
if isArtifactOnlyFactKey(key) {
|
|
continue
|
|
}
|
|
if isStructuredTargetFact(cat, key) {
|
|
structuredTexts = append(structuredTexts, summary, body)
|
|
} else {
|
|
structuredTexts = append(structuredTexts, summary)
|
|
if strings.TrimSpace(body) != "" {
|
|
proseTexts = append(proseTexts, body)
|
|
}
|
|
}
|
|
}
|
|
_ = factRows.Close()
|
|
}
|
|
|
|
// 5. Collect user prompts and completed tool outputs from bound non-assessment conversations.
|
|
promptRows, err := db.Query(
|
|
`SELECT m.content
|
|
FROM messages m
|
|
INNER JOIN conversations c ON c.id = m.conversation_id
|
|
WHERE c.project_id = ? AND m.role = 'user'
|
|
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
|
|
ORDER BY m.created_at DESC LIMIT ?`,
|
|
projectID, maxProjectSyncUserPrompts,
|
|
)
|
|
if err == nil {
|
|
for promptRows.Next() {
|
|
var content string
|
|
if promptRows.Scan(&content) == nil && strings.TrimSpace(content) != "" {
|
|
structuredTexts = append(structuredTexts, content)
|
|
}
|
|
}
|
|
_ = promptRows.Close()
|
|
}
|
|
|
|
execRows, err := db.Query(
|
|
`SELECT COALESCE(te.result, '')
|
|
FROM tool_executions te
|
|
INNER JOIN conversations c ON c.id = te.conversation_id
|
|
WHERE c.project_id = ? AND te.status = 'completed' AND COALESCE(te.result, '') <> ''
|
|
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
|
|
ORDER BY te.created_at DESC LIMIT ?`,
|
|
projectID, maxProjectSyncExecutions,
|
|
)
|
|
if err == nil {
|
|
for execRows.Next() {
|
|
var raw string
|
|
if execRows.Scan(&raw) == nil {
|
|
if text := unwrapStoredToolExecutionText(raw); text != "" {
|
|
proseTexts = append(proseTexts, text)
|
|
}
|
|
}
|
|
}
|
|
_ = execRows.Close()
|
|
}
|
|
|
|
hits := surfaceingest.ExtractPrecipitatedTargets(structuredTexts, proseTexts, seeds, excluded)
|
|
applied, err := db.applyProjectSurfaceHits(projectID, "project_sync", "project_precipitation", ownerUserID, allowGlobal, hits)
|
|
if err != nil {
|
|
return adopted + len(applied), err
|
|
}
|
|
return adopted + len(applied), nil
|
|
}
|