gapscan 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gapscan/_dist.py +6 -0
- gapscan/agent/__init__.py +0 -0
- gapscan/agent/agent.py +199 -0
- gapscan/agent/checklists.json +305 -0
- gapscan/agent/checklists.py +56 -0
- gapscan/agent/grounding.py +57 -0
- gapscan/agent/grouping.py +102 -0
- gapscan/agent/investigate.py +295 -0
- gapscan/agent/review.py +184 -0
- gapscan/agent/rules.py +223 -0
- gapscan/agent/summarize.py +106 -0
- gapscan/agent/tools.py +480 -0
- gapscan/agent/triage.py +367 -0
- gapscan/autofix.py +226 -0
- gapscan/ci.py +140 -0
- gapscan/cli.py +1459 -0
- gapscan/compare.py +49 -0
- gapscan/config.py +336 -0
- gapscan/context/__init__.py +0 -0
- gapscan/context/budget.py +85 -0
- gapscan/context/callgraph.py +205 -0
- gapscan/context/constfold.py +387 -0
- gapscan/context/extract.py +163 -0
- gapscan/context/flow.py +818 -0
- gapscan/context/injection.py +48 -0
- gapscan/context/sources.py +44 -0
- gapscan/context/treesitter.py +331 -0
- gapscan/context/variants.py +242 -0
- gapscan/controls.py +22 -0
- gapscan/core/__init__.py +2 -0
- gapscan/core/interfaces.py +169 -0
- gapscan/core/models.py +497 -0
- gapscan/core/version.py +3 -0
- gapscan/depfix.py +255 -0
- gapscan/desktop.py +113 -0
- gapscan/diffscan.py +185 -0
- gapscan/doctor.py +142 -0
- gapscan/enrich.py +66 -0
- gapscan/evaluation/__init__.py +0 -0
- gapscan/evaluation/benchmark.py +118 -0
- gapscan/evaluation/labels.py +97 -0
- gapscan/evaluation/local.py +163 -0
- gapscan/evaluation/metrics.py +221 -0
- gapscan/evaluation/runner.py +331 -0
- gapscan/evaluation/targets.py +72 -0
- gapscan/fingerprint.py +74 -0
- gapscan/flywheel.py +127 -0
- gapscan/kb/__init__.py +98 -0
- gapscan/kb/embed.py +68 -0
- gapscan/kb/index.py +163 -0
- gapscan/kb/ingest.py +321 -0
- gapscan/kb/references.py +70 -0
- gapscan/llm/__init__.py +0 -0
- gapscan/llm/bench.py +97 -0
- gapscan/llm/cache.py +68 -0
- gapscan/llm/client.py +187 -0
- gapscan/llm/prompts/autofix_v1.j2 +18 -0
- gapscan/llm/prompts/investigate_v1.j2 +42 -0
- gapscan/llm/prompts/investigate_v2.j2 +44 -0
- gapscan/llm/prompts/investigate_v3.j2 +47 -0
- gapscan/llm/prompts/investigate_v4.j2 +47 -0
- gapscan/llm/prompts/summary_v1.j2 +17 -0
- gapscan/llm/prompts/triage_agent_v1.j2 +34 -0
- gapscan/llm/prompts/triage_agent_v2.j2 +35 -0
- gapscan/llm/prompts/triage_agent_v3.j2 +38 -0
- gapscan/llm/prompts/triage_agent_v4.j2 +39 -0
- gapscan/llm/prompts/triage_agent_v5.j2 +40 -0
- gapscan/llm/prompts/triage_bench_v2.j2 +16 -0
- gapscan/llm/prompts/triage_v1.j2 +31 -0
- gapscan/llm/prompts/triage_v2.j2 +32 -0
- gapscan/llm/prompts/triage_v3.j2 +35 -0
- gapscan/llm/prompts/triage_v4.j2 +36 -0
- gapscan/llm/prompts/triage_v5.j2 +37 -0
- gapscan/llm/prompts.py +31 -0
- gapscan/llm/structured.py +103 -0
- gapscan/malware.py +207 -0
- gapscan/manifests.py +291 -0
- gapscan/mcp_server.py +179 -0
- gapscan/memory.py +164 -0
- gapscan/models.py +68 -0
- gapscan/normalize.py +364 -0
- gapscan/notify.py +59 -0
- gapscan/offline/__init__.py +0 -0
- gapscan/offline/bundle.py +313 -0
- gapscan/offline/fetch.py +386 -0
- gapscan/offline/refresh.py +103 -0
- gapscan/offline/update.py +263 -0
- gapscan/offline/versions.py +125 -0
- gapscan/owasp/__init__.py +0 -0
- gapscan/owasp/asvs.py +51 -0
- gapscan/owasp/build.py +179 -0
- gapscan/owasp/classify.py +53 -0
- gapscan/owasp/expected_editions.json +8 -0
- gapscan/owasp/mappings/.gitkeep +0 -0
- gapscan/owasp/mappings/NOTICE.md +24 -0
- gapscan/owasp/mappings/asvs_requirements.csv +347 -0
- gapscan/owasp/mappings/cwe_to_asvs.csv +2048 -0
- gapscan/owasp/mappings/cwe_to_top10.csv +250 -0
- gapscan/owasp/mappings/masvs_controls.csv +25 -0
- gapscan/owasp/mappings/versions.json +26 -0
- gapscan/owasp/packs.py +151 -0
- gapscan/paths.py +63 -0
- gapscan/pipeline.py +73 -0
- gapscan/policy.py +100 -0
- gapscan/pullrequest.py +176 -0
- gapscan/reach_hints.toml +40 -0
- gapscan/reachability.py +139 -0
- gapscan/redact.py +62 -0
- gapscan/registry.py +322 -0
- gapscan/report/__init__.py +0 -0
- gapscan/report/assets.py +104 -0
- gapscan/report/asvs.py +59 -0
- gapscan/report/build.py +452 -0
- gapscan/report/coverage.py +63 -0
- gapscan/report/dashboard.py +35 -0
- gapscan/report/decisions.py +40 -0
- gapscan/report/exports/__init__.py +35 -0
- gapscan/report/exports/csvs.py +48 -0
- gapscan/report/exports/markdown.py +67 -0
- gapscan/report/exports/pdf.py +68 -0
- gapscan/report/exports/sarif.py +88 -0
- gapscan/report/hotspots.py +63 -0
- gapscan/report/owasp_info.py +41 -0
- gapscan/report/risk.py +105 -0
- gapscan/report/sbom.py +51 -0
- gapscan/report/schema.py +345 -0
- gapscan/report/service.py +47 -0
- gapscan/report/templates/dashboard.html +416 -0
- gapscan/rules/rule_controls.csv +188 -0
- gapscan/rules/semgrep/csharp/csharp.yaml +866 -0
- gapscan/rules/semgrep/dart/flutter-more.yaml +184 -0
- gapscan/rules/semgrep/dart/flutter.yaml +149 -0
- gapscan/rules/semgrep/go/go.yaml +730 -0
- gapscan/rules/semgrep/java/android.yaml +259 -0
- gapscan/rules/semgrep/java/java.yaml +1424 -0
- gapscan/rules/semgrep/javascript/javascript.yaml +947 -0
- gapscan/rules/semgrep/kotlin/android-apps.yaml +188 -0
- gapscan/rules/semgrep/kotlin/android-crypto.yaml +170 -0
- gapscan/rules/semgrep/kotlin/android-more.yaml +275 -0
- gapscan/rules/semgrep/kotlin/android-network.yaml +118 -0
- gapscan/rules/semgrep/kotlin/android-platform.yaml +255 -0
- gapscan/rules/semgrep/kotlin/android.yaml +260 -0
- gapscan/rules/semgrep/kotlin/gradle.yaml +48 -0
- gapscan/rules/semgrep/kotlin/manifest.yaml +171 -0
- gapscan/rules/semgrep/kotlin/server.yaml +663 -0
- gapscan/rules/semgrep/php/php.yaml +917 -0
- gapscan/rules/semgrep/python/python.yaml +2763 -0
- gapscan/rules/semgrep/swift/ios-more.yaml +274 -0
- gapscan/rules/semgrep/swift/ios-platform.yaml +179 -0
- gapscan/rules/semgrep/swift/ios-storage-crypto.yaml +172 -0
- gapscan/rules/semgrep/swift/ios.yaml +170 -0
- gapscan/rules/semgrep/swift/plist.yaml +96 -0
- gapscan/rules/semgrep/swift/vapor.yaml +217 -0
- gapscan/runtime/__init__.py +3 -0
- gapscan/runtime/download.py +166 -0
- gapscan/runtime/hardware.py +101 -0
- gapscan/runtime/manager.py +426 -0
- gapscan/runtime/manifest.json +2880 -0
- gapscan/runtime/manifest.py +106 -0
- gapscan/runtime/ollama.py +51 -0
- gapscan/runtime/python-tools.in +5 -0
- gapscan/runtime/server.py +104 -0
- gapscan/runtime/tools.py +321 -0
- gapscan/sample_project/Dockerfile +5 -0
- gapscan/sample_project/README.md +4 -0
- gapscan/sample_project/app.py.sample +45 -0
- gapscan/sample_project/requirements.txt +3 -0
- gapscan/sample_project/static/app.js +5 -0
- gapscan/scanners/__init__.py +76 -0
- gapscan/scanners/bandit.py +83 -0
- gapscan/scanners/base.py +162 -0
- gapscan/scanners/checkov.py +99 -0
- gapscan/scanners/gitleaks.py +70 -0
- gapscan/scanners/imports.py +310 -0
- gapscan/scanners/osv.py +225 -0
- gapscan/scanners/sarif.py +121 -0
- gapscan/scanners/semgrep.py +119 -0
- gapscan/scanners/trivy.py +157 -0
- gapscan/scm.py +102 -0
- gapscan/secret_facts.py +203 -0
- gapscan/security_pack.py +181 -0
- gapscan/server/__init__.py +40 -0
- gapscan/server/app.py +998 -0
- gapscan/server/db.py +420 -0
- gapscan/server/health.py +116 -0
- gapscan/server/jobs.py +543 -0
- gapscan/server/plan.py +139 -0
- gapscan/server/sample.py +24 -0
- gapscan/server/security.py +116 -0
- gapscan/server/setup.py +112 -0
- gapscan/server/tasks.py +81 -0
- gapscan/server/templates/manager.html +405 -0
- gapscan/server/watch.py +55 -0
- gapscan/server/workspace.py +151 -0
- gapscan/services.py +455 -0
- gapscan/signing.py +141 -0
- gapscan/stages.py +129 -0
- gapscan/store/__init__.py +2 -0
- gapscan/store/raw.py +81 -0
- gapscan/store/sql.py +205 -0
- gapscan/taint/__init__.py +0 -0
- gapscan/taint/bench.py +128 -0
- gapscan/taint/constfold.py +249 -0
- gapscan/taint/engine.py +1583 -0
- gapscan/taint/models/java-servlet.toml +7 -0
- gapscan/taint/models/java-spring.toml +11 -0
- gapscan/taint/models/java-struts2.toml +10 -0
- gapscan/taint/models/java.toml +120 -0
- gapscan/taint/models/javascript-express.toml +7 -0
- gapscan/taint/models/javascript-nestjs.toml +16 -0
- gapscan/taint/models/javascript.toml +111 -0
- gapscan/taint/models/python-aiohttp.toml +7 -0
- gapscan/taint/models/python-django.toml +28 -0
- gapscan/taint/models/python-fastapi.toml +10 -0
- gapscan/taint/models/python-flask.toml +35 -0
- gapscan/taint/models/python.toml +135 -0
- gapscan/taint/scanner.py +56 -0
- gapscan/taint/specs.py +185 -0
- gapscan/typosquat_names.toml +26 -0
- gapscan/versions.py +10 -0
- gapscan/watch.py +261 -0
- gapscan-1.1.0.dist-info/METADATA +431 -0
- gapscan-1.1.0.dist-info/RECORD +226 -0
- gapscan-1.1.0.dist-info/WHEEL +4 -0
- gapscan-1.1.0.dist-info/entry_points.txt +5 -0
- gapscan-1.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Root-cause grouping for the deep dive.
|
|
2
|
+
|
|
3
|
+
Several scanners (and several rules of one scanner) often report the same bug: five rules flag
|
|
4
|
+
one string-built SQL query. Investigating each separately wastes model time and produces five
|
|
5
|
+
near-identical write-ups. Findings are grouped when they describe the same weakness at the same
|
|
6
|
+
place; the group is investigated once and the result is shown on every member.
|
|
7
|
+
|
|
8
|
+
Same weakness is decided from the rule text first (scanner CWEs are noisy: SQL injection rules
|
|
9
|
+
carry CWE-89, CWE-704 or CWE-915), then from the CWEs, then from the rule id. Lines on one line
|
|
10
|
+
can still be different bugs (command injection and XSS at the same `return`), so place alone is
|
|
11
|
+
never enough.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
from ..models import Category, Finding
|
|
20
|
+
|
|
21
|
+
# (weakness class, pattern over rule id / title / message), first match wins.
|
|
22
|
+
_KINDS = [
|
|
23
|
+
("sql-injection", re.compile(r"sql", re.I)),
|
|
24
|
+
("xss", re.compile(r"xss|cross.site.script|html response", re.I)),
|
|
25
|
+
# Not plain "command": config rules say things like "add a USER command".
|
|
26
|
+
(
|
|
27
|
+
"command-injection",
|
|
28
|
+
re.compile(r"subprocess|command.injection|shell.true|os\.system|popen", re.I),
|
|
29
|
+
),
|
|
30
|
+
("deserialization", re.compile(r"deserial|pickle|marshal|yaml.load", re.I)),
|
|
31
|
+
("weak-hash", re.compile(r"md5|sha-?1\b|weak.hash|insecure.hash", re.I)),
|
|
32
|
+
("container-root", re.compile(r"missing-user|\broot\b|user for the container", re.I)),
|
|
33
|
+
("path-traversal", re.compile(r"path.traversal|directory.traversal", re.I)),
|
|
34
|
+
("ssrf", re.compile(r"ssrf|server.side.request", re.I)),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def weakness_class(f: Finding) -> str:
|
|
39
|
+
for text in (f.rule_id, f"{f.title} {f.message}"):
|
|
40
|
+
for name, pattern in _KINDS:
|
|
41
|
+
if pattern.search(text):
|
|
42
|
+
return name
|
|
43
|
+
return ",".join(sorted(f.cwe)) or f.rule_id
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Findings about an import rather than a call (Bandit B4xx: "consider the security implications
|
|
47
|
+
# of the subprocess module"): they belong with the calls of that module in the same file.
|
|
48
|
+
_IMPORT_LEVEL = re.compile(r"\bimport\b|\bmodule\b", re.I)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _import_level(f: Finding) -> bool:
|
|
52
|
+
return bool(re.fullmatch(r"B4\d\d", f.rule_id)) or bool(_IMPORT_LEVEL.search(f.title))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _same_root_cause(a: Finding, b: Finding) -> bool:
|
|
56
|
+
if a.category != b.category:
|
|
57
|
+
return False
|
|
58
|
+
if a.category == Category.DEPENDENCY: # one fix: upgrade that package version
|
|
59
|
+
return (
|
|
60
|
+
bool(a.package)
|
|
61
|
+
and (a.package or "").lower() == (b.package or "").lower()
|
|
62
|
+
and (a.version == b.version)
|
|
63
|
+
)
|
|
64
|
+
if a.file != b.file or a.file is None:
|
|
65
|
+
return False
|
|
66
|
+
if a.category == Category.SECRET:
|
|
67
|
+
return a.start_line == b.start_line
|
|
68
|
+
if weakness_class(a) != weakness_class(b):
|
|
69
|
+
return False
|
|
70
|
+
if a.start_line is None or b.start_line is None: # file-level result (e.g. a Dockerfile rule)
|
|
71
|
+
return True
|
|
72
|
+
if _import_level(a) or _import_level(b): # the import enables every use in the file
|
|
73
|
+
return True
|
|
74
|
+
a_end, b_end = a.end_line or a.start_line, b.end_line or b.start_line
|
|
75
|
+
return a.start_line <= b_end and b.start_line <= a_end
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def group_findings(findings: list[Finding]) -> list[list[Finding]]:
|
|
79
|
+
"""Connected groups of findings with the same root cause, each sorted by priority (the
|
|
80
|
+
first member is the one investigated); groups keep the order of their first member."""
|
|
81
|
+
parent = list(range(len(findings)))
|
|
82
|
+
|
|
83
|
+
def root(i: int) -> int:
|
|
84
|
+
while parent[i] != i:
|
|
85
|
+
parent[i] = parent[parent[i]]
|
|
86
|
+
i = parent[i]
|
|
87
|
+
return i
|
|
88
|
+
|
|
89
|
+
for i in range(len(findings)):
|
|
90
|
+
for j in range(i + 1, len(findings)):
|
|
91
|
+
if _same_root_cause(findings[i], findings[j]):
|
|
92
|
+
parent[root(j)] = root(i)
|
|
93
|
+
groups: dict[int, list[Finding]] = {}
|
|
94
|
+
for i, f in enumerate(findings):
|
|
95
|
+
groups.setdefault(root(i), []).append(f)
|
|
96
|
+
return [sorted(g, key=lambda f: (-f.priority, f.id)) for g in groups.values()]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def group_id(members: list[Finding]) -> str:
|
|
100
|
+
"""Stable id from the member finding ids (which are themselves stable fingerprints)."""
|
|
101
|
+
key = "|".join(sorted(f.id for f in members))
|
|
102
|
+
return hashlib.sha256(key.encode()).hexdigest()[:16]
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Deep-dive investigation of one confirmed finding.
|
|
2
|
+
|
|
3
|
+
Triage decides whether a finding is real. This pass explains it the way a manual audit would:
|
|
4
|
+
what protection exists and where, which builds are affected, where else the same root cause
|
|
5
|
+
appears, what is missing, how to fix it in order, and how to verify the fix.
|
|
6
|
+
|
|
7
|
+
The model writes the prose; Python decides what may be shown as fact (hard rule #5):
|
|
8
|
+
- a cited `file:line` is kept only if those lines were shown to the model, either in the
|
|
9
|
+
finding's own context or in a tool result;
|
|
10
|
+
- a `missing` claim is kept only if it names a `search_repo` text whose search covered every
|
|
11
|
+
file and found nothing;
|
|
12
|
+
- a `related` location must be somewhere else: refs inside the investigated lines are dropped;
|
|
13
|
+
- everything else is dropped and listed in `Investigation.dropped`.
|
|
14
|
+
|
|
15
|
+
Same safety properties as the triage loop (agent.py): read-only allowlisted tools confined to
|
|
16
|
+
the target, tool output wrapped as untrusted data, schema-validated steps with repair retries.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import re
|
|
23
|
+
from typing import Literal
|
|
24
|
+
|
|
25
|
+
from pydantic import BaseModel, Field, model_validator
|
|
26
|
+
|
|
27
|
+
from ..context.injection import find_injection_lines, warning_for
|
|
28
|
+
from ..core.interfaces import LLMError, LLMProvider
|
|
29
|
+
from ..llm.cache import ResponseCache
|
|
30
|
+
from ..llm.prompts import latest_version, render_prompt
|
|
31
|
+
from ..llm.structured import StructuredOutputError, structured_chat
|
|
32
|
+
from ..models import (
|
|
33
|
+
CodeContext,
|
|
34
|
+
EvidenceEffect,
|
|
35
|
+
Finding,
|
|
36
|
+
Investigation,
|
|
37
|
+
InvestigationAnswer,
|
|
38
|
+
ToolCallRecord,
|
|
39
|
+
Verdict,
|
|
40
|
+
)
|
|
41
|
+
from .agent import _tool_message
|
|
42
|
+
from .checklists import checklist_for, render_checklist
|
|
43
|
+
from .grounding import _REF, Seen, _norm, seen_from_context
|
|
44
|
+
from .grouping import group_id, weakness_class
|
|
45
|
+
from .tools import DEEP_TOOL_DESCRIPTIONS, ToolBox, manifest_lines
|
|
46
|
+
from .triage import finding_text, neutralize_delimiters
|
|
47
|
+
|
|
48
|
+
PROMPT_NAME = "investigate"
|
|
49
|
+
DEFAULT_MAX_TOOL_CALLS = 12
|
|
50
|
+
|
|
51
|
+
DeepTool = Literal[
|
|
52
|
+
"read_code", "find_callers", "find_definition", "find_imports", "lookup_cwe", "search_kb",
|
|
53
|
+
"search_repo", "list_files", "build_variants", "read_config",
|
|
54
|
+
] # fmt: skip
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class DeepStep(BaseModel):
|
|
58
|
+
"""One model turn in the deep dive: a tool call or the final investigation."""
|
|
59
|
+
|
|
60
|
+
action: Literal["tool", "final"]
|
|
61
|
+
tool: DeepTool | None = None
|
|
62
|
+
args: dict[str, str | int] = Field(default_factory=dict)
|
|
63
|
+
answer: InvestigationAnswer | None = None
|
|
64
|
+
|
|
65
|
+
@model_validator(mode="after")
|
|
66
|
+
def _consistent(self) -> DeepStep:
|
|
67
|
+
if self.action == "tool" and (self.tool is None or self.answer is not None):
|
|
68
|
+
raise ValueError("a tool step needs `tool` and must not include `answer`")
|
|
69
|
+
if self.action == "final" and (self.answer is None or self.tool is not None):
|
|
70
|
+
raise ValueError("a final step needs `answer` and must not include `tool`")
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# --- grounding ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
# A search for a plain English word ("validation") proves nothing about code; absence claims
|
|
77
|
+
# must rest on code-shaped text: punctuation, an uppercase letter or a digit.
|
|
78
|
+
_CODE_SHAPED = re.compile(r"[._()=:<>/\-\[\]{}\"'$#@,;]|[A-Z]|\d")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_code_shaped(text: str) -> bool:
|
|
82
|
+
return bool(_CODE_SHAPED.search(text.strip()))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _overlaps(ref: str, own: list[tuple[str, int, int]]) -> bool:
|
|
86
|
+
m = _REF.match(ref)
|
|
87
|
+
if m is None:
|
|
88
|
+
return False
|
|
89
|
+
lo, hi = int(m["lo"]), int(m["hi"] or m["lo"])
|
|
90
|
+
return any(_norm(m["file"]) == _norm(f) and lo <= b and a <= hi for f, a, b in own)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def own_lines(members: list[Finding]) -> list[tuple[str, int, int]]:
|
|
94
|
+
"""The lines the investigated group itself is about."""
|
|
95
|
+
return [(f.file, f.start_line, f.end_line or f.start_line)
|
|
96
|
+
for f in members if f.file and f.start_line] # fmt: skip
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def other_issue_lines(members: list[Finding], known: list[Finding]) -> list[tuple[str, int, int]]:
|
|
100
|
+
"""Lines of scan findings that are a different weakness from the investigated group (and
|
|
101
|
+
not also flagged for the same weakness): a "related" ref there is another issue."""
|
|
102
|
+
kinds = {weakness_class(m) for m in members}
|
|
103
|
+
same = own_lines([f for f in known if weakness_class(f) in kinds])
|
|
104
|
+
other = own_lines([f for f in known if weakness_class(f) not in kinds])
|
|
105
|
+
return [o for o in other if not any(o[0] == s[0] and o[1] <= s[2] and s[1] <= o[2]
|
|
106
|
+
for s in same)] # fmt: skip
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def ground(
|
|
110
|
+
answer: InvestigationAnswer,
|
|
111
|
+
seen: Seen,
|
|
112
|
+
own: list[tuple[str, int, int]] | None = None,
|
|
113
|
+
other_issues: list[tuple[str, int, int]] | None = None,
|
|
114
|
+
vetted: set[str] | None = None,
|
|
115
|
+
) -> tuple[InvestigationAnswer, list[str]]:
|
|
116
|
+
"""Keep only items whose refs were shown to the model; return the reasons for the rest."""
|
|
117
|
+
dropped: list[str] = []
|
|
118
|
+
evidence = []
|
|
119
|
+
for e in answer.evidence:
|
|
120
|
+
if e.effect == EvidenceEffect.MISSING:
|
|
121
|
+
key = (e.search or "").strip().lower()
|
|
122
|
+
plain = not is_code_shaped(e.search or "") and key not in (vetted or set())
|
|
123
|
+
if key in seen.empty_searches and plain:
|
|
124
|
+
dropped.append(f"evidence (missing): {e.search!r} is a plain word, not code, so "
|
|
125
|
+
f"an empty search for it does not show {e.claim!r}") # fmt: skip
|
|
126
|
+
elif key in seen.empty_searches:
|
|
127
|
+
update: dict[str, str | None] = {"search_scope": seen.empty_searches[key]}
|
|
128
|
+
if e.ref and not seen.covers(e.ref):
|
|
129
|
+
update["ref"] = None # the claim stands on the search
|
|
130
|
+
evidence.append(e.model_copy(update=update))
|
|
131
|
+
else:
|
|
132
|
+
dropped.append(f"evidence (missing): no complete empty search backs {e.claim!r}")
|
|
133
|
+
elif e.ref and seen.covers(e.ref):
|
|
134
|
+
# only absence claims rest on a search; never show an unbacked "found nothing"
|
|
135
|
+
evidence.append(e.model_copy(update={"search": None, "search_scope": None}))
|
|
136
|
+
else:
|
|
137
|
+
dropped.append(f"evidence: {e.ref or 'no ref'} was not shown for {e.claim!r}")
|
|
138
|
+
scope = []
|
|
139
|
+
for s in answer.scope:
|
|
140
|
+
if seen.covers(s.ref):
|
|
141
|
+
scope.append(s)
|
|
142
|
+
else:
|
|
143
|
+
dropped.append(f"scope: {s.ref} was not shown for {s.where!r}")
|
|
144
|
+
related = []
|
|
145
|
+
for r in answer.related:
|
|
146
|
+
if not seen.covers(r.ref):
|
|
147
|
+
dropped.append(f"related: {r.ref} was not shown")
|
|
148
|
+
elif _overlaps(r.ref, own or []):
|
|
149
|
+
dropped.append(f"related: {r.ref} is the finding itself, not another location")
|
|
150
|
+
elif _overlaps(r.ref, other_issues or []):
|
|
151
|
+
dropped.append(f"related: {r.ref} is a different kind of issue found by the scan")
|
|
152
|
+
else:
|
|
153
|
+
related.append(r)
|
|
154
|
+
kept = answer.model_copy(update={"evidence": evidence, "scope": scope, "related": related})
|
|
155
|
+
return kept, dropped
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# --- loop -------------------------------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _triage_text(verdict: Verdict) -> str:
|
|
162
|
+
lines = [f"TRIAGE VERDICT: {verdict.verdict.value} (confidence {verdict.confidence:.2f})"]
|
|
163
|
+
if verdict.reasoning:
|
|
164
|
+
lines.append(f"TRIAGE REASONING: {verdict.reasoning}")
|
|
165
|
+
if verdict.exploit_scenario:
|
|
166
|
+
lines.append(f"EXPLOIT SCENARIO: {verdict.exploit_scenario}")
|
|
167
|
+
for note in verdict.policy_notes: # facts GapScan computed (e.g. which builds ship a secret)
|
|
168
|
+
lines.append(f"GAPSCAN FACT: {note}")
|
|
169
|
+
return neutralize_delimiters("\n".join(lines))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _group_text(finding: Finding, members: list[Finding]) -> str:
|
|
173
|
+
others = [m for m in members if m.id != finding.id]
|
|
174
|
+
if not others:
|
|
175
|
+
return ""
|
|
176
|
+
lines = ["OTHER SCANNER RESULTS FOR THIS SAME ISSUE (one investigation covers them all):"]
|
|
177
|
+
for m in others[:10]:
|
|
178
|
+
where = f"{m.file}:{m.start_line}" if m.file and m.start_line else (m.file or m.package)
|
|
179
|
+
lines.append(f"- {', '.join(m.sources)} {m.rule_id} at {where}: {m.title[:120]}")
|
|
180
|
+
return neutralize_delimiters("\n".join(lines))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def investigate(
|
|
184
|
+
client: LLMProvider,
|
|
185
|
+
finding: Finding,
|
|
186
|
+
context: CodeContext | None,
|
|
187
|
+
verdict: Verdict,
|
|
188
|
+
toolbox: ToolBox,
|
|
189
|
+
*,
|
|
190
|
+
members: list[Finding] | None = None,
|
|
191
|
+
known: list[Finding] | None = None,
|
|
192
|
+
max_tool_calls: int = DEFAULT_MAX_TOOL_CALLS,
|
|
193
|
+
cache: ResponseCache | None = None,
|
|
194
|
+
max_tokens: int = 2000,
|
|
195
|
+
) -> Investigation:
|
|
196
|
+
"""Investigate `finding` (the first member of its root-cause group, see agent/grouping.py);
|
|
197
|
+
`members` are every finding the result will be shown on, including `finding`; `known` are
|
|
198
|
+
all scan findings, used to reject "related" refs that point at a different issue."""
|
|
199
|
+
members = members or [finding]
|
|
200
|
+
version = latest_version(PROMPT_NAME)
|
|
201
|
+
suspected = list(context.injection_lines) if context else []
|
|
202
|
+
seen = seen_from_context(context)
|
|
203
|
+
text = finding_text(finding, context)
|
|
204
|
+
if finding.package and finding.file: # dependency: show where the package is declared
|
|
205
|
+
decl = manifest_lines(toolbox, finding.file, finding.package)
|
|
206
|
+
if decl.ok and decl.seen:
|
|
207
|
+
text += f"\n\nWHERE {finding.file} DECLARES {finding.package}:\n"
|
|
208
|
+
text += neutralize_delimiters(decl.text)
|
|
209
|
+
for file, lo, hi in decl.seen:
|
|
210
|
+
seen.add(file, lo, hi)
|
|
211
|
+
if group := _group_text(finding, members):
|
|
212
|
+
text += "\n\n" + group
|
|
213
|
+
entry = checklist_for(members)
|
|
214
|
+
prompt = render_prompt(
|
|
215
|
+
version,
|
|
216
|
+
checklist=render_checklist(entry) if entry else "",
|
|
217
|
+
finding_text=text,
|
|
218
|
+
triage_text=_triage_text(verdict),
|
|
219
|
+
warning=warning_for(suspected) if suspected else "",
|
|
220
|
+
max_tool_calls=max_tool_calls,
|
|
221
|
+
tool_lines=list(DEEP_TOOL_DESCRIPTIONS.values()),
|
|
222
|
+
)
|
|
223
|
+
messages: list[dict[str, str]] = [{"role": "user", "content": prompt}]
|
|
224
|
+
records: list[ToolCallRecord] = []
|
|
225
|
+
seen_calls: set[str] = set()
|
|
226
|
+
attempts, tokens, seconds, cached = 0, 0, 0.0, True
|
|
227
|
+
answer: InvestigationAnswer | None = None
|
|
228
|
+
|
|
229
|
+
def failed(error: str) -> Investigation:
|
|
230
|
+
return Investigation(
|
|
231
|
+
finding_id=finding.id, group_id=group_id(members), covers=[m.id for m in members],
|
|
232
|
+
failed=True, error=error[:300], prompt_version=version,
|
|
233
|
+
model=client.model, attempts=attempts, tool_calls=records,
|
|
234
|
+
injection_suspected=bool(suspected), tokens=tokens, seconds=round(seconds, 2),
|
|
235
|
+
) # fmt: skip
|
|
236
|
+
|
|
237
|
+
try:
|
|
238
|
+
while answer is None:
|
|
239
|
+
forced = len(records) >= max_tool_calls
|
|
240
|
+
if forced:
|
|
241
|
+
messages.append({"role": "user", "content": (
|
|
242
|
+
"Tool budget used up. Give your final investigation now as the JSON object "
|
|
243
|
+
'with "action": "final".')}) # fmt: skip
|
|
244
|
+
res = structured_chat(
|
|
245
|
+
client, messages, DeepStep, max_tokens=max_tokens, cache=cache,
|
|
246
|
+
prompt_version=version,
|
|
247
|
+
) # fmt: skip
|
|
248
|
+
attempts += res.attempts
|
|
249
|
+
tokens += res.prompt_tokens + res.completion_tokens
|
|
250
|
+
seconds += res.duration_s
|
|
251
|
+
cached = cached and res.cached
|
|
252
|
+
step = res.value
|
|
253
|
+
if step.action == "final" or forced:
|
|
254
|
+
if step.answer is None:
|
|
255
|
+
raise StructuredOutputError("no final answer after tool budget", attempts, "")
|
|
256
|
+
answer = step.answer
|
|
257
|
+
break
|
|
258
|
+
assert step.tool is not None # guaranteed by the validator
|
|
259
|
+
call_key = json.dumps([step.tool, step.args], sort_keys=True)
|
|
260
|
+
if call_key in seen_calls:
|
|
261
|
+
text, ok, ref, outcome = (
|
|
262
|
+
"You already made this exact call; use the earlier result.", False, None, None,
|
|
263
|
+
) # fmt: skip
|
|
264
|
+
else:
|
|
265
|
+
seen_calls.add(call_key)
|
|
266
|
+
tr = toolbox.execute(step.tool, step.args)
|
|
267
|
+
text, ok, ref, outcome = tr.text, tr.ok, tr.evidence_ref, tr.outcome
|
|
268
|
+
for file, lo, hi in tr.seen:
|
|
269
|
+
seen.add(file, lo, hi)
|
|
270
|
+
if step.tool == "search_repo" and outcome == "no_matches":
|
|
271
|
+
key = str(step.args.get("text", "")).strip().lower()
|
|
272
|
+
# a whole-project search outranks a narrower one for the same text
|
|
273
|
+
if seen.empty_searches.get(key) != "":
|
|
274
|
+
seen.empty_searches[key] = tr.scope
|
|
275
|
+
records.append(ToolCallRecord(tool=step.tool, args=dict(step.args), ok=ok,
|
|
276
|
+
evidence_ref=ref, outcome=outcome)) # fmt: skip
|
|
277
|
+
suspect = bool(find_injection_lines(list(enumerate(text.splitlines()))))
|
|
278
|
+
suspected = suspected or ([0] if suspect else [])
|
|
279
|
+
messages += [
|
|
280
|
+
{"role": "assistant", "content": step.model_dump_json(exclude_none=True)},
|
|
281
|
+
{"role": "user", "content": _tool_message(step.tool, step.args, ok, text, suspect)},
|
|
282
|
+
]
|
|
283
|
+
except StructuredOutputError as exc:
|
|
284
|
+
return failed(str(exc))
|
|
285
|
+
except LLMError as exc:
|
|
286
|
+
return failed(str(exc))
|
|
287
|
+
other = other_issue_lines(members, known or [])
|
|
288
|
+
vetted = {s.strip().lower() for c in (entry or {}).get("controls", []) for s in c["signals"]}
|
|
289
|
+
kept, dropped = ground(answer, seen, own_lines(members), other, vetted)
|
|
290
|
+
return Investigation(
|
|
291
|
+
finding_id=finding.id, group_id=group_id(members), covers=[m.id for m in members],
|
|
292
|
+
answer=kept, dropped=dropped, prompt_version=version,
|
|
293
|
+
model=client.model, cached=cached, attempts=attempts, tool_calls=records,
|
|
294
|
+
injection_suspected=bool(suspected), tokens=tokens, seconds=round(seconds, 2),
|
|
295
|
+
) # fmt: skip
|
gapscan/agent/review.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""The security pack's model review: triage of the top findings, the deep dive into confirmed
|
|
2
|
+
root causes and the repository summary, with the agent's tools, rules and knowledge base.
|
|
3
|
+
|
|
4
|
+
The engine runs the review flow (`gapscan.services.review_scan`: limits, progress, what happens
|
|
5
|
+
when the deep dive fails); this module is the domain's side of it. Apps pass an `AgentSteps` on
|
|
6
|
+
the model provider they wired.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from ..config import Config
|
|
15
|
+
from ..context.extract import build_context
|
|
16
|
+
from ..core.interfaces import LLMProvider
|
|
17
|
+
from ..kb import load_kb
|
|
18
|
+
from ..llm.cache import ResponseCache
|
|
19
|
+
from ..memory import Memory, render_memory, retrieve
|
|
20
|
+
from ..models import Finding, Investigation, RepoSummary, ScanResult, Verdict, VerdictLabel
|
|
21
|
+
from ..redact import mask
|
|
22
|
+
from .agent import triage_with_tools
|
|
23
|
+
from .grouping import group_findings
|
|
24
|
+
from .investigate import investigate
|
|
25
|
+
from .rules import deterministic_verdict
|
|
26
|
+
from .summarize import summarize_repo
|
|
27
|
+
from .tools import KnowledgeBase, ToolBox, language_for_finding
|
|
28
|
+
from .triage import guard_memory_use, triage_finding, with_references
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def triage_top_findings(
|
|
32
|
+
config: Config,
|
|
33
|
+
result: ScanResult,
|
|
34
|
+
target: Path,
|
|
35
|
+
*,
|
|
36
|
+
limit: int,
|
|
37
|
+
client: LLMProvider,
|
|
38
|
+
cache: ResponseCache | None = None,
|
|
39
|
+
kb: KnowledgeBase | None = None,
|
|
40
|
+
on_verdict: Callable[[Verdict], None] | None = None,
|
|
41
|
+
memories: list[Memory] | None = None,
|
|
42
|
+
memory_provider: Callable[[Finding], list[Memory]] | None = None,
|
|
43
|
+
) -> list[Verdict]:
|
|
44
|
+
"""Triage the highest-priority findings flagged for the LLM, with tools when enabled.
|
|
45
|
+
|
|
46
|
+
`memories` are the team's notes; the most relevant ones are shown to the model for each
|
|
47
|
+
finding. `memory_provider` lets a caller choose them per finding (used by the evaluation)."""
|
|
48
|
+
if cache is None: # not `or`: an empty ResponseCache is falsy (it defines __len__)
|
|
49
|
+
cache = ResponseCache(config.data.dir / "cache" / "llm.sqlite")
|
|
50
|
+
kb = kb or load_kb(config) # None until `gapscan kb build` has been run
|
|
51
|
+
by_id = {f.id: f for f in result.findings}
|
|
52
|
+
verdicts = []
|
|
53
|
+
for f in [f for f in result.findings if f.llm_triage][:limit]:
|
|
54
|
+
ctx = build_context(f, target.resolve(), budget_tokens=config.llm.code_context_tokens)
|
|
55
|
+
rule_verdict = deterministic_verdict(f, ctx, target)
|
|
56
|
+
if rule_verdict is not None: # decided by code: no model call, no tokens
|
|
57
|
+
rule_verdict = with_references(rule_verdict, kb, f)
|
|
58
|
+
verdicts.append(rule_verdict)
|
|
59
|
+
if on_verdict:
|
|
60
|
+
on_verdict(rule_verdict)
|
|
61
|
+
continue
|
|
62
|
+
picked = memory_provider(f) if memory_provider else retrieve(memories or [], f)
|
|
63
|
+
ctx.memories = [mask(render_memory(m)) for m in picked]
|
|
64
|
+
ctx.memory_ids = [m.id for m in picked]
|
|
65
|
+
if config.agent.use_tools:
|
|
66
|
+
toolbox = ToolBox(target, ctx.language or language_for_finding(by_id[f.id]), kb)
|
|
67
|
+
v = triage_with_tools(client, by_id[f.id], ctx, toolbox, cache=cache,
|
|
68
|
+
max_tool_calls=config.agent.max_tool_calls) # fmt: skip
|
|
69
|
+
else:
|
|
70
|
+
v = triage_finding(client, by_id[f.id], ctx, cache=cache, kb=kb)
|
|
71
|
+
v = v.model_copy(update={"memories_used": ctx.memory_ids, "memory_notes": ctx.memories})
|
|
72
|
+
v = guard_memory_use(f, v, [m.kind for m in picked])
|
|
73
|
+
verdicts.append(v)
|
|
74
|
+
if on_verdict:
|
|
75
|
+
on_verdict(v)
|
|
76
|
+
return verdicts
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
DEEP_DIVE_VERDICTS = (VerdictLabel.TRUE_POSITIVE, VerdictLabel.LIKELY_TRUE_POSITIVE)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def deep_dive_groups(
|
|
83
|
+
config: Config, result: ScanResult, verdicts: list[Verdict], limit: int
|
|
84
|
+
) -> list[list[Finding]]:
|
|
85
|
+
"""Root-cause groups worth a deep dive, highest priority first, at most `limit` groups.
|
|
86
|
+
|
|
87
|
+
Members are findings judged real (true or likely true positive, by the model or a
|
|
88
|
+
deterministic rule); a group qualifies when its top member is at or above
|
|
89
|
+
`agent.deep_dive_min_priority`. The first member of each group is the one investigated."""
|
|
90
|
+
real = {v.finding_id for v in verdicts
|
|
91
|
+
if not v.triage_failed and v.verdict in DEEP_DIVE_VERDICTS} # fmt: skip
|
|
92
|
+
groups = group_findings([f for f in result.findings if f.id in real])
|
|
93
|
+
groups = [g for g in groups if g[0].priority >= config.agent.deep_dive_min_priority]
|
|
94
|
+
groups.sort(key=lambda g: (-g[0].priority, g[0].id))
|
|
95
|
+
return groups[:limit]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def deep_dive_findings(
|
|
99
|
+
config: Config,
|
|
100
|
+
result: ScanResult,
|
|
101
|
+
target: Path,
|
|
102
|
+
verdicts: list[Verdict],
|
|
103
|
+
*,
|
|
104
|
+
limit: int,
|
|
105
|
+
client: LLMProvider,
|
|
106
|
+
cache: ResponseCache | None = None,
|
|
107
|
+
kb: KnowledgeBase | None = None,
|
|
108
|
+
on_investigation: Callable[[Investigation], None] | None = None,
|
|
109
|
+
) -> list[Investigation]:
|
|
110
|
+
"""Detailed, grounded investigations, one per root-cause group of
|
|
111
|
+
confirmed findings; `Investigation.covers` lists every finding each one applies to."""
|
|
112
|
+
if cache is None: # not `or`: an empty ResponseCache is falsy (it defines __len__)
|
|
113
|
+
cache = ResponseCache(config.data.dir / "cache" / "llm.sqlite")
|
|
114
|
+
kb = kb or load_kb(config)
|
|
115
|
+
vmap = {v.finding_id: v for v in verdicts}
|
|
116
|
+
out = []
|
|
117
|
+
for members in deep_dive_groups(config, result, verdicts, limit):
|
|
118
|
+
f = members[0]
|
|
119
|
+
ctx = build_context(f, target.resolve(), budget_tokens=config.llm.code_context_tokens)
|
|
120
|
+
toolbox = ToolBox(target, ctx.language or language_for_finding(f), kb)
|
|
121
|
+
inv = investigate(client, f, ctx, vmap[f.id], toolbox, members=members,
|
|
122
|
+
known=result.findings, cache=cache,
|
|
123
|
+
max_tool_calls=config.agent.deep_dive_tool_calls) # fmt: skip
|
|
124
|
+
out.append(inv)
|
|
125
|
+
if on_investigation:
|
|
126
|
+
on_investigation(inv)
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def summarize_scan(
|
|
131
|
+
config: Config,
|
|
132
|
+
result: ScanResult,
|
|
133
|
+
verdicts: list[Verdict],
|
|
134
|
+
*,
|
|
135
|
+
client: LLMProvider,
|
|
136
|
+
cache: ResponseCache | None = None,
|
|
137
|
+
) -> RepoSummary:
|
|
138
|
+
"""Repo-level summary: Python-computed stats plus a validated model-written narrative."""
|
|
139
|
+
if cache is None: # not `or`: an empty ResponseCache is falsy (it defines __len__)
|
|
140
|
+
cache = ResponseCache(config.data.dir / "cache" / "llm.sqlite")
|
|
141
|
+
return summarize_repo(client, result, verdicts, cache=cache)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
OnVerdict = Callable[[Verdict], None]
|
|
145
|
+
OnInvestigation = Callable[[Investigation], None]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class AgentSteps:
|
|
149
|
+
"""The review steps (`gapscan.services.ReviewSteps`) on one model provider."""
|
|
150
|
+
|
|
151
|
+
def __init__(self, client: LLMProvider) -> None:
|
|
152
|
+
self.client = client
|
|
153
|
+
|
|
154
|
+
def triage(
|
|
155
|
+
self,
|
|
156
|
+
cfg: Config,
|
|
157
|
+
result: ScanResult,
|
|
158
|
+
target: Path,
|
|
159
|
+
limit: int,
|
|
160
|
+
on_verdict: OnVerdict,
|
|
161
|
+
memories: list[Memory] | None = None,
|
|
162
|
+
) -> list[Verdict]:
|
|
163
|
+
return triage_top_findings(cfg, result, target, limit=limit, client=self.client,
|
|
164
|
+
on_verdict=on_verdict, memories=memories) # fmt: skip
|
|
165
|
+
|
|
166
|
+
def deep_dive_count(
|
|
167
|
+
self, cfg: Config, result: ScanResult, verdicts: list[Verdict], limit: int
|
|
168
|
+
) -> int:
|
|
169
|
+
return len(deep_dive_groups(cfg, result, verdicts, limit))
|
|
170
|
+
|
|
171
|
+
def deep_dive(
|
|
172
|
+
self,
|
|
173
|
+
cfg: Config,
|
|
174
|
+
result: ScanResult,
|
|
175
|
+
target: Path,
|
|
176
|
+
verdicts: list[Verdict],
|
|
177
|
+
limit: int,
|
|
178
|
+
on_investigation: OnInvestigation,
|
|
179
|
+
) -> list[Investigation]:
|
|
180
|
+
return deep_dive_findings(cfg, result, target, verdicts, limit=limit, client=self.client,
|
|
181
|
+
on_investigation=on_investigation) # fmt: skip
|
|
182
|
+
|
|
183
|
+
def summarize(self, cfg: Config, result: ScanResult, verdicts: list[Verdict]) -> RepoSummary:
|
|
184
|
+
return summarize_scan(cfg, result, verdicts, client=self.client)
|