From 91bf8bc00b7f73fbbb4d59c5bf53cd0ffd9f7b93 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:16:03 +0100 Subject: [PATCH] fix(agent,server): scope discovery coverage by surface with >=50 entries and warn on JSON/all-404 CTF vhosts --- agent/discovery_gate.go | 159 +++++++++++++++++++++++++++-- agent/discovery_gate_extra_test.go | 90 ++++++++++++++++ agent/hypothesis.go | 17 +-- agent/tools.go | 5 +- server/target_fingerprint.go | 17 ++- server/target_fingerprint_test.go | 17 +++ 6 files changed, 283 insertions(+), 22 deletions(-) create mode 100644 agent/discovery_gate_extra_test.go diff --git a/agent/discovery_gate.go b/agent/discovery_gate.go index 67471e01..4ec3eade 100644 --- a/agent/discovery_gate.go +++ b/agent/discovery_gate.go @@ -3,12 +3,17 @@ package agent import ( "encoding/json" "fmt" + "net/url" "regexp" "strings" "github.com/Autumn-27/artex/db" ) +// MinDiscoveryWordlistEntries enforces a real wordlist run (at least 50 entries) +// so a trivial 1-entry run cannot satisfy criterion (a) of DiscoveryArtifact. +const MinDiscoveryWordlistEntries = 50 + // DiscoveryWordlistRun captures criterion (a): at least one curated/real // wordlist run (such as skills/api-recon/wordlists/api.txt). type DiscoveryWordlistRun struct { @@ -29,8 +34,8 @@ type DiscoveryArtifact struct { func (a DiscoveryArtifact) MissingChecks() []string { var missing []string - if strings.TrimSpace(a.WordlistRun.Wordlist) == "" || a.WordlistRun.EntriesTested <= 0 { - missing = append(missing, "(a) wordlist_run with non-empty wordlist (e.g. skills/api-recon/wordlists/api.txt) and entries_tested > 0") + if strings.TrimSpace(a.WordlistRun.Wordlist) == "" || a.WordlistRun.EntriesTested < MinDiscoveryWordlistEntries { + missing = append(missing, fmt.Sprintf("(a) wordlist_run with non-empty wordlist (e.g. skills/api-recon/wordlists/api.txt) and entries_tested >= %d", MinDiscoveryWordlistEntries)) } if len(nonEmptyTrimmed(a.NestedPaths)) == 0 { missing = append(missing, "(b) nested_paths under discovered routes") @@ -68,7 +73,10 @@ func (a DiscoveryArtifact) CompactSummary() string { ) } -var routeExhaustionClaimRe = regexp.MustCompile(`(?i)\b(route(?:\s+space)?\s+exhaust(?:ed|ion)?|exhaust(?:ed|ion)\s+(?:all\s+)?routes|no\s+(?:more\s+)?(?:api\s+)?routes|endpoint(?:\s+space)?\s+exhaust(?:ed|ion)?|(?:all|404)\s+(?:on\s+)?\d+\s+root\s+nouns?|wordlist\s+exhaust(?:ed|ion)?|surface\s+exhaust(?:ed|ion)?)\b`) +var ( + routeExhaustionClaimRe = regexp.MustCompile(`(?i)\b(route(?:\s+space)?\s+exhaust(?:ed|ion)?|exhaust(?:ed|ion)\s+(?:all\s+)?routes|no\s+(?:more\s+)?(?:api\s+)?routes|endpoint(?:\s+space)?\s+exhaust(?:ed|ion)?|(?:all|404)\s+(?:on\s+)?\d+\s+root\s+nouns?|wordlist\s+exhaust(?:ed|ion)?|surface\s+exhaust(?:ed|ion)?)\b`) + dottedHostTokenRe = regexp.MustCompile(`(?i)\b([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)\b`) +) func isRouteExhaustionClaim(text string) bool { return routeExhaustionClaimRe.MatchString(text) @@ -84,21 +92,108 @@ func isRouteDiscoveryRiskArea(riskArea string) bool { } } +func normalizeDiscoverySurfaceHost(surface string) string { + s := strings.TrimSpace(strings.ToLower(surface)) + if s == "" { + return "" + } + if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") { + if u, err := url.Parse(s); err == nil && u.Hostname() != "" { + return strings.ToLower(strings.TrimSuffix(u.Hostname(), ".")) + } + } + if i := strings.IndexAny(s, "/?#"); i >= 0 { + s = s[:i] + } + if host, _, ok := strings.Cut(s, ":"); ok && !strings.Contains(host, "]") { + s = host + } + return strings.TrimSuffix(s, ".") +} + +func isLikelyNonHostFilename(tok string) bool { + for _, ext := range []string{ + ".txt", ".js", ".mjs", ".ts", ".json", ".yaml", ".yml", ".xml", + ".html", ".htm", ".css", ".png", ".jpg", ".svg", ".go", ".py", + ".sh", ".md", ".csv", ".log", ".pdf", + } { + if strings.HasSuffix(tok, ext) { + return true + } + } + return false +} + +func extractDiscoveryClaimHosts(text string) []string { + seen := map[string]bool{} + var hosts []string + add := func(h string) { + h = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(h), ".")) + if h == "" || seen[h] { + return + } + seen[h] = true + hosts = append(hosts, h) + } + for _, raw := range probeURLRe.FindAllString(text, 16) { + if u, err := url.Parse(strings.TrimRight(raw, `.,;:'")`)); err == nil && u.Hostname() != "" { + add(u.Hostname()) + } + } + for _, m := range dottedHostTokenRe.FindAllStringSubmatch(text, 16) { + if len(m) == 2 { + tok := strings.ToLower(m[1]) + if !isLikelyNonHostFilename(tok) { + add(tok) + } + } + } + return hosts +} + +type storedDiscoveryCoverage struct { + surface string + host string + art DiscoveryArtifact +} + func isDiscoveryCoverageNode(n *db.Node) (DiscoveryArtifact, bool) { - if n == nil || n.Kind != db.KindFact { + sc, ok := decodeDiscoveryCoverageNode(n) + if !ok { return DiscoveryArtifact{}, false } + return sc.art, true +} + +func decodeDiscoveryCoverageNode(n *db.Node) (storedDiscoveryCoverage, bool) { + if n == nil || n.Kind != db.KindFact { + return storedDiscoveryCoverage{}, false + } var p struct { Subtype string `json:"subtype"` + Surface string `json:"surface"` + Host string `json:"host"` Artifact *DiscoveryArtifact `json:"artifact"` } if json.Unmarshal(n.Payload, &p) != nil || p.Subtype != db.FactSubtypeDiscoveryCoverage || p.Artifact == nil { - return DiscoveryArtifact{}, false + return storedDiscoveryCoverage{}, false } - return *p.Artifact, true + host := strings.ToLower(strings.TrimSpace(p.Host)) + if host == "" { + host = normalizeDiscoverySurfaceHost(p.Surface) + } + return storedDiscoveryCoverage{ + surface: strings.ToLower(strings.TrimSpace(p.Surface)), + host: host, + art: *p.Artifact, + }, true } func hasCompleteDiscoveryCoverage(ts *db.ExplorationStore) bool { + return hasCompleteDiscoveryCoverageForClaim(ts, "") +} + +func hasCompleteDiscoveryCoverageForClaim(ts *db.ExplorationStore, claimText string) bool { if ts == nil { return false } @@ -106,21 +201,54 @@ func hasCompleteDiscoveryCoverage(ts *db.ExplorationStore) bool { if err != nil { return false } + var complete []storedDiscoveryCoverage for _, n := range nodes { - if art, ok := isDiscoveryCoverageNode(n); ok && len(art.MissingChecks()) == 0 { - return true + if sc, ok := decodeDiscoveryCoverageNode(n); ok && len(sc.art.MissingChecks()) == 0 { + complete = append(complete, sc) } } - return false + if len(complete) == 0 { + return false + } + + claimHosts := extractDiscoveryClaimHosts(claimText) + if len(claimHosts) == 0 { + desc, goal, _ := ts.Root() + claimHosts = extractDiscoveryClaimHosts(desc + " " + goal) + } + if len(claimHosts) == 0 { + return true + } + + claimLower := strings.ToLower(strings.TrimSpace(claimText)) + for _, targetHost := range claimHosts { + var matched bool + for _, sc := range complete { + if sc.host != "" && sc.host == targetHost { + matched = true + break + } + if sc.surface != "" && (sc.surface == targetHost || strings.Contains(claimLower, sc.surface)) { + matched = true + break + } + } + if !matched { + return false + } + } + return true } func recordDiscoveryCoverageFact(ts *db.ExplorationStore, intentID int64, surface string, art DiscoveryArtifact) (int64, error) { if ts == nil { return 0, nil } + host := normalizeDiscoverySurfaceHost(surface) payload := map[string]any{ "subtype": db.FactSubtypeDiscoveryCoverage, "surface": surface, + "host": host, "artifact": art, "summary": fmt.Sprintf("Discovery quality coverage complete for %s (%s)", surface, art.CompactSummary()), "source": "tool_output", @@ -138,8 +266,17 @@ func recordDiscoveryCoverageFact(ts *db.ExplorationStore, intentID int64, surfac } func missingDiscoveryCoverageError(ts *db.ExplorationStore) error { - if hasCompleteDiscoveryCoverage(ts) { + return missingDiscoveryCoverageErrorForClaim(ts, "") +} + +func missingDiscoveryCoverageErrorForClaim(ts *db.ExplorationStore, claimText string) error { + if hasCompleteDiscoveryCoverageForClaim(ts, claimText) { return nil } - return fmt.Errorf("route space cannot be declared exhausted without a complete record_coverage discovery_artifact covering all 5 checks: (a) wordlist_run (e.g. skills/api-recon/wordlists/api.txt), (b) nested_paths under discovered routes, (c) parameters_tested, (d) method_matrix, (e) static_docs_js_reviewed; a shallow 404 on root nouns is not exhaustive") + hosts := extractDiscoveryClaimHosts(claimText) + scopeNote := "" + if len(hosts) > 0 { + scopeNote = fmt.Sprintf(" matching target host/surface %s", strings.Join(hosts, ", ")) + } + return fmt.Errorf("route space cannot be declared exhausted without a complete record_coverage discovery_artifact%s covering all 5 checks: (a) wordlist_run (e.g. skills/api-recon/wordlists/api.txt, entries_tested >= %d), (b) nested_paths under discovered routes, (c) parameters_tested, (d) method_matrix, (e) static_docs_js_reviewed; a shallow 404 on root nouns is not exhaustive", scopeNote, MinDiscoveryWordlistEntries) } diff --git a/agent/discovery_gate_extra_test.go b/agent/discovery_gate_extra_test.go new file mode 100644 index 00000000..b90a35a7 --- /dev/null +++ b/agent/discovery_gate_extra_test.go @@ -0,0 +1,90 @@ +package agent + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestDiscoveryCoverageCrossHostAndMinimumWordlist(t *testing.T) { + d := testDB(t) + t.Cleanup(func() { _ = d.Close() }) + task, err := d.CreateTaskWithOptions("discovery-scope", "Enumerate routes on https://main.lab.local", db.TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(task.ID) }) + + store := d.Exploration(task.ExplorationID) + as := d.Assets() + workerTS := NewToolSet(store, "worker#1") + workerTS.SetTaskID(task.ID) + workerTS.SetAssetStore(as, as.Companies()) + plannerTS := NewToolSet(store, "planner") + plannerTS.SetTaskID(task.ID) + plannerTS.SetAssetStore(as, as.Companies()) + + // 1. A tiny 1-entry wordlist run CANNOT satisfy criterion (a). + tinyCov := json.RawMessage(`{ + "surface": "https://main.lab.local/", + "risk_area": "route_discovery", + "outcome": "no_issue_found", + "evidence": "tested 1 path", + "discovery_artifact": { + "wordlist_run": {"wordlist": "skills/api-recon/wordlists/api.txt", "entries_tested": 1}, + "nested_paths": ["/api/v1"], + "parameters_tested": ["id"], + "method_matrix": ["GET", "POST"], + "static_docs_js_reviewed": ["/docs"] + } + }`) + res, err := workerTS.recordCoverage().Call(t.Context(), tinyCov, nil) + if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "(a)") { + t.Fatalf("expected tiny 1-entry wordlist run rejected for (a), got err=%v res=%s", err, res.Flatten()) + } + + // 2. Complete coverage on main.lab.local unlocks exhaustion on main.lab.local ONLY. + mainCov := json.RawMessage(`{ + "surface": "https://main.lab.local/", + "risk_area": "route_discovery", + "outcome": "no_issue_found", + "evidence": "full 5-part discovery on main", + "discovery_artifact": { + "wordlist_run": {"wordlist": "skills/api-recon/wordlists/api.txt", "entries_tested": 126, "discovered": ["/api/v1/users"]}, + "nested_paths": ["/api/v1/users/profile"], + "parameters_tested": ["id", "role"], + "method_matrix": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + "static_docs_js_reviewed": ["/docs", "/static/app.js"] + } + }`) + if res, err := workerTS.recordCoverage().Call(t.Context(), mainCov, nil); err != nil || res.IsError { + t.Fatalf("expected complete main.lab.local discovery coverage accepted, got err=%v res=%s", err, res.Flatten()) + } + + // Cross-host exhaustion claim for estate.lab.local MUST STILL be rejected! + estateHyp := json.RawMessage(`{"hypothesis":"Discover routes on https://estate.lab.local/","status":"closed","close_reason":"route space exhausted on estate.lab.local; no more API routes"}`) + res, err = plannerTS.upsertHypothesis().Call(t.Context(), estateHyp, nil) + if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "estate.lab.local") { + t.Fatalf("expected main.lab.local coverage NOT to unlock estate.lab.local hypothesis close, got err=%v res=%s", err, res.Flatten()) + } + + estateFact := json.RawMessage(`{"facts":[{"summary":"Route space exhausted on https://estate.lab.local/: all 404","detail":"probed estate.lab.local","evidence":"404","confidence":"observed","source":"tool_output"}]}`) + res, err = workerTS.recordFact().Call(t.Context(), estateFact, nil) + if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "estate.lab.local") { + t.Fatalf("expected main.lab.local coverage NOT to unlock estate.lab.local record_fact exhaustion, got err=%v res=%s", err, res.Flatten()) + } + + estateGoalMet := json.RawMessage(`{"reason":"Route space exhausted on estate.lab.local"}`) + res, err = plannerTS.goalMet().Call(t.Context(), estateGoalMet, nil) + if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "estate.lab.local") { + t.Fatalf("expected main.lab.local coverage NOT to unlock estate.lab.local goal_met, got err=%v res=%s", err, res.Flatten()) + } + + // Same-host exhaustion claim on main.lab.local succeeds. + mainHyp := json.RawMessage(`{"hypothesis":"Discover routes on https://main.lab.local/","status":"closed","close_reason":"route space exhausted on main.lab.local"}`) + if res, err := plannerTS.upsertHypothesis().Call(t.Context(), mainHyp, nil); err != nil || res.IsError { + t.Fatalf("expected same-host main.lab.local exhaustion accepted, got err=%v res=%s", err, res.Flatten()) + } +} diff --git a/agent/hypothesis.go b/agent/hypothesis.go index 63015c7e..b160467c 100644 --- a/agent/hypothesis.go +++ b/agent/hypothesis.go @@ -73,19 +73,19 @@ func (t *ToolSet) upsertHypothesis() actool.CoreTool { if status == "closed" && strings.TrimSpace(a.CloseReason) == "" { return actool.Errorf("close_reason is required when closing a hypothesis"), nil } - if status == "closed" && isRouteExhaustionClaim(a.CloseReason+" "+a.Hypothesis) { - if gerr := missingDiscoveryCoverageError(t.ts); gerr != nil { - return actool.Errorf(gerr.Error()), nil - } - } - id := pid(a.ID) + claimContext := a.CloseReason + " " + a.Hypothesis + " " + a.Direction if id > 0 { n, err := t.ts.GetNode(id) p, ok := isHypothesisNode(n) if err != nil || !ok { return actool.Errorf(fmt.Sprintf("hypothesis #%d not found", id)), nil } + if status == "closed" && isRouteExhaustionClaim(claimContext+" "+p.Hypothesis+" "+p.Direction) { + if gerr := missingDiscoveryCoverageErrorForClaim(t.ts, claimContext+" "+p.Hypothesis+" "+p.Direction); gerr != nil { + return actool.Errorf(gerr.Error()), nil + } + } if p.Status == "closed" && status == "open" { if strings.TrimSpace(a.NewEvidence) == "" || strings.TrimSpace(a.ReopenReason) == "" { return actool.Errorf("reopening a closed hypothesis requires both new_evidence and reopen_reason"), nil @@ -108,6 +108,11 @@ func (t *ToolSet) upsertHypothesis() actool.CoreTool { return jsonResult(map[string]any{"id": id, "status": status, "hypothesis": p.Hypothesis, "close_reason": p.CloseReason}) } + if status == "closed" && isRouteExhaustionClaim(claimContext) { + if gerr := missingDiscoveryCoverageErrorForClaim(t.ts, claimContext); gerr != nil { + return actool.Errorf(gerr.Error()), nil + } + } hypText := strings.TrimSpace(a.Hypothesis) if hypText == "" { return actool.Errorf("hypothesis is required when creating a new hypothesis"), nil diff --git a/agent/tools.go b/agent/tools.go index 1afc0b41..5c6c9060 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -1653,7 +1653,7 @@ func (t *ToolSet) goalMet() actool.CoreTool { // goal_met ends the task only when no goal node is open (#124, F5). A task // without goal nodes keeps the old behavior. if isRouteExhaustionClaim(a.Reason) { - if gerr := missingDiscoveryCoverageError(t.ts); gerr != nil { + if gerr := missingDiscoveryCoverageErrorForClaim(t.ts, a.Reason); gerr != nil { return actool.Errorf(gerr.Error()), nil } } @@ -2086,7 +2086,8 @@ func (t *ToolSet) recordFact() actool.CoreTool { errs := map[string]string{} for i, it := range items { if isRouteExhaustionClaim(it.Summary + " " + it.Detail) { - if gerr := missingDiscoveryCoverageError(t.ts); gerr != nil { + claimTxt := it.Summary + " " + it.Detail + " " + it.Evidence + if gerr := missingDiscoveryCoverageErrorForClaim(t.ts, claimTxt); gerr != nil { errs[strconv.Itoa(i)] = gerr.Error() continue } diff --git a/server/target_fingerprint.go b/server/target_fingerprint.go index c02359e6..13bdbccc 100644 --- a/server/target_fingerprint.go +++ b/server/target_fingerprint.go @@ -22,7 +22,7 @@ var ( htmlCanonicalLinkRe = regexp.MustCompile(`(?is)]+rel=["']?canonical["']?[^>]+href=["']([^"'>\s]+)["']`) htmlLinkHrefRe = regexp.MustCompile(`(?is)(?:href|src|action)=["']([^"'>\s]+)["']`) rawHTTPLinkRe = regexp.MustCompile(`(?i)https?://[^\s"'<>\\)\]]+`) - fingerprintCTFConsoleRe = regexp.MustCompile(`(?i)\b(ctf|capture\s+(?:the\s+)?flag|flag\s*[1-9#]|flags\b|gablewrick|bb\s+arena|console)\b`) + fingerprintCTFConsoleRe = regexp.MustCompile(`(?i)\b(ctf|capture\s+(?:the\s+)?flag|flag\s*[1-9#]|flags\b|gablewrick|bb\s+arena|console|control\s+plane)\b`) ) func allowFingerprintExtraProbes(goal, desc string) bool { @@ -239,9 +239,20 @@ func (s *Server) FingerprintTarget(ctx context.Context, t *Task, goalURL string) trimmedBody := strings.TrimSpace(bodyStr) isJSON := strings.Contains(strings.ToLower(ct), "json") || strings.HasPrefix(trimmedBody, "{") || strings.HasPrefix(trimmedBody, "[") goalLower := strings.ToLower(t.Goal + " " + t.Description) + anyConsolePath := false + for _, exists := range probeExists { + if exists { + anyConsolePath = true + break + } + } var warnings []string - if isJSON && strings.Contains(goalLower, "console") { - warnings = append(warnings, fmt.Sprintf("root %s returned JSON (%d) while the task goal mentions console — verify whether the web console is on another host or path", sanitizedURL, resp.StatusCode)) + if isJSON && fingerprintCTFConsoleRe.MatchString(goalLower) { + if len(probeExists) > 0 && !anyConsolePath { + warnings = append(warnings, fmt.Sprintf("root %s returned JSON (%d) and /login, /signup, /app, /docs are all missing: possible secondary/service vhost; verify the main instance URL", sanitizedURL, resp.StatusCode)) + } else if strings.Contains(goalLower, "console") { + warnings = append(warnings, fmt.Sprintf("root %s returned JSON (%d) while the task goal mentions console — verify whether the web console is on another host or path", sanitizedURL, resp.StatusCode)) + } } if canonicalHost != "" { warnings = append(warnings, fmt.Sprintf("page references canonical/alternate host %s (task target host is %s) — verify vhost alignment", canonicalHost, rootHost)) diff --git a/server/target_fingerprint_test.go b/server/target_fingerprint_test.go index c95f105c..5e3a5b91 100644 --- a/server/target_fingerprint_test.go +++ b/server/target_fingerprint_test.go @@ -105,6 +105,23 @@ func TestTargetFingerprintFactAndWarningsTableDriven(t *testing.T) { wantProbes: map[string]bool{"/login": false, "/signup": true, "/app": true, "/docs": false}, wantNoCrossHit: true, }, + { + name: "ctf_estate_control_plane_json_root_all_probes_404_warns_secondary_vhost", + goal: "Capture 4 flags in order against Estate control plane on ", + handler: func(requested *[]string, seenCreds *bool) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *requested = append(*requested, r.URL.Path) + if r.URL.Path == "/" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"service":"gablewrick-estate-edge","status":"ok"}`)) + return + } + w.WriteHeader(http.StatusNotFound) + }) + }, + wantWarnings: []string{"possible secondary/service vhost; verify the main instance URL"}, + wantProbes: map[string]bool{"/login": false, "/signup": false, "/app": false, "/docs": false}, + }, } m, err := NewManager(t.TempDir(), "")