feat: Add LLM analysis workflow and ruff linter fixes

LLM Analysis Workflow:
- Add llm_analyzer module for AI-powered code security analysis
- Add llm_analysis workflow with SARIF output support
- Mount AI module in Python worker for A2A wrapper access
- Add a2a-sdk dependency to Python worker requirements
- Fix workflow parameter ordering in Temporal manager

Ruff Linter Fixes:
- Fix bare except clauses (E722) across AI and CLI modules
- Add noqa comments for intentional late imports (E402)
- Replace undefined get_ai_status_async with TODO placeholder
- Remove unused imports and variables
- Remove container diagnostics display from exception handler

MCP Configuration:
- Reactivate FUZZFORGE_MCP_URL with default value
- Set default MCP URL to http://localhost:8010/mcp in init
This commit is contained in:
tduhamel42
2025-10-14 16:43:14 +02:00
parent dabbcf3718
commit 4d30b08476
23 changed files with 882 additions and 74 deletions
@@ -0,0 +1,19 @@
"""
LLM Analysis Workflow
"""
# Copyright (c) 2025 FuzzingLabs
#
# Licensed under the Business Source License 1.1 (BSL). See the LICENSE file
# at the root of this repository for details.
#
# After the Change Date (four years from publication), this version of the
# Licensed Work will be made available under the Apache License, Version 2.0.
# See the LICENSE-APACHE file or http://www.apache.org/licenses/LICENSE-2.0
#
# Additional attribution and requirements are provided in the NOTICE file.
from .workflow import LlmAnalysisWorkflow
from .activities import analyze_with_llm
__all__ = ["LlmAnalysisWorkflow", "analyze_with_llm"]
@@ -0,0 +1,162 @@
"""
LLM Analysis Workflow Activities
"""
# Copyright (c) 2025 FuzzingLabs
#
# Licensed under the Business Source License 1.1 (BSL). See the LICENSE file
# at the root of this repository for details.
#
# After the Change Date (four years from publication), this version of the
# Licensed Work will be made available under the Apache License, Version 2.0.
# See the LICENSE-APACHE file or http://www.apache.org/licenses/LICENSE-2.0
#
# Additional attribution and requirements are provided in the NOTICE file.
import logging
from pathlib import Path
from typing import Dict, Any
from temporalio import activity
try:
from toolbox.modules.analyzer.llm_analyzer import LLMAnalyzer
except ImportError:
try:
from modules.analyzer.llm_analyzer import LLMAnalyzer
except ImportError:
from src.toolbox.modules.analyzer.llm_analyzer import LLMAnalyzer
logger = logging.getLogger(__name__)
@activity.defn(name="llm_generate_sarif")
async def llm_generate_sarif(findings: list, metadata: Dict[str, Any]) -> Dict[str, Any]:
"""
Generate SARIF report from LLM findings.
Args:
findings: List of finding dictionaries
metadata: Metadata including tool_name, tool_version, run_id
Returns:
SARIF report dictionary
"""
activity.logger.info(f"Generating SARIF report from {len(findings)} findings")
# Basic SARIF 2.1.0 structure
sarif_report = {
"version": "2.1.0",
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
"runs": [
{
"tool": {
"driver": {
"name": metadata.get("tool_name", "llm-analyzer"),
"version": metadata.get("tool_version", "1.0.0"),
"informationUri": "https://github.com/FuzzingLabs/fuzzforge_ai"
}
},
"results": []
}
]
}
# Convert findings to SARIF results
for finding in findings:
sarif_result = {
"ruleId": finding.get("id", "unknown"),
"level": _severity_to_sarif_level(finding.get("severity", "warning")),
"message": {
"text": finding.get("title", "Security issue detected")
},
"locations": []
}
# Add description if present
if finding.get("description"):
sarif_result["message"]["markdown"] = finding["description"]
# Add location if file path is present
if finding.get("file_path"):
location = {
"physicalLocation": {
"artifactLocation": {
"uri": finding["file_path"]
}
}
}
# Add region if line number is present
if finding.get("line_start"):
location["physicalLocation"]["region"] = {
"startLine": finding["line_start"]
}
if finding.get("line_end"):
location["physicalLocation"]["region"]["endLine"] = finding["line_end"]
sarif_result["locations"].append(location)
sarif_report["runs"][0]["results"].append(sarif_result)
activity.logger.info(f"Generated SARIF report with {len(sarif_report['runs'][0]['results'])} results")
return sarif_report
def _severity_to_sarif_level(severity: str) -> str:
"""Convert severity to SARIF level"""
severity_map = {
"critical": "error",
"high": "error",
"medium": "warning",
"low": "note",
"info": "note"
}
return severity_map.get(severity.lower(), "warning")
@activity.defn(name="analyze_with_llm")
async def analyze_with_llm(target_path: str, config: Dict[str, Any]) -> Dict[str, Any]:
"""
Analyze code using LLM.
Args:
target_path: Path to the workspace containing code
config: LLM analyzer configuration
Returns:
Dictionary containing findings and summary
"""
activity.logger.info(f"Starting LLM analysis: {target_path}")
activity.logger.info(f"Config: {config}")
workspace = Path(target_path)
if not workspace.exists():
raise FileNotFoundError(f"Workspace not found: {target_path}")
# Create and execute LLM analyzer
analyzer = LLMAnalyzer()
# Validate configuration
analyzer.validate_config(config)
# Execute analysis
result = await analyzer.execute(config, workspace)
if result.status == "failed":
raise RuntimeError(f"LLM analysis failed: {result.error or 'Unknown error'}")
activity.logger.info(
f"LLM analysis completed: {len(result.findings)} findings from "
f"{result.summary.get('files_analyzed', 0)} files"
)
# Convert ModuleFinding objects to dicts for serialization
findings_dicts = [finding.model_dump() for finding in result.findings]
return {
"findings": findings_dicts,
"summary": result.summary
}
@@ -0,0 +1,64 @@
name: llm_analysis
version: "1.0.0"
vertical: python
description: "Uses AI/LLM to analyze code for security vulnerabilities and code quality issues"
author: "FuzzForge Team"
tags:
- "llm"
- "ai"
- "security"
- "static-analysis"
- "code-quality"
# Workspace isolation mode
workspace_isolation: "shared"
default_parameters:
agent_url: "http://fuzzforge-task-agent:8000/a2a/litellm_agent"
llm_model: "gpt-4o-mini"
llm_provider: "openai"
max_files: 5
parameters:
type: object
properties:
agent_url:
type: string
description: "A2A agent endpoint URL"
llm_model:
type: string
description: "LLM model to use (e.g., gpt-4o-mini, claude-3-5-sonnet)"
llm_provider:
type: string
description: "LLM provider (openai, anthropic, etc.)"
file_patterns:
type: array
items:
type: string
description: "File patterns to analyze (e.g., ['*.py', '*.js'])"
max_files:
type: integer
description: "Maximum number of files to analyze"
max_file_size:
type: integer
description: "Maximum file size in bytes"
timeout:
type: integer
description: "Timeout per file in seconds"
output_schema:
type: object
properties:
sarif:
type: object
description: "SARIF-formatted security findings from LLM"
summary:
type: object
description: "Analysis summary"
properties:
files_analyzed:
type: integer
total_findings:
type: integer
model_used:
type: string
@@ -0,0 +1,236 @@
"""
LLM Analysis Workflow - Temporal Version
Uses AI/LLM to analyze code for security issues.
"""
# Copyright (c) 2025 FuzzingLabs
#
# Licensed under the Business Source License 1.1 (BSL). See the LICENSE file
# at the root of this repository for details.
#
# After the Change Date (four years from publication), this version of the
# Licensed Work will be made available under the Apache License, Version 2.0.
# See the LICENSE-APACHE file or http://www.apache.org/licenses/LICENSE-2.0
#
# Additional attribution and requirements are provided in the NOTICE file.
from datetime import timedelta
from typing import Dict, Any, Optional
from temporalio import workflow
from temporalio.common import RetryPolicy
# Import for type hints (will be executed by worker)
with workflow.unsafe.imports_passed_through():
import logging
logger = logging.getLogger(__name__)
@workflow.defn
class LlmAnalysisWorkflow:
"""
Analyze code using AI/LLM for security vulnerabilities.
User workflow:
1. User runs: ff workflow run llm_analysis .
2. CLI uploads project to MinIO
3. Worker downloads project
4. Worker calls LLM analyzer module
5. LLM analyzes code files and reports findings
6. Results returned in SARIF format
"""
@workflow.run
async def run(
self,
target_id: str, # MinIO UUID of uploaded user code
agent_url: Optional[str] = None,
llm_model: Optional[str] = None,
llm_provider: Optional[str] = None,
file_patterns: Optional[list] = None,
max_files: Optional[int] = None,
max_file_size: Optional[int] = None,
timeout: Optional[int] = None
) -> Dict[str, Any]:
"""
Main workflow execution.
Args:
target_id: UUID of the uploaded target in MinIO
agent_url: A2A agent endpoint URL
llm_model: LLM model to use
llm_provider: LLM provider
file_patterns: File patterns to analyze
max_files: Maximum number of files to analyze
max_file_size: Maximum file size in bytes
timeout: Timeout per file in seconds
Returns:
Dictionary containing findings and summary
"""
workflow_id = workflow.info().workflow_id
workflow.logger.info(
f"Starting LLMAnalysisWorkflow "
f"(workflow_id={workflow_id}, target_id={target_id}, model={llm_model})"
)
results = {
"workflow_id": workflow_id,
"target_id": target_id,
"status": "running",
"steps": [],
"findings": []
}
try:
# Get run ID for workspace isolation
run_id = workflow.info().run_id
# Step 1: Download user's project from MinIO
workflow.logger.info("Step 1: Downloading user code from MinIO")
target_path = await workflow.execute_activity(
"get_target",
args=[target_id, run_id, "shared"],
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
maximum_attempts=3
)
)
results["steps"].append({
"step": "download",
"status": "success",
"target_path": target_path
})
workflow.logger.info(f"✓ Target downloaded to: {target_path}")
# Step 2: Run LLM analysis
workflow.logger.info("Step 2: Analyzing code with LLM")
# Build analyzer config
analyzer_config = {}
if agent_url:
analyzer_config["agent_url"] = agent_url
if llm_model:
analyzer_config["llm_model"] = llm_model
if llm_provider:
analyzer_config["llm_provider"] = llm_provider
if file_patterns:
analyzer_config["file_patterns"] = file_patterns
if max_files is not None:
analyzer_config["max_files"] = max_files
if max_file_size is not None:
analyzer_config["max_file_size"] = max_file_size
if timeout is not None:
analyzer_config["timeout"] = timeout
analysis_results = await workflow.execute_activity(
"analyze_with_llm",
args=[target_path, analyzer_config],
start_to_close_timeout=timedelta(minutes=30), # LLM calls can be slow
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=5),
maximum_interval=timedelta(minutes=1),
maximum_attempts=2
)
)
findings = analysis_results.get("findings", [])
summary = analysis_results.get("summary", {})
results["steps"].append({
"step": "llm_analysis",
"status": "success",
"files_analyzed": summary.get("files_analyzed", 0),
"findings_count": len(findings)
})
workflow.logger.info(
f"✓ LLM analysis completed: "
f"{summary.get('files_analyzed', 0)} files, "
f"{len(findings)} findings"
)
# Step 3: Generate SARIF report
workflow.logger.info("Step 3: Generating SARIF report")
sarif_report = await workflow.execute_activity(
"llm_generate_sarif",
args=[findings, {
"tool_name": "llm-analyzer",
"tool_version": "1.0.0",
"run_id": run_id
}],
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
maximum_attempts=3
)
)
results["steps"].append({
"step": "sarif_generation",
"status": "success",
"results_count": len(sarif_report.get("runs", [{}])[0].get("results", []))
})
workflow.logger.info(
f"✓ SARIF report generated: "
f"{len(sarif_report.get('runs', [{}])[0].get('results', []))} results"
)
# Step 4: Upload results to MinIO
workflow.logger.info("Step 4: Uploading results to MinIO")
# Upload SARIF report
if sarif_report:
results_url = await workflow.execute_activity(
"upload_results",
args=[run_id, sarif_report],
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=30),
maximum_attempts=3
)
)
results["results_url"] = results_url
workflow.logger.info(f"✓ Results uploaded to: {results_url}")
# Step 5: Cleanup cache
workflow.logger.info("Step 5: Cleaning up cache")
await workflow.execute_activity(
"cleanup_cache",
args=[target_id],
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
maximum_interval=timedelta(seconds=10),
maximum_attempts=2
)
)
workflow.logger.info("✓ Cache cleaned up")
# Mark workflow as successful
results["status"] = "success"
results["sarif"] = sarif_report
results["summary"] = summary
results["findings"] = findings
workflow.logger.info(
f"✅ LLMAnalysisWorkflow completed successfully: "
f"{len(findings)} findings"
)
except Exception as e:
workflow.logger.error(f"❌ Workflow failed: {e}")
results["status"] = "failed"
results["error"] = str(e)
raise
return results