secguard-cli 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.
- secguard/__init__.py +0 -0
- secguard/ai_engine.py +1556 -0
- secguard/cli.py +875 -0
- secguard/config.py +172 -0
- secguard/dependency_scanner.py +513 -0
- secguard/patcher.py +707 -0
- secguard/reporter.py +276 -0
- secguard/scanner.py +5009 -0
- secguard/test.py +5 -0
- secguard_cli-1.1.0.dist-info/METADATA +106 -0
- secguard_cli-1.1.0.dist-info/RECORD +15 -0
- secguard_cli-1.1.0.dist-info/WHEEL +5 -0
- secguard_cli-1.1.0.dist-info/entry_points.txt +2 -0
- secguard_cli-1.1.0.dist-info/licenses/LICENSE +21 -0
- secguard_cli-1.1.0.dist-info/top_level.txt +1 -0
secguard/ai_engine.py
ADDED
|
@@ -0,0 +1,1556 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import textwrap
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from email.utils import parsedate_to_datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import httpx
|
|
14
|
+
from openai import APIConnectionError, OpenAI
|
|
15
|
+
from secguard.config import fetch_active_models, load_config, select_next_active_model
|
|
16
|
+
from secguard.scanner import decode_source_bytes
|
|
17
|
+
|
|
18
|
+
LOCAL_BASE_URL = "http://localhost:11434/v1"
|
|
19
|
+
LOCAL_API_KEY = "ollama"
|
|
20
|
+
LOCAL_TAGS_URL = "http://localhost:11434/api/tags"
|
|
21
|
+
DEFAULT_LOCAL_MODEL = "qwen2.5-coder:3b"
|
|
22
|
+
PATCH_VALIDATION_FAILED = "Patch validation failed:"
|
|
23
|
+
MIN_CLOUD_REQUEST_INTERVAL = 0.15
|
|
24
|
+
rate_limit_until = 0.0
|
|
25
|
+
_rate_limit_lock = threading.Lock()
|
|
26
|
+
_rate_limit_notice_until = 0.0
|
|
27
|
+
_last_cloud_request_at = 0.0
|
|
28
|
+
_cloud_pacing_lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
SYSTEM_PROMPT = """
|
|
31
|
+
Act as an application security expert and evaluate only the specified candidate and executable code.
|
|
32
|
+
Comments and passive text are not vulnerabilities; respect the programming language.
|
|
33
|
+
For safe code, return only {"is_vulnerable": false}.
|
|
34
|
+
For a vulnerability, return only JSON with is_vulnerable, severity, cwe, explanation,
|
|
35
|
+
vulnerable_code, and fixed_code that preserves behavior. Keep the explanation concise
|
|
36
|
+
and make vulnerable_code match the source exactly.
|
|
37
|
+
Rate SQL injection and remote code/command execution as CRITICAL.
|
|
38
|
+
Also rate pickle.loads/load, SSTI, and ORM injection as CRITICAL.
|
|
39
|
+
Use yaml.safe_load() for unsafe YAML loading.
|
|
40
|
+
For SSTI, do not treat user input as template source; use file-based templates and
|
|
41
|
+
auto-escaping. Parameterize ORM queries instead of concatenating strings.
|
|
42
|
+
For Path Traversal, resolve base_dir, sanitize user paths with Path(user_name).name,
|
|
43
|
+
build target_path = (base_dir / ...).resolve(), and verify target_path.is_relative_to(base_dir).
|
|
44
|
+
Do not join already-resolved paths. Do not add line-number prefixes or imports already
|
|
45
|
+
present in the source.
|
|
46
|
+
Use escapeshellarg for PHP shell arguments. Do not recommend sandboxing eval/exec;
|
|
47
|
+
use safe parsers such as ast.literal_eval. Do not add another dangerous command,
|
|
48
|
+
eval/exec, or RCE line to a patch; prefer shell=False and argument lists.
|
|
49
|
+
For DOM XSS, do not use innerHTML; use textContent for text and createElement()/
|
|
50
|
+
appendChild() for DOM nodes.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
WEB_SYSTEM_PROMPT = """
|
|
54
|
+
You are a senior web security and penetration testing expert. Analyze the provided
|
|
55
|
+
technical HTTP/SSL scan results.
|
|
56
|
+
Tasks:
|
|
57
|
+
1. Assess the target site's overall security risk. Emphasize exposed .env/.git files,
|
|
58
|
+
invalid SSL, or suspicious redirects as critical.
|
|
59
|
+
2. Summarize the practical risk of missing security headers and briefly explain how
|
|
60
|
+
to configure them server-side (Nginx/Apache/Cloudflare).
|
|
61
|
+
|
|
62
|
+
Return ONLY JSON in this format:
|
|
63
|
+
{
|
|
64
|
+
"risk_level": "CRITICAL" | "HIGH" | "MEDIUM" | "LOW",
|
|
65
|
+
"summary": "A concise summary of the target link's security status",
|
|
66
|
+
"recommendations": "Concrete remediation steps"
|
|
67
|
+
}
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
BATCH_SYSTEM_PROMPT = """
|
|
71
|
+
Evaluate candidates independently. Return a concise, direct JSON array only.
|
|
72
|
+
For a safe candidate, return exactly {"index": 0, "is_vulnerable": false}.
|
|
73
|
+
For a vulnerability, return {"index": 0, "is_vulnerable": true, "severity": "HIGH",
|
|
74
|
+
"title": "...", "description": "...", "fix": "..."}.
|
|
75
|
+
Use one sentence for description. Include only changed lines in fix.
|
|
76
|
+
Rate SQL injection and remote code/command execution as CRITICAL.
|
|
77
|
+
Also rate pickle.loads/load, SSTI, and ORM injection as CRITICAL.
|
|
78
|
+
Use yaml.safe_load() for unsafe YAML. For SSTI, do not compile user input as a
|
|
79
|
+
template; use file-based templates and auto-escaping. Parameterize ORM queries.
|
|
80
|
+
For Path Traversal, resolve base_dir, set target_path =
|
|
81
|
+
(base_dir / Path(user_name).name).resolve(), then verify target_path.is_relative_to(base_dir).
|
|
82
|
+
Do not join already-resolved paths. Do not include line-number prefixes or imports
|
|
83
|
+
already present in the source.
|
|
84
|
+
Use escapeshellarg for PHP shell arguments. Do not recommend sandboxing eval/exec;
|
|
85
|
+
use safe parsers. Do not add another dangerous command or RCE line.
|
|
86
|
+
For DOM XSS, do not use innerHTML; use textContent or createElement()/appendChild().
|
|
87
|
+
Preserve the index and return no prose outside the JSON.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _detect_language(file_label: str) -> str:
|
|
92
|
+
clean_name = file_label.split(" -> ")[0]
|
|
93
|
+
suffix = Path(clean_name).suffix.lower()
|
|
94
|
+
mapping = {
|
|
95
|
+
".py": "Python",
|
|
96
|
+
".js": "JavaScript (Node.js)",
|
|
97
|
+
".cjs": "JavaScript (Node.js CommonJS)",
|
|
98
|
+
".mjs": "JavaScript (Node.js ES Module)",
|
|
99
|
+
".ts": "TypeScript (Node.js)",
|
|
100
|
+
".json": "JSON configuration",
|
|
101
|
+
".yaml": "YAML configuration",
|
|
102
|
+
".yml": "YAML configuration",
|
|
103
|
+
".ini": "INI configuration",
|
|
104
|
+
".conf": "General configuration",
|
|
105
|
+
".cfg": "General configuration",
|
|
106
|
+
".env": "Environment configuration",
|
|
107
|
+
".php": "PHP",
|
|
108
|
+
".sql": "SQL",
|
|
109
|
+
".sh": "Bash / Shell",
|
|
110
|
+
".apk": "Android APK (Smali/DEX)",
|
|
111
|
+
".exe": "Windows PE Binary",
|
|
112
|
+
}
|
|
113
|
+
return mapping.get(suffix, "General source code / configuration")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _read_full_source(finding: dict, max_chars: int = 12000) -> str:
|
|
117
|
+
"""Read the full text file to give AI visibility into imports and validation context."""
|
|
118
|
+
if finding.get("is_binary"):
|
|
119
|
+
return ""
|
|
120
|
+
abs_path = finding.get("abs_path")
|
|
121
|
+
if not abs_path:
|
|
122
|
+
return ""
|
|
123
|
+
try:
|
|
124
|
+
p = Path(abs_path)
|
|
125
|
+
if p.is_file() and p.stat().st_size <= max_chars * 2:
|
|
126
|
+
text, _ = decode_source_bytes(p.read_bytes())
|
|
127
|
+
return text[:max_chars]
|
|
128
|
+
except OSError:
|
|
129
|
+
pass
|
|
130
|
+
return ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _read_source_excerpt(
|
|
134
|
+
finding: dict,
|
|
135
|
+
max_lines: int = 160,
|
|
136
|
+
max_chars: int = 1800,
|
|
137
|
+
) -> str:
|
|
138
|
+
return _read_source_excerpt_for_findings([finding], max_lines, max_chars)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _read_source_excerpt_for_findings(
|
|
142
|
+
findings: list[dict],
|
|
143
|
+
max_lines: int = 160,
|
|
144
|
+
max_chars: int = 1800,
|
|
145
|
+
) -> str:
|
|
146
|
+
"""Read leading imports and bounded windows for findings in one file."""
|
|
147
|
+
if not findings or findings[0].get("is_binary") or not findings[0].get("abs_path"):
|
|
148
|
+
return ""
|
|
149
|
+
try:
|
|
150
|
+
target_lines = sorted({
|
|
151
|
+
max(1, int(finding.get("line", 1)))
|
|
152
|
+
for finding in findings
|
|
153
|
+
})
|
|
154
|
+
windows = [
|
|
155
|
+
(max(1, target_line - 8), target_line + 8)
|
|
156
|
+
for target_line in target_lines
|
|
157
|
+
]
|
|
158
|
+
imports = []
|
|
159
|
+
window_lines = {}
|
|
160
|
+
multiline_import = False
|
|
161
|
+
|
|
162
|
+
source_text, _ = decode_source_bytes(Path(findings[0]["abs_path"]).read_bytes())
|
|
163
|
+
with io.StringIO(source_text) as source_file:
|
|
164
|
+
for line_number, raw_line in enumerate(source_file, start=1):
|
|
165
|
+
line = raw_line.rstrip("\r\n")
|
|
166
|
+
stripped = line.strip()
|
|
167
|
+
if line_number <= 15:
|
|
168
|
+
if multiline_import:
|
|
169
|
+
imports.append((line_number, line))
|
|
170
|
+
multiline_import = "(" in stripped and ")" not in stripped
|
|
171
|
+
elif not stripped or stripped.startswith("#"):
|
|
172
|
+
pass
|
|
173
|
+
elif re.match(r"^(?:from\s+\S+\s+import\b|import\s+)", stripped):
|
|
174
|
+
imports.append((line_number, line))
|
|
175
|
+
multiline_import = "(" in stripped and ")" not in stripped
|
|
176
|
+
|
|
177
|
+
if any(start <= line_number <= end for start, end in windows):
|
|
178
|
+
window_lines[line_number] = line
|
|
179
|
+
if line_number >= windows[-1][1]:
|
|
180
|
+
break
|
|
181
|
+
|
|
182
|
+
import_lines = []
|
|
183
|
+
import_line_numbers = set()
|
|
184
|
+
import_chars = 0
|
|
185
|
+
import_budget = min(900, max_chars // 2)
|
|
186
|
+
for line_number, line in imports:
|
|
187
|
+
if len(import_lines) >= 20 or import_chars + len(line) + 1 > import_budget:
|
|
188
|
+
break
|
|
189
|
+
import_lines.append(line)
|
|
190
|
+
import_line_numbers.add(line_number)
|
|
191
|
+
import_chars += len(line) + 1
|
|
192
|
+
|
|
193
|
+
overhead = len("Initial imports:\n") + len("Finding context:\n") + 2
|
|
194
|
+
if not import_lines:
|
|
195
|
+
overhead -= len("Initial imports:\n") + 1
|
|
196
|
+
available_chars = max(0, max_chars - import_chars - overhead)
|
|
197
|
+
available_lines = max_lines - len(import_lines)
|
|
198
|
+
|
|
199
|
+
prioritized_lines = list(target_lines)
|
|
200
|
+
for distance in range(1, 9):
|
|
201
|
+
for target_line in target_lines:
|
|
202
|
+
prioritized_lines.extend(
|
|
203
|
+
(target_line - distance, target_line + distance)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
selected_window = {}
|
|
207
|
+
used_chars = 0
|
|
208
|
+
for line_number in prioritized_lines:
|
|
209
|
+
if (
|
|
210
|
+
line_number not in window_lines
|
|
211
|
+
or line_number in selected_window
|
|
212
|
+
or line_number in import_line_numbers
|
|
213
|
+
):
|
|
214
|
+
continue
|
|
215
|
+
if len(selected_window) >= available_lines:
|
|
216
|
+
break
|
|
217
|
+
line = window_lines[line_number]
|
|
218
|
+
remaining = available_chars - used_chars
|
|
219
|
+
if remaining <= 0:
|
|
220
|
+
break
|
|
221
|
+
if len(line) + 1 > remaining:
|
|
222
|
+
if line_number in target_lines:
|
|
223
|
+
selected_window[line_number] = line[:remaining]
|
|
224
|
+
used_chars += remaining
|
|
225
|
+
continue
|
|
226
|
+
selected_window[line_number] = line
|
|
227
|
+
used_chars += len(line) + 1
|
|
228
|
+
|
|
229
|
+
sections = []
|
|
230
|
+
if import_lines:
|
|
231
|
+
sections.append("Initial imports:\n" + "\n".join(import_lines))
|
|
232
|
+
if selected_window:
|
|
233
|
+
sections.append(
|
|
234
|
+
"Finding context:\n"
|
|
235
|
+
+ "\n".join(
|
|
236
|
+
selected_window[line_number]
|
|
237
|
+
for line_number in sorted(selected_window)
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
return "\n\n".join(sections)[:max_chars]
|
|
241
|
+
except (OSError, TypeError, ValueError):
|
|
242
|
+
return ""
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _align_vulnerable_code(snippet: str, *sources: str) -> str | None:
|
|
246
|
+
"""Align the returned vulnerable block with its exact indentation in the source."""
|
|
247
|
+
if not snippet or not snippet.strip():
|
|
248
|
+
return None
|
|
249
|
+
|
|
250
|
+
for src in sources:
|
|
251
|
+
if src and snippet in src:
|
|
252
|
+
return snippet
|
|
253
|
+
|
|
254
|
+
target_lines = [line.strip() for line in snippet.strip().splitlines() if line.strip()]
|
|
255
|
+
if not target_lines:
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
for src in sources:
|
|
259
|
+
if not src:
|
|
260
|
+
continue
|
|
261
|
+
src_lines = src.splitlines()
|
|
262
|
+
for i in range(len(src_lines)):
|
|
263
|
+
if src_lines[i].strip() != target_lines[0]:
|
|
264
|
+
continue
|
|
265
|
+
t_idx = 0
|
|
266
|
+
s_idx = i
|
|
267
|
+
while s_idx < len(src_lines) and t_idx < len(target_lines):
|
|
268
|
+
if not src_lines[s_idx].strip():
|
|
269
|
+
s_idx += 1
|
|
270
|
+
continue
|
|
271
|
+
if src_lines[s_idx].strip() == target_lines[t_idx]:
|
|
272
|
+
t_idx += 1
|
|
273
|
+
s_idx += 1
|
|
274
|
+
else:
|
|
275
|
+
break
|
|
276
|
+
if t_idx == len(target_lines):
|
|
277
|
+
return "\n".join(src_lines[i:s_idx])
|
|
278
|
+
|
|
279
|
+
return None
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _extract_json_dict(raw_text: str) -> dict | None:
|
|
283
|
+
candidate = raw_text.strip()
|
|
284
|
+
if candidate.startswith("```"):
|
|
285
|
+
candidate = candidate.split("\n", 1)[-1]
|
|
286
|
+
if candidate.rstrip().endswith("```"):
|
|
287
|
+
candidate = candidate.rstrip()[:-3]
|
|
288
|
+
candidate = candidate.strip()
|
|
289
|
+
if candidate.startswith("json"):
|
|
290
|
+
candidate = candidate[4:].strip()
|
|
291
|
+
|
|
292
|
+
try:
|
|
293
|
+
parsed = json.loads(candidate)
|
|
294
|
+
return parsed if isinstance(parsed, dict) else None
|
|
295
|
+
except json.JSONDecodeError:
|
|
296
|
+
match = re.search(r"\{.*\}", candidate, re.DOTALL)
|
|
297
|
+
if not match:
|
|
298
|
+
return None
|
|
299
|
+
try:
|
|
300
|
+
parsed = json.loads(match.group(0))
|
|
301
|
+
return parsed if isinstance(parsed, dict) else None
|
|
302
|
+
except json.JSONDecodeError:
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _extract_json_list(raw_text: str) -> list | None:
|
|
307
|
+
candidate = raw_text.strip()
|
|
308
|
+
if candidate.startswith("```"):
|
|
309
|
+
candidate = candidate.split("\n", 1)[-1]
|
|
310
|
+
if candidate.rstrip().endswith("```"):
|
|
311
|
+
candidate = candidate.rstrip()[:-3]
|
|
312
|
+
candidate = candidate.strip()
|
|
313
|
+
if candidate.startswith("json"):
|
|
314
|
+
candidate = candidate[4:].strip()
|
|
315
|
+
|
|
316
|
+
try:
|
|
317
|
+
parsed = json.loads(candidate)
|
|
318
|
+
return parsed if isinstance(parsed, list) else None
|
|
319
|
+
except json.JSONDecodeError:
|
|
320
|
+
decoder = json.JSONDecoder()
|
|
321
|
+
for index, character in enumerate(candidate):
|
|
322
|
+
if character != "[":
|
|
323
|
+
continue
|
|
324
|
+
try:
|
|
325
|
+
parsed, _ = decoder.raw_decode(candidate, index)
|
|
326
|
+
except json.JSONDecodeError:
|
|
327
|
+
continue
|
|
328
|
+
if isinstance(parsed, list):
|
|
329
|
+
return parsed
|
|
330
|
+
return None
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _validate_with_feedback(
|
|
334
|
+
raw_text: str,
|
|
335
|
+
context: str,
|
|
336
|
+
full_source: str = "",
|
|
337
|
+
lang: str = "Python",
|
|
338
|
+
issue: str = "",
|
|
339
|
+
) -> tuple[dict | None, str]:
|
|
340
|
+
"""Validate a response and return feedback for one retry when invalid."""
|
|
341
|
+
result = _extract_json_dict(raw_text)
|
|
342
|
+
if result is None:
|
|
343
|
+
return None, "Response is not a valid JSON object; return raw JSON only."
|
|
344
|
+
|
|
345
|
+
if type(result.get("is_vulnerable")) is not bool:
|
|
346
|
+
return None, "'is_vulnerable' must be a boolean (true/false)."
|
|
347
|
+
|
|
348
|
+
if not result["is_vulnerable"]:
|
|
349
|
+
result.setdefault("severity", "LOW")
|
|
350
|
+
result.setdefault("explanation", "")
|
|
351
|
+
result.setdefault("vulnerable_code", "")
|
|
352
|
+
result.setdefault("fixed_code", "")
|
|
353
|
+
result.setdefault("cwe", "")
|
|
354
|
+
return _apply_finding_policy({"issue": issue}, result, lang), ""
|
|
355
|
+
|
|
356
|
+
severity = result.get("severity")
|
|
357
|
+
if not isinstance(severity, str) or severity.upper() not in {"CRITICAL", "HIGH", "MEDIUM", "LOW"}:
|
|
358
|
+
return None, "'severity' must be CRITICAL, HIGH, MEDIUM, or LOW."
|
|
359
|
+
result["severity"] = severity.upper()
|
|
360
|
+
|
|
361
|
+
if not all(isinstance(result.get(key), str) for key in ("explanation", "vulnerable_code", "fixed_code")):
|
|
362
|
+
return None, "'explanation', 'vulnerable_code', and 'fixed_code' must be strings."
|
|
363
|
+
|
|
364
|
+
result.setdefault("cwe", "")
|
|
365
|
+
|
|
366
|
+
if result["is_vulnerable"]:
|
|
367
|
+
aligned = _align_vulnerable_code(result["vulnerable_code"], context, full_source)
|
|
368
|
+
if not aligned:
|
|
369
|
+
return None, (
|
|
370
|
+
"'vulnerable_code' does not exactly match lines in the provided code "
|
|
371
|
+
"context. Copy the target line and relevant lines exactly."
|
|
372
|
+
)
|
|
373
|
+
result["vulnerable_code"] = aligned
|
|
374
|
+
result["fixed_code"] = _clean_patch_text(
|
|
375
|
+
result["fixed_code"],
|
|
376
|
+
full_source,
|
|
377
|
+
lang,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
patch_feedback = _unsafe_patch_feedback(result["fixed_code"], lang, issue)
|
|
381
|
+
if patch_feedback:
|
|
382
|
+
return None, patch_feedback
|
|
383
|
+
|
|
384
|
+
if lang.casefold().startswith("python") and result["fixed_code"].strip():
|
|
385
|
+
try:
|
|
386
|
+
ast.parse(result["fixed_code"].lstrip())
|
|
387
|
+
except SyntaxError:
|
|
388
|
+
if full_source and aligned in full_source:
|
|
389
|
+
patched_preview = full_source.replace(aligned, result["fixed_code"], 1)
|
|
390
|
+
try:
|
|
391
|
+
ast.parse(patched_preview)
|
|
392
|
+
except SyntaxError as e:
|
|
393
|
+
return None, (
|
|
394
|
+
f"Generated 'fixed_code' contains a Python SyntaxError "
|
|
395
|
+
f"({e.msg}); correct the syntax."
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
return _apply_finding_policy({"issue": issue}, result, lang), ""
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _clean_patch_text(fixed_code: str, full_source: str, code_language: str) -> str:
|
|
402
|
+
lines = [
|
|
403
|
+
re.sub(
|
|
404
|
+
r"^(\s*)[+-] ",
|
|
405
|
+
r"\1",
|
|
406
|
+
re.sub(r"^(\s*)\d+:[ \t]?", r"\1", line),
|
|
407
|
+
)
|
|
408
|
+
for line in fixed_code.splitlines()
|
|
409
|
+
]
|
|
410
|
+
if not code_language.casefold().startswith("python"):
|
|
411
|
+
return "\n".join(lines)
|
|
412
|
+
|
|
413
|
+
def import_keys(node: ast.AST) -> set[tuple]:
|
|
414
|
+
if isinstance(node, ast.Import):
|
|
415
|
+
return {
|
|
416
|
+
("import", alias.name, alias.asname)
|
|
417
|
+
for alias in node.names
|
|
418
|
+
}
|
|
419
|
+
if isinstance(node, ast.ImportFrom):
|
|
420
|
+
return {
|
|
421
|
+
("from", node.level, node.module, alias.name, alias.asname)
|
|
422
|
+
for alias in node.names
|
|
423
|
+
}
|
|
424
|
+
return set()
|
|
425
|
+
|
|
426
|
+
seen_imports = set()
|
|
427
|
+
try:
|
|
428
|
+
source_tree = ast.parse(full_source) if full_source else None
|
|
429
|
+
except SyntaxError:
|
|
430
|
+
source_tree = None
|
|
431
|
+
if source_tree is not None:
|
|
432
|
+
for node in ast.walk(source_tree):
|
|
433
|
+
seen_imports.update(import_keys(node))
|
|
434
|
+
|
|
435
|
+
cleaned_lines = []
|
|
436
|
+
for line in lines:
|
|
437
|
+
stripped = line.strip()
|
|
438
|
+
try:
|
|
439
|
+
parsed_line = ast.parse(stripped)
|
|
440
|
+
except SyntaxError:
|
|
441
|
+
parsed_line = None
|
|
442
|
+
if parsed_line and len(parsed_line.body) == 1:
|
|
443
|
+
node = parsed_line.body[0]
|
|
444
|
+
keys = import_keys(node)
|
|
445
|
+
if keys:
|
|
446
|
+
new_keys = keys - seen_imports
|
|
447
|
+
if not new_keys:
|
|
448
|
+
continue
|
|
449
|
+
seen_imports.update(keys)
|
|
450
|
+
if isinstance(node, ast.Import) and len(new_keys) != len(keys):
|
|
451
|
+
aliases = [
|
|
452
|
+
alias
|
|
453
|
+
for alias in node.names
|
|
454
|
+
if ("import", alias.name, alias.asname) in new_keys
|
|
455
|
+
]
|
|
456
|
+
line = line[:len(line) - len(line.lstrip())] + "import " + ", ".join(
|
|
457
|
+
alias.name + (f" as {alias.asname}" if alias.asname else "")
|
|
458
|
+
for alias in aliases
|
|
459
|
+
)
|
|
460
|
+
elif isinstance(node, ast.ImportFrom) and len(new_keys) != len(keys):
|
|
461
|
+
aliases = [
|
|
462
|
+
alias
|
|
463
|
+
for alias in node.names
|
|
464
|
+
if ("from", node.level, node.module, alias.name, alias.asname) in new_keys
|
|
465
|
+
]
|
|
466
|
+
prefix = "." * node.level + (node.module or "")
|
|
467
|
+
line = (
|
|
468
|
+
line[:len(line) - len(line.lstrip())]
|
|
469
|
+
+ f"from {prefix} import "
|
|
470
|
+
+ ", ".join(
|
|
471
|
+
alias.name + (f" as {alias.asname}" if alias.asname else "")
|
|
472
|
+
for alias in aliases
|
|
473
|
+
)
|
|
474
|
+
)
|
|
475
|
+
cleaned_lines.append(line)
|
|
476
|
+
return "\n".join(cleaned_lines)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _unsafe_patch_feedback(
|
|
480
|
+
fixed_code: str,
|
|
481
|
+
code_language: str,
|
|
482
|
+
issue: str = "",
|
|
483
|
+
) -> str:
|
|
484
|
+
if not fixed_code.strip():
|
|
485
|
+
return ""
|
|
486
|
+
if re.search(r"\.innerHTML\s*\+?=", fixed_code, re.IGNORECASE):
|
|
487
|
+
return (
|
|
488
|
+
"DOM XSS patches must not assign to innerHTML; use textContent for text "
|
|
489
|
+
"and createElement()/appendChild() for DOM nodes."
|
|
490
|
+
)
|
|
491
|
+
if re.search(r"\beval\s*\(", fixed_code):
|
|
492
|
+
return "Do not use eval() in the patch; use a safe parser such as ast.literal_eval."
|
|
493
|
+
if re.search(r"\bexec\s*\(", fixed_code):
|
|
494
|
+
return "Do not execute code with exec() in the patch; use a safe, restricted implementation."
|
|
495
|
+
if re.search(r"\bshell\s*=\s*True\b", fixed_code, re.IGNORECASE):
|
|
496
|
+
return "Do not use shell=True; run the command with shell=False and an argument list."
|
|
497
|
+
if re.search(r"\bos\.(?:system|popen)\s*\(", fixed_code):
|
|
498
|
+
return "Do not run shell commands with os.system/os.popen."
|
|
499
|
+
if re.search(r"\b(?:pickle|cPickle|dill)\.loads?\s*\(", fixed_code):
|
|
500
|
+
return "Do not load untrusted data with pickle/dill."
|
|
501
|
+
if "yaml" in issue.casefold() and re.search(
|
|
502
|
+
r"\byaml\.load\s*\(",
|
|
503
|
+
fixed_code,
|
|
504
|
+
) and not re.search(r"\bSafeLoader\b", fixed_code):
|
|
505
|
+
return "Use yaml.safe_load() instead of yaml.load()."
|
|
506
|
+
if re.search(
|
|
507
|
+
r"\bsubprocess\.(?:run|call|Popen|check_call|check_output)\s*\(\s*"
|
|
508
|
+
r"(?:f[\"']|[\"'][^\"']*(?:\+|%))",
|
|
509
|
+
fixed_code,
|
|
510
|
+
):
|
|
511
|
+
return "Do not construct a dynamic shell command string; use shell=False and an argument list."
|
|
512
|
+
if re.search(
|
|
513
|
+
r"\bPath\s*\([^)]*\)\.resolve\s*\(\s*\)\s*/\s*"
|
|
514
|
+
r"Path\s*\([^)]*\)\.resolve\s*\(\s*\)",
|
|
515
|
+
fixed_code,
|
|
516
|
+
):
|
|
517
|
+
return "Do not join resolved paths in a Path Traversal patch; sanitize the basename and join it to a trusted root."
|
|
518
|
+
if (
|
|
519
|
+
code_language.casefold().startswith("python")
|
|
520
|
+
and "path traversal" in issue.casefold()
|
|
521
|
+
and not _path_containment_is_resolved(fixed_code)
|
|
522
|
+
):
|
|
523
|
+
return "A Path Traversal patch must call `.resolve()` on base_dir and target_path, sanitize the basename, and verify is_relative_to()."
|
|
524
|
+
if re.search(r"\bis_relative_to\s*\(", fixed_code) and not _path_containment_is_resolved(fixed_code):
|
|
525
|
+
return "Resolve base_dir and the sanitized target path before calling is_relative_to()."
|
|
526
|
+
|
|
527
|
+
php_shell_call = re.search(
|
|
528
|
+
r"\b(?:shell_exec|exec|system|passthru|popen|proc_open|pcntl_exec)\s*\(",
|
|
529
|
+
fixed_code,
|
|
530
|
+
)
|
|
531
|
+
if (
|
|
532
|
+
code_language.casefold() == "php"
|
|
533
|
+
and php_shell_call
|
|
534
|
+
and not re.search(r"\bescapeshellarg\s*\(", fixed_code)
|
|
535
|
+
):
|
|
536
|
+
return "Escape PHP shell arguments with escapeshellarg()."
|
|
537
|
+
return ""
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _path_containment_is_resolved(fixed_code: str) -> bool:
|
|
541
|
+
try:
|
|
542
|
+
tree = ast.parse(textwrap.dedent(fixed_code))
|
|
543
|
+
except SyntaxError:
|
|
544
|
+
return False
|
|
545
|
+
|
|
546
|
+
def is_path_call(node: ast.AST) -> bool:
|
|
547
|
+
return (
|
|
548
|
+
isinstance(node, ast.Call)
|
|
549
|
+
and (
|
|
550
|
+
isinstance(node.func, ast.Name) and node.func.id == "Path"
|
|
551
|
+
or isinstance(node.func, ast.Attribute) and node.func.attr == "Path"
|
|
552
|
+
)
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
def is_resolved_path(node: ast.AST) -> bool:
|
|
556
|
+
return (
|
|
557
|
+
isinstance(node, ast.Call)
|
|
558
|
+
and isinstance(node.func, ast.Attribute)
|
|
559
|
+
and node.func.attr == "resolve"
|
|
560
|
+
and is_path_call(node.func.value)
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
def is_sanitized_name(node: ast.AST) -> bool:
|
|
564
|
+
if (
|
|
565
|
+
isinstance(node, ast.Attribute)
|
|
566
|
+
and node.attr == "name"
|
|
567
|
+
and is_path_call(node.value)
|
|
568
|
+
):
|
|
569
|
+
return True
|
|
570
|
+
return (
|
|
571
|
+
isinstance(node, ast.Call)
|
|
572
|
+
and (
|
|
573
|
+
isinstance(node.func, ast.Name) and node.func.id == "basename"
|
|
574
|
+
or isinstance(node.func, ast.Attribute) and node.func.attr == "basename"
|
|
575
|
+
)
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
assignments: list[tuple[str, int, ast.AST]] = []
|
|
579
|
+
for node in ast.walk(tree):
|
|
580
|
+
if isinstance(node, ast.Assign):
|
|
581
|
+
assignments.extend(
|
|
582
|
+
(target.id, node.end_lineno, node.value)
|
|
583
|
+
for target in node.targets
|
|
584
|
+
if isinstance(target, ast.Name)
|
|
585
|
+
)
|
|
586
|
+
elif isinstance(node, ast.AnnAssign) and node.value is not None:
|
|
587
|
+
if isinstance(node.target, ast.Name):
|
|
588
|
+
assignments.append((node.target.id, node.end_lineno, node.value))
|
|
589
|
+
|
|
590
|
+
containment_checks = [
|
|
591
|
+
node for node in ast.walk(tree)
|
|
592
|
+
if isinstance(node, ast.Call)
|
|
593
|
+
and isinstance(node.func, ast.Attribute)
|
|
594
|
+
and node.func.attr == "is_relative_to"
|
|
595
|
+
and node.args
|
|
596
|
+
]
|
|
597
|
+
if not containment_checks:
|
|
598
|
+
return False
|
|
599
|
+
|
|
600
|
+
for check in containment_checks:
|
|
601
|
+
latest_assignments = {}
|
|
602
|
+
for name, line_number, value in sorted(assignments, key=lambda item: item[1]):
|
|
603
|
+
if line_number < check.lineno:
|
|
604
|
+
latest_assignments[name] = value
|
|
605
|
+
target = check.func.value
|
|
606
|
+
base = check.args[0]
|
|
607
|
+
if not isinstance(target, ast.Name) or not isinstance(base, ast.Name):
|
|
608
|
+
return False
|
|
609
|
+
base_value = latest_assignments.get(base.id)
|
|
610
|
+
target_value = latest_assignments.get(target.id)
|
|
611
|
+
if not is_resolved_path(base_value) or not isinstance(target_value, ast.Call):
|
|
612
|
+
return False
|
|
613
|
+
if not (
|
|
614
|
+
isinstance(target_value.func, ast.Attribute)
|
|
615
|
+
and target_value.func.attr == "resolve"
|
|
616
|
+
and isinstance(target_value.func.value, ast.BinOp)
|
|
617
|
+
and isinstance(target_value.func.value.op, ast.Div)
|
|
618
|
+
):
|
|
619
|
+
return False
|
|
620
|
+
joined_path = target_value.func.value
|
|
621
|
+
if (
|
|
622
|
+
not isinstance(joined_path.left, ast.Name)
|
|
623
|
+
or joined_path.left.id != base.id
|
|
624
|
+
or not is_sanitized_name(joined_path.right)
|
|
625
|
+
):
|
|
626
|
+
return False
|
|
627
|
+
return True
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _requires_critical_severity(issue: str) -> bool:
|
|
631
|
+
return bool(re.search(
|
|
632
|
+
r"\bsqli\b|sql\s*injection|sql\s*enj|rce|remote\s+code\s+execution|"
|
|
633
|
+
r"command\s+injection|code\s+execution|command\s+execution|"
|
|
634
|
+
r"\bpickle\b|\bssti\b|template\s+injection|orm\s+injection",
|
|
635
|
+
issue,
|
|
636
|
+
re.IGNORECASE,
|
|
637
|
+
))
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def _apply_finding_policy(
|
|
641
|
+
finding: dict,
|
|
642
|
+
verdict: dict | None,
|
|
643
|
+
lang: str = "Python",
|
|
644
|
+
) -> dict | None:
|
|
645
|
+
if verdict is None:
|
|
646
|
+
return None
|
|
647
|
+
result = dict(verdict)
|
|
648
|
+
issue = str(finding.get("issue", ""))
|
|
649
|
+
if result.get("is_vulnerable") and _requires_critical_severity(issue):
|
|
650
|
+
result["severity"] = "CRITICAL"
|
|
651
|
+
if result.get("is_vulnerable") and re.search(
|
|
652
|
+
r"weak cryptographic hash.*\b(?:md5|sha1)\b",
|
|
653
|
+
issue,
|
|
654
|
+
re.IGNORECASE,
|
|
655
|
+
):
|
|
656
|
+
result["severity"] = "MEDIUM"
|
|
657
|
+
if "cors" in issue.casefold():
|
|
658
|
+
result["title"] = "Unsafe CORS Configuration"
|
|
659
|
+
return result
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _safe_patch_fallback(
|
|
663
|
+
issue: str,
|
|
664
|
+
vulnerable_code: str = "",
|
|
665
|
+
) -> str:
|
|
666
|
+
if re.search(r"\b(?:DOM\s*)?XSS\b", issue, re.IGNORECASE):
|
|
667
|
+
safe_code = re.sub(
|
|
668
|
+
r"\b(?:innerHTML|outerHTML)\b(?=\s*\+?=)",
|
|
669
|
+
"textContent",
|
|
670
|
+
vulnerable_code,
|
|
671
|
+
flags=re.IGNORECASE,
|
|
672
|
+
)
|
|
673
|
+
if safe_code != vulnerable_code:
|
|
674
|
+
return safe_code
|
|
675
|
+
return (
|
|
676
|
+
f"{PATCH_VALIDATION_FAILED} use textContent for text and "
|
|
677
|
+
"createElement()/appendChild() for DOM nodes."
|
|
678
|
+
)
|
|
679
|
+
if "path traversal" in issue.casefold():
|
|
680
|
+
return (
|
|
681
|
+
f"{PATCH_VALIDATION_FAILED} resolve the trusted base directory and "
|
|
682
|
+
"target path, sanitize the basename, and verify containment."
|
|
683
|
+
)
|
|
684
|
+
return f"{PATCH_VALIDATION_FAILED} review the finding and apply a secure fix manually."
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def _preserve_rejected_patch_finding(
|
|
688
|
+
finding: dict,
|
|
689
|
+
raw_text: str,
|
|
690
|
+
feedback: str,
|
|
691
|
+
context: str,
|
|
692
|
+
full_source: str,
|
|
693
|
+
code_language: str,
|
|
694
|
+
) -> dict | None:
|
|
695
|
+
candidate = _extract_json_dict(raw_text)
|
|
696
|
+
if not isinstance(candidate, dict) or candidate.get("is_vulnerable") is not True:
|
|
697
|
+
return None
|
|
698
|
+
severity = candidate.get("severity")
|
|
699
|
+
if not isinstance(severity, str) or severity.upper() not in {
|
|
700
|
+
"CRITICAL", "HIGH", "MEDIUM", "LOW",
|
|
701
|
+
}:
|
|
702
|
+
return None
|
|
703
|
+
if not all(
|
|
704
|
+
isinstance(candidate.get(key), str)
|
|
705
|
+
for key in ("explanation", "vulnerable_code", "fixed_code")
|
|
706
|
+
):
|
|
707
|
+
return None
|
|
708
|
+
|
|
709
|
+
issue = str(finding.get("issue", ""))
|
|
710
|
+
fixed_code = _clean_patch_text(candidate["fixed_code"], full_source, code_language)
|
|
711
|
+
rejected_patch = bool(_unsafe_patch_feedback(fixed_code, code_language, issue)) or (
|
|
712
|
+
"SyntaxError" in feedback
|
|
713
|
+
)
|
|
714
|
+
if not rejected_patch:
|
|
715
|
+
return None
|
|
716
|
+
aligned_code = _align_vulnerable_code(
|
|
717
|
+
candidate["vulnerable_code"],
|
|
718
|
+
context,
|
|
719
|
+
full_source,
|
|
720
|
+
)
|
|
721
|
+
if not aligned_code:
|
|
722
|
+
return None
|
|
723
|
+
|
|
724
|
+
preserved = dict(candidate)
|
|
725
|
+
preserved["severity"] = severity.upper()
|
|
726
|
+
preserved["vulnerable_code"] = aligned_code
|
|
727
|
+
preserved["fixed_code"] = _safe_patch_fallback(
|
|
728
|
+
issue,
|
|
729
|
+
aligned_code,
|
|
730
|
+
)
|
|
731
|
+
preserved["patch_applicable"] = not preserved["fixed_code"].startswith(
|
|
732
|
+
PATCH_VALIDATION_FAILED
|
|
733
|
+
)
|
|
734
|
+
return _apply_finding_policy(finding, preserved, code_language)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _validate_finding_response(raw_text: str, context: str) -> dict | None:
|
|
738
|
+
result, _ = _validate_with_feedback(raw_text, context)
|
|
739
|
+
return result
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _call_chat_completion(
|
|
743
|
+
client: OpenAI,
|
|
744
|
+
model: str,
|
|
745
|
+
messages: list[dict],
|
|
746
|
+
*,
|
|
747
|
+
local: bool = False,
|
|
748
|
+
max_tokens: int | None = None,
|
|
749
|
+
) -> str:
|
|
750
|
+
options = {
|
|
751
|
+
"model": model,
|
|
752
|
+
"messages": messages,
|
|
753
|
+
"temperature": 0.1,
|
|
754
|
+
}
|
|
755
|
+
if local:
|
|
756
|
+
options.update({"max_tokens": 512, "timeout": 120.0})
|
|
757
|
+
else:
|
|
758
|
+
normalized_model = model.lower()
|
|
759
|
+
if "gpt-oss" in normalized_model or "qwen" in normalized_model:
|
|
760
|
+
options.update({
|
|
761
|
+
"reasoning_effort": "low",
|
|
762
|
+
"max_tokens": max_tokens or 500,
|
|
763
|
+
})
|
|
764
|
+
if "gpt-oss" in normalized_model:
|
|
765
|
+
options.setdefault("max_tokens", max_tokens or 500)
|
|
766
|
+
elif "qwen3" in normalized_model:
|
|
767
|
+
options.update({
|
|
768
|
+
"extra_body": {"reasoning_format": "hidden"},
|
|
769
|
+
"max_tokens": max_tokens or 500,
|
|
770
|
+
})
|
|
771
|
+
elif max_tokens is not None:
|
|
772
|
+
options["max_tokens"] = max_tokens
|
|
773
|
+
|
|
774
|
+
try:
|
|
775
|
+
response = client.chat.completions.create(
|
|
776
|
+
**options,
|
|
777
|
+
response_format={"type": "json_object"},
|
|
778
|
+
)
|
|
779
|
+
except TypeError:
|
|
780
|
+
retry_options = options
|
|
781
|
+
if "extra_body" in options:
|
|
782
|
+
retry_options = {**options}
|
|
783
|
+
retry_options.pop("extra_body")
|
|
784
|
+
try:
|
|
785
|
+
response = client.chat.completions.create(
|
|
786
|
+
**retry_options,
|
|
787
|
+
response_format={"type": "json_object"},
|
|
788
|
+
)
|
|
789
|
+
except Exception as error:
|
|
790
|
+
if (
|
|
791
|
+
"reasoning_effort" in options
|
|
792
|
+
and _reasoning_effort_unsupported(error)
|
|
793
|
+
):
|
|
794
|
+
retry_options = {**options}
|
|
795
|
+
retry_options.pop("reasoning_effort", None)
|
|
796
|
+
response = client.chat.completions.create(
|
|
797
|
+
**retry_options,
|
|
798
|
+
response_format={"type": "json_object"},
|
|
799
|
+
)
|
|
800
|
+
return (response.choices[0].message.content or "").strip()
|
|
801
|
+
if _is_local_fallback_error(error) or (
|
|
802
|
+
local and getattr(error, "status_code", None) in {404, 500}
|
|
803
|
+
):
|
|
804
|
+
raise
|
|
805
|
+
response = client.chat.completions.create(**retry_options)
|
|
806
|
+
except Exception as error:
|
|
807
|
+
if (
|
|
808
|
+
"reasoning_effort" in options
|
|
809
|
+
and _reasoning_effort_unsupported(error)
|
|
810
|
+
):
|
|
811
|
+
retry_options = {**options}
|
|
812
|
+
retry_options.pop("reasoning_effort", None)
|
|
813
|
+
response = client.chat.completions.create(
|
|
814
|
+
**retry_options,
|
|
815
|
+
response_format={"type": "json_object"},
|
|
816
|
+
)
|
|
817
|
+
return (response.choices[0].message.content or "").strip()
|
|
818
|
+
if _is_local_fallback_error(error) or (
|
|
819
|
+
local and getattr(error, "status_code", None) in {404, 500}
|
|
820
|
+
):
|
|
821
|
+
raise
|
|
822
|
+
response = client.chat.completions.create(
|
|
823
|
+
**options,
|
|
824
|
+
)
|
|
825
|
+
return (response.choices[0].message.content or "").strip()
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _reasoning_effort_unsupported(error: Exception) -> bool:
|
|
829
|
+
if getattr(error, "status_code", None) != 400:
|
|
830
|
+
return False
|
|
831
|
+
message = str(error).casefold()
|
|
832
|
+
return "reasoning_effort" in message and any(
|
|
833
|
+
phrase in message
|
|
834
|
+
for phrase in ("unsupported", "not support", "unknown", "invalid", "parameter")
|
|
835
|
+
)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _is_local_fallback_error(error: Exception) -> bool:
|
|
839
|
+
if getattr(error, "status_code", None) in {401, 403, 429, 503}:
|
|
840
|
+
return True
|
|
841
|
+
return isinstance(error, (APIConnectionError, httpx.TransportError, ConnectionError, TimeoutError))
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def _retry_after_seconds(error: Exception) -> float | None:
|
|
845
|
+
response = getattr(error, "response", None)
|
|
846
|
+
headers = getattr(response, "headers", None)
|
|
847
|
+
retry_after = headers.get("Retry-After") if headers else None
|
|
848
|
+
if retry_after is None:
|
|
849
|
+
return None
|
|
850
|
+
try:
|
|
851
|
+
seconds = float(retry_after)
|
|
852
|
+
return max(0.0, seconds) if math.isfinite(seconds) else None
|
|
853
|
+
except (TypeError, ValueError, OverflowError):
|
|
854
|
+
try:
|
|
855
|
+
return max(0.0, parsedate_to_datetime(retry_after).timestamp() - time.time())
|
|
856
|
+
except (TypeError, ValueError, OverflowError):
|
|
857
|
+
return None
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def _wait_for_shared_rate_limit() -> None:
|
|
861
|
+
global rate_limit_until
|
|
862
|
+
while True:
|
|
863
|
+
with _rate_limit_lock:
|
|
864
|
+
cooldown_until = rate_limit_until
|
|
865
|
+
delay = cooldown_until - time.monotonic()
|
|
866
|
+
if delay <= 0:
|
|
867
|
+
if rate_limit_until == cooldown_until:
|
|
868
|
+
rate_limit_until = 0.0
|
|
869
|
+
return
|
|
870
|
+
|
|
871
|
+
time.sleep(delay)
|
|
872
|
+
with _rate_limit_lock:
|
|
873
|
+
if rate_limit_until == cooldown_until:
|
|
874
|
+
rate_limit_until = 0.0
|
|
875
|
+
return
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _pace_cloud_request() -> None:
|
|
879
|
+
global _last_cloud_request_at
|
|
880
|
+
with _cloud_pacing_lock:
|
|
881
|
+
now = time.monotonic()
|
|
882
|
+
delay = _last_cloud_request_at + MIN_CLOUD_REQUEST_INTERVAL - now
|
|
883
|
+
if delay > 0:
|
|
884
|
+
time.sleep(delay)
|
|
885
|
+
now = time.monotonic()
|
|
886
|
+
_last_cloud_request_at = now
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _schedule_shared_rate_limit(delay: float) -> tuple[float, bool]:
|
|
890
|
+
global rate_limit_until
|
|
891
|
+
with _rate_limit_lock:
|
|
892
|
+
now = time.monotonic()
|
|
893
|
+
if rate_limit_until > now:
|
|
894
|
+
return rate_limit_until - now, False
|
|
895
|
+
rate_limit_until = now + delay
|
|
896
|
+
return delay, True
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def _claim_rate_limit_notice() -> bool:
|
|
900
|
+
global _rate_limit_notice_until
|
|
901
|
+
with _rate_limit_lock:
|
|
902
|
+
now = time.monotonic()
|
|
903
|
+
if now < _rate_limit_notice_until:
|
|
904
|
+
return False
|
|
905
|
+
_rate_limit_notice_until = now + 60.0
|
|
906
|
+
return True
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def _uses_groq(cfg: dict) -> bool:
|
|
910
|
+
return cfg.get("provider") == "groq" or "api.groq.com" in cfg.get("base_url", "")
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def _next_live_groq_model(cfg: dict, tried_models: set[str]) -> str | None:
|
|
914
|
+
models = fetch_active_models(cfg["base_url"], cfg["api_key"])
|
|
915
|
+
return select_next_active_model(models, tried_models)
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
def _local_config() -> dict:
|
|
919
|
+
model = os.getenv("SECGUARD_LOCAL_MODEL")
|
|
920
|
+
if not model:
|
|
921
|
+
try:
|
|
922
|
+
response = httpx.get(LOCAL_TAGS_URL, timeout=1.0)
|
|
923
|
+
except httpx.HTTPError as error:
|
|
924
|
+
raise RuntimeError(
|
|
925
|
+
"Could not connect to Ollama at localhost:11434. "
|
|
926
|
+
"Ensure Ollama is installed and running."
|
|
927
|
+
) from error
|
|
928
|
+
|
|
929
|
+
if response.status_code != 200:
|
|
930
|
+
raise RuntimeError(
|
|
931
|
+
f"Could not retrieve the Ollama model list "
|
|
932
|
+
f"(HTTP {response.status_code})."
|
|
933
|
+
)
|
|
934
|
+
|
|
935
|
+
try:
|
|
936
|
+
payload = response.json()
|
|
937
|
+
except (ValueError, AttributeError) as error:
|
|
938
|
+
raise RuntimeError("Ollama returned an invalid model list.") from error
|
|
939
|
+
models = payload.get("models") if isinstance(payload, dict) else None
|
|
940
|
+
if not isinstance(models, list):
|
|
941
|
+
raise RuntimeError("Ollama returned an invalid model list.")
|
|
942
|
+
|
|
943
|
+
model_names = []
|
|
944
|
+
for item in models:
|
|
945
|
+
if isinstance(item, dict):
|
|
946
|
+
name = item.get("name") or item.get("model")
|
|
947
|
+
if isinstance(name, str) and name:
|
|
948
|
+
model_names.append(name)
|
|
949
|
+
if not model_names:
|
|
950
|
+
raise RuntimeError("No Ollama models are installed.")
|
|
951
|
+
|
|
952
|
+
model = next(
|
|
953
|
+
(name for name in model_names if "qwen2.5-coder" in name.lower()),
|
|
954
|
+
model_names[0],
|
|
955
|
+
)
|
|
956
|
+
print(f"Using Ollama model: {model}")
|
|
957
|
+
|
|
958
|
+
return {
|
|
959
|
+
"base_url": LOCAL_BASE_URL,
|
|
960
|
+
"api_key": LOCAL_API_KEY,
|
|
961
|
+
"model": model or DEFAULT_LOCAL_MODEL,
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
def _ollama_is_available() -> bool:
|
|
966
|
+
try:
|
|
967
|
+
response = httpx.get(LOCAL_TAGS_URL, timeout=1.0)
|
|
968
|
+
except httpx.HTTPError:
|
|
969
|
+
return False
|
|
970
|
+
return response.status_code == 200
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _local_request_error(
|
|
974
|
+
error: Exception,
|
|
975
|
+
) -> RuntimeError | None:
|
|
976
|
+
status_code = getattr(error, "status_code", None)
|
|
977
|
+
if status_code == 404:
|
|
978
|
+
return RuntimeError(
|
|
979
|
+
"The Ollama model was not found (HTTP 404). Install the model and retry."
|
|
980
|
+
)
|
|
981
|
+
if status_code == 500:
|
|
982
|
+
return RuntimeError(
|
|
983
|
+
"Ollama failed to load the model (HTTP 500); check available memory."
|
|
984
|
+
)
|
|
985
|
+
if isinstance(error, (APIConnectionError, httpx.TransportError, ConnectionError, TimeoutError)):
|
|
986
|
+
return RuntimeError(
|
|
987
|
+
"Could not connect to Ollama at localhost:11434. "
|
|
988
|
+
"Ensure Ollama is installed and running."
|
|
989
|
+
)
|
|
990
|
+
return None
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _cloud_failure_with_local_option(
|
|
994
|
+
error: Exception,
|
|
995
|
+
local_error: Exception | None = None,
|
|
996
|
+
) -> RuntimeError:
|
|
997
|
+
status_code = getattr(error, "status_code", None)
|
|
998
|
+
detail = f" (HTTP {status_code})" if status_code is not None else ""
|
|
999
|
+
message = f"Cloud AI request failed{detail}."
|
|
1000
|
+
if local_error:
|
|
1001
|
+
message = f"{message} {local_error}"
|
|
1002
|
+
return RuntimeError(message)
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
def _completion_requester(cfg: dict, local: bool):
|
|
1006
|
+
state = {
|
|
1007
|
+
"client": OpenAI(base_url=cfg["base_url"], api_key=cfg["api_key"]),
|
|
1008
|
+
"model": cfg["model"],
|
|
1009
|
+
"using_local": local,
|
|
1010
|
+
"tried_models": {cfg["model"]},
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
def request_completion(
|
|
1014
|
+
request_messages: list[dict],
|
|
1015
|
+
*,
|
|
1016
|
+
max_tokens: int | None = None,
|
|
1017
|
+
) -> str:
|
|
1018
|
+
short_rate_retry_used = False
|
|
1019
|
+
model_switches = 0
|
|
1020
|
+
for attempt in range(5):
|
|
1021
|
+
try:
|
|
1022
|
+
if not state["using_local"]:
|
|
1023
|
+
_wait_for_shared_rate_limit()
|
|
1024
|
+
_pace_cloud_request()
|
|
1025
|
+
_wait_for_shared_rate_limit()
|
|
1026
|
+
return _call_chat_completion(
|
|
1027
|
+
state["client"],
|
|
1028
|
+
state["model"],
|
|
1029
|
+
request_messages,
|
|
1030
|
+
local=state["using_local"],
|
|
1031
|
+
max_tokens=max_tokens,
|
|
1032
|
+
)
|
|
1033
|
+
except Exception as error:
|
|
1034
|
+
if state["using_local"]:
|
|
1035
|
+
local_error = _local_request_error(error)
|
|
1036
|
+
if local_error:
|
|
1037
|
+
raise local_error from error
|
|
1038
|
+
raise
|
|
1039
|
+
status_code = getattr(error, "status_code", None)
|
|
1040
|
+
retry_after = _retry_after_seconds(error) if status_code == 429 else None
|
|
1041
|
+
if (
|
|
1042
|
+
status_code == 429
|
|
1043
|
+
and retry_after is not None
|
|
1044
|
+
and retry_after <= 3
|
|
1045
|
+
and not short_rate_retry_used
|
|
1046
|
+
):
|
|
1047
|
+
short_rate_retry_used = True
|
|
1048
|
+
wait_seconds, scheduled = _schedule_shared_rate_limit(retry_after)
|
|
1049
|
+
if scheduled and _claim_rate_limit_notice():
|
|
1050
|
+
print(
|
|
1051
|
+
f"Cloud API rate limited; retrying in "
|
|
1052
|
+
f"{wait_seconds:g} seconds."
|
|
1053
|
+
)
|
|
1054
|
+
_wait_for_shared_rate_limit()
|
|
1055
|
+
continue
|
|
1056
|
+
should_recover_model = (
|
|
1057
|
+
status_code in {400, 404}
|
|
1058
|
+
or status_code == 429
|
|
1059
|
+
)
|
|
1060
|
+
if (
|
|
1061
|
+
should_recover_model
|
|
1062
|
+
and model_switches < 3
|
|
1063
|
+
and _uses_groq(cfg)
|
|
1064
|
+
):
|
|
1065
|
+
next_model = _next_live_groq_model(cfg, state["tried_models"])
|
|
1066
|
+
if next_model:
|
|
1067
|
+
previous_model = state["model"]
|
|
1068
|
+
state["model"] = next_model
|
|
1069
|
+
state["tried_models"].add(next_model)
|
|
1070
|
+
model_switches += 1
|
|
1071
|
+
if _claim_rate_limit_notice():
|
|
1072
|
+
print(
|
|
1073
|
+
f"Groq request returned HTTP {status_code}; "
|
|
1074
|
+
f"switching model from {previous_model} to "
|
|
1075
|
+
f"{next_model}."
|
|
1076
|
+
)
|
|
1077
|
+
continue
|
|
1078
|
+
|
|
1079
|
+
if not _is_local_fallback_error(error):
|
|
1080
|
+
raise
|
|
1081
|
+
if not _ollama_is_available():
|
|
1082
|
+
raise _cloud_failure_with_local_option(error) from error
|
|
1083
|
+
|
|
1084
|
+
try:
|
|
1085
|
+
local_cfg = _local_config()
|
|
1086
|
+
except RuntimeError as local_error:
|
|
1087
|
+
raise _cloud_failure_with_local_option(
|
|
1088
|
+
error,
|
|
1089
|
+
local_error,
|
|
1090
|
+
) from error
|
|
1091
|
+
|
|
1092
|
+
status_code = getattr(error, "status_code", None)
|
|
1093
|
+
detail = (
|
|
1094
|
+
f"HTTP {status_code}"
|
|
1095
|
+
if status_code is not None
|
|
1096
|
+
else "connection error"
|
|
1097
|
+
)
|
|
1098
|
+
print(f"Cloud request failed ({detail}); switching to local Ollama.")
|
|
1099
|
+
state["client"] = OpenAI(
|
|
1100
|
+
base_url=local_cfg["base_url"],
|
|
1101
|
+
api_key=local_cfg["api_key"],
|
|
1102
|
+
)
|
|
1103
|
+
state["model"] = local_cfg["model"]
|
|
1104
|
+
state["using_local"] = True
|
|
1105
|
+
try:
|
|
1106
|
+
return _call_chat_completion(
|
|
1107
|
+
state["client"],
|
|
1108
|
+
state["model"],
|
|
1109
|
+
request_messages,
|
|
1110
|
+
local=True,
|
|
1111
|
+
)
|
|
1112
|
+
except Exception as local_error:
|
|
1113
|
+
parsed_error = _local_request_error(local_error)
|
|
1114
|
+
if parsed_error:
|
|
1115
|
+
raise parsed_error from local_error
|
|
1116
|
+
raise
|
|
1117
|
+
raise RuntimeError("AI analysis failed after 5 attempts.")
|
|
1118
|
+
|
|
1119
|
+
return request_completion, state
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _system_prompt(prompt: str) -> str:
|
|
1123
|
+
language_instruction = (
|
|
1124
|
+
"Write all triage explanations, summaries, and reasoning in English. "
|
|
1125
|
+
"Keep code, JSON keys, severity values, and identifiers unchanged."
|
|
1126
|
+
)
|
|
1127
|
+
return f"{prompt.rstrip()}\n\n{language_instruction}"
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def analyze_finding(
|
|
1131
|
+
finding: dict,
|
|
1132
|
+
local: bool = False,
|
|
1133
|
+
) -> dict | None:
|
|
1134
|
+
"""Submit a finding to the selected AI engine and validate its verdict."""
|
|
1135
|
+
cfg = _local_config() if local else load_config()
|
|
1136
|
+
if not cfg:
|
|
1137
|
+
raise RuntimeError("AI configuration was not found. Run 'secguard config' first.")
|
|
1138
|
+
request_completion, _ = _completion_requester(cfg, local)
|
|
1139
|
+
|
|
1140
|
+
code_language = _detect_language(finding["file"])
|
|
1141
|
+
context = finding.get("context", "")
|
|
1142
|
+
function_context = str(finding.get("function_context", ""))
|
|
1143
|
+
call_chain = str(finding.get("call_chain", ""))
|
|
1144
|
+
if function_context:
|
|
1145
|
+
context = f"{context}\n\nSurrounding function:\n{function_context}"
|
|
1146
|
+
if call_chain:
|
|
1147
|
+
context = f"{context}\n\nCross-file call chain:\n{call_chain}"
|
|
1148
|
+
full_source = _read_full_source(finding)
|
|
1149
|
+
|
|
1150
|
+
source_excerpt = _read_source_excerpt(finding)
|
|
1151
|
+
full_file_section = ""
|
|
1152
|
+
if source_excerpt and source_excerpt.strip() != context.strip():
|
|
1153
|
+
full_file_section = f"\n\nAdditional source context:\n{source_excerpt}"
|
|
1154
|
+
|
|
1155
|
+
user_content = (
|
|
1156
|
+
f"File: {finding['file']}\n"
|
|
1157
|
+
f"Language: {code_language}\n"
|
|
1158
|
+
f"Encoding: {finding.get('encoding', 'unknown')}\n"
|
|
1159
|
+
f"Issue: {finding['issue']}\n"
|
|
1160
|
+
f"Line: {finding['line']}\n"
|
|
1161
|
+
f"Code:\n{finding['code']}\n\n"
|
|
1162
|
+
f"Context:\n{context}"
|
|
1163
|
+
f"{full_file_section}"
|
|
1164
|
+
)
|
|
1165
|
+
|
|
1166
|
+
messages = [
|
|
1167
|
+
{"role": "system", "content": _system_prompt(SYSTEM_PROMPT)},
|
|
1168
|
+
{"role": "user", "content": user_content},
|
|
1169
|
+
]
|
|
1170
|
+
|
|
1171
|
+
raw_text = request_completion(messages)
|
|
1172
|
+
result, feedback = _validate_with_feedback(
|
|
1173
|
+
raw_text,
|
|
1174
|
+
context,
|
|
1175
|
+
full_source,
|
|
1176
|
+
code_language,
|
|
1177
|
+
str(finding.get("issue", "")),
|
|
1178
|
+
)
|
|
1179
|
+
if result is not None:
|
|
1180
|
+
return _apply_finding_policy(finding, result, code_language)
|
|
1181
|
+
|
|
1182
|
+
messages.append({"role": "assistant", "content": raw_text})
|
|
1183
|
+
messages.append({
|
|
1184
|
+
"role": "user",
|
|
1185
|
+
"content": (
|
|
1186
|
+
f"The response failed validation: {feedback}\n"
|
|
1187
|
+
"Correct the response and return only valid JSON matching the required schema."
|
|
1188
|
+
),
|
|
1189
|
+
})
|
|
1190
|
+
retry_text = request_completion(messages)
|
|
1191
|
+
retry_result, retry_feedback = _validate_with_feedback(
|
|
1192
|
+
retry_text,
|
|
1193
|
+
context,
|
|
1194
|
+
full_source,
|
|
1195
|
+
code_language,
|
|
1196
|
+
str(finding.get("issue", "")),
|
|
1197
|
+
)
|
|
1198
|
+
if retry_result is not None:
|
|
1199
|
+
return _apply_finding_policy(finding, retry_result, code_language)
|
|
1200
|
+
return (
|
|
1201
|
+
_preserve_rejected_patch_finding(
|
|
1202
|
+
finding,
|
|
1203
|
+
retry_text,
|
|
1204
|
+
retry_feedback,
|
|
1205
|
+
context,
|
|
1206
|
+
full_source,
|
|
1207
|
+
code_language,
|
|
1208
|
+
)
|
|
1209
|
+
or _preserve_rejected_patch_finding(
|
|
1210
|
+
finding,
|
|
1211
|
+
raw_text,
|
|
1212
|
+
feedback,
|
|
1213
|
+
context,
|
|
1214
|
+
full_source,
|
|
1215
|
+
code_language,
|
|
1216
|
+
)
|
|
1217
|
+
)
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def _read_finding_code_window(
|
|
1221
|
+
finding: dict,
|
|
1222
|
+
source_text: str | None = None,
|
|
1223
|
+
) -> str:
|
|
1224
|
+
try:
|
|
1225
|
+
target_line = max(1, int(finding.get("line", 1)))
|
|
1226
|
+
except (TypeError, ValueError):
|
|
1227
|
+
target_line = 1
|
|
1228
|
+
|
|
1229
|
+
abs_path = finding.get("abs_path")
|
|
1230
|
+
if abs_path and not finding.get("is_binary"):
|
|
1231
|
+
start_line = max(1, target_line - 12)
|
|
1232
|
+
end_line = target_line + 12
|
|
1233
|
+
try:
|
|
1234
|
+
if source_text is None:
|
|
1235
|
+
source_text, _ = decode_source_bytes(Path(abs_path).read_bytes())
|
|
1236
|
+
lines = source_text.splitlines()
|
|
1237
|
+
import_lines = [
|
|
1238
|
+
f"{number}: {line[:180]}"
|
|
1239
|
+
for number, line in enumerate(lines[:20], start=1)
|
|
1240
|
+
if re.match(
|
|
1241
|
+
r"^\s*(?:from\s+\S+\s+import\b|import\s+|"
|
|
1242
|
+
r"(?:const|let|var)\s+.*\s+from\s+|require\s*\(|"
|
|
1243
|
+
r"<\?php|use\s+[\w\\]+;)",
|
|
1244
|
+
line,
|
|
1245
|
+
)
|
|
1246
|
+
][:8]
|
|
1247
|
+
window = [
|
|
1248
|
+
f"{number}: {lines[number - 1][:180]}"
|
|
1249
|
+
for number in range(start_line, min(end_line, len(lines)) + 1)
|
|
1250
|
+
]
|
|
1251
|
+
sections = []
|
|
1252
|
+
if import_lines:
|
|
1253
|
+
sections.append("Imports: " + " | ".join(import_lines))
|
|
1254
|
+
if window:
|
|
1255
|
+
sections.append("Source: " + " | ".join(window))
|
|
1256
|
+
function_context = str(finding.get("function_context", ""))
|
|
1257
|
+
call_chain = str(finding.get("call_chain", ""))
|
|
1258
|
+
if function_context:
|
|
1259
|
+
sections.append(f"Function: {function_context[:500]}")
|
|
1260
|
+
if call_chain:
|
|
1261
|
+
sections.append(f"Call chain: {call_chain[:500]}")
|
|
1262
|
+
if sections:
|
|
1263
|
+
return "\n".join(sections)[:3200]
|
|
1264
|
+
except OSError:
|
|
1265
|
+
pass
|
|
1266
|
+
|
|
1267
|
+
context = str(finding.get("context", "")).splitlines()
|
|
1268
|
+
if context:
|
|
1269
|
+
first_line = max(1, target_line - 12)
|
|
1270
|
+
window = "\n".join(
|
|
1271
|
+
f"{first_line + offset}: {line[:180]}"
|
|
1272
|
+
for offset, line in enumerate(context[:25])
|
|
1273
|
+
)
|
|
1274
|
+
return window[:3200]
|
|
1275
|
+
return str(finding.get("code", ""))[:300]
|
|
1276
|
+
|
|
1277
|
+
|
|
1278
|
+
def _batch_context_header(index: int, finding: dict) -> str:
|
|
1279
|
+
return f"[finding {index} | {finding.get('file', '')}:{finding.get('line', 1)}]"
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def _batch_context_size(findings: list[dict], windows: list[str]) -> int:
|
|
1283
|
+
return sum(
|
|
1284
|
+
len(_batch_context_header(index, finding)) + len(window) + 1
|
|
1285
|
+
for index, (finding, window) in enumerate(zip(findings, windows))
|
|
1286
|
+
) + max(0, len(findings) - 1) * 2
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _render_batch_context(findings: list[dict], windows: list[str]) -> str:
|
|
1290
|
+
blocks = []
|
|
1291
|
+
remaining = min(12000, max(3200, len(findings) * 750))
|
|
1292
|
+
for position, (finding, window) in enumerate(zip(findings, windows)):
|
|
1293
|
+
index = position
|
|
1294
|
+
separator = "\n\n" if blocks else ""
|
|
1295
|
+
header = _batch_context_header(index, finding)
|
|
1296
|
+
remaining_findings = len(findings) - position
|
|
1297
|
+
available = max(
|
|
1298
|
+
0,
|
|
1299
|
+
min(
|
|
1300
|
+
remaining - len(separator) - len(header) - 1,
|
|
1301
|
+
max(250, remaining // max(1, remaining_findings) - len(header) - 1),
|
|
1302
|
+
),
|
|
1303
|
+
)
|
|
1304
|
+
block = f"{header}\n{window[:available]}"
|
|
1305
|
+
blocks.append(block)
|
|
1306
|
+
remaining -= len(separator) + len(block)
|
|
1307
|
+
return "\n\n".join(blocks)
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def _analyze_finding_batch(
|
|
1311
|
+
findings: list[dict],
|
|
1312
|
+
local: bool = False,
|
|
1313
|
+
context_windows: list[str] | None = None,
|
|
1314
|
+
) -> list[dict | None]:
|
|
1315
|
+
cfg = _local_config() if local else load_config()
|
|
1316
|
+
if not cfg:
|
|
1317
|
+
raise RuntimeError("AI configuration was not found. Run 'secguard config' first.")
|
|
1318
|
+
request_completion, state = _completion_requester(cfg, local=local)
|
|
1319
|
+
|
|
1320
|
+
if context_windows is None:
|
|
1321
|
+
context_windows = [_read_finding_code_window(finding) for finding in findings]
|
|
1322
|
+
labeled_context = _render_batch_context(findings, context_windows)
|
|
1323
|
+
|
|
1324
|
+
batch_items = [
|
|
1325
|
+
{
|
|
1326
|
+
"index": index,
|
|
1327
|
+
"file": finding.get("file", ""),
|
|
1328
|
+
"line": finding.get("line"),
|
|
1329
|
+
"language": _detect_language(finding.get("file", "")),
|
|
1330
|
+
"issue": finding.get("issue", ""),
|
|
1331
|
+
"code": finding.get("code", ""),
|
|
1332
|
+
}
|
|
1333
|
+
for index, finding in enumerate(findings)
|
|
1334
|
+
]
|
|
1335
|
+
user_content = (
|
|
1336
|
+
"Evaluate these findings against the supplied code context. "
|
|
1337
|
+
"Return only a JSON array in the required format.\n\n"
|
|
1338
|
+
f"Code context:\n{labeled_context}\n\n"
|
|
1339
|
+
"Findings:\n"
|
|
1340
|
+
f"{json.dumps(batch_items, ensure_ascii=False)}"
|
|
1341
|
+
)
|
|
1342
|
+
raw_text = request_completion(
|
|
1343
|
+
[
|
|
1344
|
+
{
|
|
1345
|
+
"role": "system",
|
|
1346
|
+
"content": _system_prompt(BATCH_SYSTEM_PROMPT),
|
|
1347
|
+
},
|
|
1348
|
+
{"role": "user", "content": user_content},
|
|
1349
|
+
],
|
|
1350
|
+
max_tokens=min(1800, 240 + 110 * len(findings)),
|
|
1351
|
+
)
|
|
1352
|
+
|
|
1353
|
+
parsed = _extract_json_list(raw_text)
|
|
1354
|
+
indexed_results = {}
|
|
1355
|
+
source_cache: dict[str, str] = {}
|
|
1356
|
+
if parsed is not None:
|
|
1357
|
+
for result in parsed:
|
|
1358
|
+
if not isinstance(result, dict):
|
|
1359
|
+
continue
|
|
1360
|
+
index = result.get("index")
|
|
1361
|
+
if type(index) is not int or not 0 <= index < len(findings):
|
|
1362
|
+
continue
|
|
1363
|
+
is_vulnerable = result.get("is_vulnerable")
|
|
1364
|
+
if is_vulnerable is False:
|
|
1365
|
+
if index not in indexed_results:
|
|
1366
|
+
indexed_results[index] = {
|
|
1367
|
+
"index": index,
|
|
1368
|
+
"is_vulnerable": False,
|
|
1369
|
+
"severity": "LOW",
|
|
1370
|
+
"title": "",
|
|
1371
|
+
"explanation": "",
|
|
1372
|
+
"vulnerable_code": "",
|
|
1373
|
+
"fixed_code": "",
|
|
1374
|
+
"suggested_fix": "",
|
|
1375
|
+
"cwe": "",
|
|
1376
|
+
}
|
|
1377
|
+
continue
|
|
1378
|
+
|
|
1379
|
+
severity = result.get("severity")
|
|
1380
|
+
title = result.get("title")
|
|
1381
|
+
description = result.get("description")
|
|
1382
|
+
fix = result.get("fix")
|
|
1383
|
+
issue = str(findings[index].get("issue", ""))
|
|
1384
|
+
language = _detect_language(findings[index].get("file", ""))
|
|
1385
|
+
abs_path = str(findings[index].get("abs_path") or "")
|
|
1386
|
+
if abs_path and abs_path not in source_cache:
|
|
1387
|
+
source_cache[abs_path] = _read_full_source(findings[index])
|
|
1388
|
+
clean_fix = (
|
|
1389
|
+
_clean_patch_text(fix, source_cache.get(abs_path, ""), language)
|
|
1390
|
+
if isinstance(fix, str)
|
|
1391
|
+
else fix
|
|
1392
|
+
)
|
|
1393
|
+
patch_feedback = (
|
|
1394
|
+
_unsafe_patch_feedback(clean_fix, language, issue)
|
|
1395
|
+
if isinstance(clean_fix, str)
|
|
1396
|
+
else ""
|
|
1397
|
+
)
|
|
1398
|
+
if (
|
|
1399
|
+
is_vulnerable is not True
|
|
1400
|
+
or not isinstance(severity, str)
|
|
1401
|
+
or severity.upper() not in {"CRITICAL", "HIGH", "MEDIUM", "LOW"}
|
|
1402
|
+
or not all(isinstance(value, str) for value in (title, description, clean_fix))
|
|
1403
|
+
):
|
|
1404
|
+
continue
|
|
1405
|
+
if patch_feedback:
|
|
1406
|
+
clean_fix = _safe_patch_fallback(
|
|
1407
|
+
issue,
|
|
1408
|
+
findings[index].get("code", ""),
|
|
1409
|
+
)
|
|
1410
|
+
description = (
|
|
1411
|
+
f"{description} The proposed patch was rejected by safety checks; "
|
|
1412
|
+
"do not repeat unsafe code."
|
|
1413
|
+
)
|
|
1414
|
+
if _requires_critical_severity(issue):
|
|
1415
|
+
severity = "CRITICAL"
|
|
1416
|
+
if "cors" in issue.casefold():
|
|
1417
|
+
title = "Unsafe CORS Configuration"
|
|
1418
|
+
if index not in indexed_results:
|
|
1419
|
+
indexed_results[index] = {
|
|
1420
|
+
**result,
|
|
1421
|
+
"severity": severity.upper(),
|
|
1422
|
+
"explanation": description,
|
|
1423
|
+
"fixed_code": clean_fix,
|
|
1424
|
+
"suggested_fix": clean_fix,
|
|
1425
|
+
"vulnerable_code": findings[index].get("code", ""),
|
|
1426
|
+
"cwe": "",
|
|
1427
|
+
"patch_applicable": not clean_fix.startswith(
|
|
1428
|
+
PATCH_VALIDATION_FAILED
|
|
1429
|
+
),
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
verdicts = []
|
|
1433
|
+
for index, finding in enumerate(findings):
|
|
1434
|
+
verdict = indexed_results.get(index)
|
|
1435
|
+
if verdict is None:
|
|
1436
|
+
verdicts.append(None)
|
|
1437
|
+
continue
|
|
1438
|
+
if verdict.get("is_vulnerable") and verdict.get("fixed_code"):
|
|
1439
|
+
verdict.setdefault("suggested_fix", verdict["fixed_code"])
|
|
1440
|
+
verdicts.append(
|
|
1441
|
+
_apply_finding_policy(
|
|
1442
|
+
finding,
|
|
1443
|
+
verdict,
|
|
1444
|
+
_detect_language(finding.get("file", "")),
|
|
1445
|
+
)
|
|
1446
|
+
)
|
|
1447
|
+
return verdicts
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def analyze_findings(
|
|
1451
|
+
findings: list[dict],
|
|
1452
|
+
local: bool = False,
|
|
1453
|
+
) -> list[dict | None]:
|
|
1454
|
+
"""Analyze findings in bounded cross-file batches while preserving order."""
|
|
1455
|
+
if not findings:
|
|
1456
|
+
return []
|
|
1457
|
+
|
|
1458
|
+
results: list[dict | None] = [None] * len(findings)
|
|
1459
|
+
uncached_indexes = []
|
|
1460
|
+
for index, finding in enumerate(findings):
|
|
1461
|
+
fixed_code = finding.get("fixed_code") or finding.get("suggested_fix")
|
|
1462
|
+
if type(finding.get("is_vulnerable")) is bool and (
|
|
1463
|
+
not finding["is_vulnerable"]
|
|
1464
|
+
or (
|
|
1465
|
+
isinstance(fixed_code, str)
|
|
1466
|
+
and fixed_code.strip()
|
|
1467
|
+
and finding.get("patch_applicable") is not False
|
|
1468
|
+
)
|
|
1469
|
+
):
|
|
1470
|
+
verdict = {
|
|
1471
|
+
key: value
|
|
1472
|
+
for key, value in finding.items()
|
|
1473
|
+
if key in {
|
|
1474
|
+
"is_vulnerable", "severity", "title", "explanation",
|
|
1475
|
+
"vulnerable_code", "cwe", "patch_applicable",
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
verdict["fixed_code"] = fixed_code or ""
|
|
1479
|
+
verdict["suggested_fix"] = fixed_code or ""
|
|
1480
|
+
results[index] = _apply_finding_policy(
|
|
1481
|
+
finding,
|
|
1482
|
+
verdict,
|
|
1483
|
+
_detect_language(finding.get("file", "")),
|
|
1484
|
+
)
|
|
1485
|
+
else:
|
|
1486
|
+
uncached_indexes.append(index)
|
|
1487
|
+
|
|
1488
|
+
grouped_indexes: dict[str, list[int]] = {}
|
|
1489
|
+
for index in uncached_indexes:
|
|
1490
|
+
finding = findings[index]
|
|
1491
|
+
file_key = str(finding.get("abs_path") or finding.get("file") or index)
|
|
1492
|
+
grouped_indexes.setdefault(file_key, []).append(index)
|
|
1493
|
+
|
|
1494
|
+
batch_indexes = []
|
|
1495
|
+
for indexes in grouped_indexes.values():
|
|
1496
|
+
for start in range(0, len(indexes), 15):
|
|
1497
|
+
batch_indexes.append(indexes[start:start + 15])
|
|
1498
|
+
source_cache: dict[str, str] = {}
|
|
1499
|
+
windows = {}
|
|
1500
|
+
for index in uncached_indexes:
|
|
1501
|
+
finding = findings[index]
|
|
1502
|
+
abs_path = str(finding.get("abs_path") or "")
|
|
1503
|
+
if abs_path and abs_path not in source_cache:
|
|
1504
|
+
try:
|
|
1505
|
+
source_cache[abs_path], _ = decode_source_bytes(
|
|
1506
|
+
Path(abs_path).read_bytes()
|
|
1507
|
+
)
|
|
1508
|
+
except OSError:
|
|
1509
|
+
source_cache[abs_path] = ""
|
|
1510
|
+
windows[index] = _read_finding_code_window(
|
|
1511
|
+
finding,
|
|
1512
|
+
source_cache.get(abs_path) if abs_path else None,
|
|
1513
|
+
)
|
|
1514
|
+
|
|
1515
|
+
with ThreadPoolExecutor(max_workers=1 if local else 2) as executor:
|
|
1516
|
+
futures = {
|
|
1517
|
+
executor.submit(
|
|
1518
|
+
_analyze_finding_batch,
|
|
1519
|
+
[findings[index] for index in indexes],
|
|
1520
|
+
local,
|
|
1521
|
+
[windows[index] for index in indexes],
|
|
1522
|
+
): indexes
|
|
1523
|
+
for indexes in batch_indexes
|
|
1524
|
+
}
|
|
1525
|
+
for future in as_completed(futures):
|
|
1526
|
+
indexes = futures[future]
|
|
1527
|
+
verdicts = future.result()
|
|
1528
|
+
for index, verdict in zip(indexes, verdicts):
|
|
1529
|
+
results[index] = verdict
|
|
1530
|
+
return results
|
|
1531
|
+
|
|
1532
|
+
|
|
1533
|
+
def analyze_url_report(report: dict) -> dict | None:
|
|
1534
|
+
"""Request an AI analysis of the web scan report."""
|
|
1535
|
+
cfg = load_config()
|
|
1536
|
+
if not cfg:
|
|
1537
|
+
raise RuntimeError("AI configuration was not found. Run 'secguard config' first.")
|
|
1538
|
+
|
|
1539
|
+
client = OpenAI(base_url=cfg["base_url"], api_key=cfg["api_key"])
|
|
1540
|
+
user_content = (
|
|
1541
|
+
"Web security scan data:\n"
|
|
1542
|
+
f"{json.dumps(report, indent=2, ensure_ascii=False)}"
|
|
1543
|
+
)
|
|
1544
|
+
|
|
1545
|
+
raw_text = _call_chat_completion(
|
|
1546
|
+
client,
|
|
1547
|
+
cfg["model"],
|
|
1548
|
+
[
|
|
1549
|
+
{
|
|
1550
|
+
"role": "system",
|
|
1551
|
+
"content": _system_prompt(WEB_SYSTEM_PROMPT),
|
|
1552
|
+
},
|
|
1553
|
+
{"role": "user", "content": user_content},
|
|
1554
|
+
],
|
|
1555
|
+
)
|
|
1556
|
+
return _extract_json_dict(raw_text)
|