Spaces:
Runtime error
Runtime error
File size: 26,886 Bytes
cb3062d 2a26b7d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | """
pdf.py β PDF Report Generator
================================
Builds a clean, branded PDF from a scan result dict.
Uses ReportLab Platypus β no external services, no cloud storage.
Called from app.py's GET /report/{id}/pdf endpoint.
"""
import logging
from datetime import datetime, timezone
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
logger = logging.getLogger("secretscan.pdf")
# Brand colours
_DARK = colors.HexColor("#0f172a")
_ACCENT = colors.HexColor("#5b7bfe")
_HIGH = colors.HexColor("#f43f5e")
_MEDIUM = colors.HexColor("#fb923c")
_LOW = colors.HexColor("#facc15")
_NONE = colors.HexColor("#22c55e")
_MUTED = colors.HexColor("#64748b")
_BG_LIGHT = colors.HexColor("#f8fafc")
_SEV_COLOR = {"HIGH": _HIGH, "MEDIUM": _MEDIUM, "LOW": _LOW, "NONE": _NONE}
def generate_pdf(scan_id: str, result: dict, out_path: str) -> None:
"""
Write a PDF report to out_path.
Args:
scan_id: UUID of the scan (shown in header).
result: The full build_result() dict from scanner.py.
out_path: Filesystem path to write the .pdf file.
Raises:
Exception: propagates ReportLab errors to the caller.
"""
styles = getSampleStyleSheet()
doc = SimpleDocTemplate(
out_path,
pagesize = letter,
topMargin = 36,
bottomMargin = 36,
leftMargin = 48,
rightMargin = 48,
)
findings = result.get("findings", [])
summary = result.get("summary", {})
risk = result.get("risk_level", "NONE")
total = result.get("total_secrets", 0)
source = result.get("source", "")
truncated= result.get("truncated", False)
story: list = []
# ββ Header ββββββββββββββββββββββββββββββββββββββββββββββββ
story.append(Paragraph(
"π SecretScan Security Report",
ParagraphStyle("Title", parent=styles["Title"],
fontSize=22, textColor=_DARK, spaceAfter=2),
))
story.append(Paragraph(
f"Scan ID: {scan_id[:8]}β¦ Β· "
f"Generated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}",
ParagraphStyle("Sub", parent=styles["Normal"],
fontSize=9, textColor=_MUTED, spaceAfter=10),
))
story.append(HRFlowable(width="100%", thickness=1, color=_ACCENT, spaceAfter=12))
# ββ Risk banner βββββββββββββββββββββββββββββββββββββββββββ
risk_color = _SEV_COLOR.get(risk, _NONE)
story.append(Paragraph(
f"Overall Risk Level: <b>{risk}</b>",
ParagraphStyle("Risk", parent=styles["Normal"],
fontSize=16, textColor=risk_color, spaceAfter=6),
))
# ββ Summary table βββββββββββββββββββββββββββββββββββββββββ
table_data = [
["Total Secrets", "HIGH", "MEDIUM", "LOW"],
[
str(total),
str(summary.get("high", 0)),
str(summary.get("medium", 0)),
str(summary.get("low", 0)),
],
]
tbl = Table(table_data, colWidths=[120, 80, 80, 80])
tbl.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), _DARK),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 10),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [_BG_LIGHT, colors.white]),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
# Colour the HIGH/MEDIUM/LOW header cells
("TEXTCOLOR", (1, 0), (1, 0), _HIGH),
("TEXTCOLOR", (2, 0), (2, 0), _MEDIUM),
("TEXTCOLOR", (3, 0), (3, 0), _LOW),
]))
story.append(tbl)
story.append(Spacer(1, 14))
# ββ Source ββββββββββββββββββββββββββββββββββββββββββββββββ
if source:
story.append(Paragraph(
f"<b>Source:</b> {source}",
ParagraphStyle("Src", parent=styles["Normal"],
fontSize=9, textColor=_MUTED, spaceAfter=14),
))
# ββ Free-tier truncation notice βββββββββββββββββββββββββββ
if truncated:
story.append(Paragraph(
"β This report shows a partial view. "
"Upgrade to SecretScan Pro to see all findings and download the full PDF.",
ParagraphStyle("Warn", parent=styles["Normal"],
fontSize=10, textColor=_MEDIUM,
backColor=colors.HexColor("#fff7ed"),
borderPadding=8, spaceAfter=14),
))
# ββ Findings ββββββββββββββββββββββββββββββββββββββββββββββ
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"),
spaceAfter=8))
if not findings:
story.append(Paragraph(
"β No secrets detected in this scan.",
ParagraphStyle("Good", parent=styles["Normal"],
fontSize=12, textColor=_NONE),
))
else:
story.append(Paragraph(
f"Findings ({len(findings)} shown)",
ParagraphStyle("H2", parent=styles["Heading2"],
fontSize=13, textColor=_DARK, spaceAfter=8),
))
for idx, f in enumerate(findings, 1):
sev = f.get("severity", "LOW")
color = _SEV_COLOR.get(sev, _LOW)
# Finding header: index + type + severity badge
story.append(Paragraph(
f"{idx}. <b>{f.get('type', 'Unknown')}</b>"
f" <font color='#{color.hexval()[2:]}' size='9'>[{sev}]</font>",
ParagraphStyle(f"FH{idx}", parent=styles["Normal"],
fontSize=11, textColor=_DARK, spaceAfter=2),
))
# File + line
story.append(Paragraph(
f"<font color='#64748b' size='9'>"
f"π {f.get('file', '?')} Β· Line {f.get('line', '?')}"
f"</font>",
styles["Normal"],
))
# Redacted match
if f.get("match"):
story.append(Paragraph(
f"<font color='#64748b' size='8'><i>Match: {f['match']}</i></font>",
styles["Normal"],
))
# Description
story.append(Paragraph(
f.get("description", ""),
ParagraphStyle(f"FD{idx}", parent=styles["Normal"],
fontSize=9, textColor=_MUTED, spaceAfter=2),
))
# Fix recommendation
story.append(Paragraph(
f"<b>Fix:</b> {f.get('fix', '')}",
ParagraphStyle(f"FF{idx}", parent=styles["Normal"],
fontSize=9, textColor=_DARK, spaceAfter=10),
))
story.append(HRFlowable(
width="100%", thickness=0.3,
color=colors.HexColor("#e2e8f0"), spaceAfter=8,
))
# ββ Footer ββββββββββββββββββββββββββββββββββββββββββββββββ
story.append(Spacer(1, 20))
story.append(Paragraph(
"Generated by SecretScan β secretscan.io",
ParagraphStyle("Footer", parent=styles["Normal"],
fontSize=8, textColor=_MUTED, alignment=1),
))
doc.build(story)
logger.info(f"PDF generated: {out_path} ({len(findings)} findings)")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PHASE 1 β EXECUTIVE PDF REPORTS (item 5)
# New function. generate_pdf() above is UNCHANGED and still used
# by any existing callers β this is a richer, additive report type
# for Pro/Enterprise users.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from reportlab.platypus import PageBreak, Image as RLImage
from reportlab.lib.units import inch
_GOOD = colors.HexColor("#22c55e")
_BRAND = colors.HexColor("#5b7bfe")
_SECONDARY = colors.HexColor("#38bdf8")
_SCORE_BAND_COLOR = {
"Excellent": _GOOD,
"Good": _GOOD,
"Moderate": _MEDIUM,
"High Risk": _HIGH,
"Critical": colors.HexColor("#c026d3"),
}
def generate_executive_pdf(scan_id: str, result: dict, out_path: str,
org_name: str = "", user_email: str = "") -> None:
"""
Generate a multi-section "Executive" PDF security assessment report.
Sections:
1. Cover / header β branding, org name, scan timestamp
2. Executive Summary β security score, risk level, key stats
3. Repository Health (if present in result['repo_health'])
4. Critical & High Findings β detailed, with OWASP/NIST mapping
5. Detected Secrets (Secrets Exposure category findings)
6. Dependency Risks (if result['dependency_findings'] present)
7. Compliance Mapping summary table (OWASP Top 10 coverage)
8. Recommendations
9. Footer β branding, scan ID, timestamp
Args:
scan_id: UUID of the scan (shown in header).
result: The full build_result() dict from scanner.py β may
include Phase 1 fields (security_score, repo_health,
dependency_findings, and per-finding owasp/nist/auto_fix).
out_path: Filesystem path to write the .pdf file.
org_name: Organization name for branding (optional).
user_email: Requesting user's email, shown in report metadata (optional).
Raises:
Exception: propagates ReportLab errors to the caller.
"""
styles = getSampleStyleSheet()
doc = SimpleDocTemplate(
out_path,
pagesize=letter,
topMargin=40, bottomMargin=40, leftMargin=48, rightMargin=48,
)
findings = result.get("findings", [])
dep_findings = result.get("dependency_findings", [])
summary = result.get("summary", {})
risk = result.get("risk_level", "NONE")
total = result.get("total_secrets", len(findings))
source = result.get("source", "")
truncated = result.get("truncated", False)
security_score = result.get("security_score", 0)
score_risk_level = result.get("score_risk_level", "Moderate")
repo_health = result.get("repo_health")
now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
story: list = []
# ββ Title / Cover ββββββββββββββββββββββββββββββββββββββββ
story.append(Paragraph(
"SafeAIScan Security Assessment",
ParagraphStyle("Title", parent=styles["Title"],
fontSize=24, textColor=_DARK, spaceAfter=4),
))
story.append(Paragraph(
"Executive Security Report",
ParagraphStyle("Subtitle", parent=styles["Normal"],
fontSize=13, textColor=_ACCENT, spaceAfter=12),
))
meta_lines = [f"<b>Scan ID:</b> {scan_id[:8]}β¦",
f"<b>Generated:</b> {now_str}"]
if org_name:
meta_lines.append(f"<b>Organization:</b> {org_name}")
if user_email:
meta_lines.append(f"<b>Requested by:</b> {user_email}")
if source:
meta_lines.append(f"<b>Source:</b> {source}")
story.append(Paragraph(
" Β· ".join(meta_lines),
ParagraphStyle("Meta", parent=styles["Normal"],
fontSize=9, textColor=_MUTED, spaceAfter=10),
))
story.append(HRFlowable(width="100%", thickness=1.5, color=_ACCENT, spaceAfter=16))
# ββ Executive Summary ββββββββββββββββββββββββββββββββββββ
story.append(Paragraph(
"Executive Summary",
ParagraphStyle("H1", parent=styles["Heading1"], fontSize=15,
textColor=_DARK, spaceAfter=8),
))
score_color = _SCORE_BAND_COLOR.get(score_risk_level, _MEDIUM)
summary_table_data = [
["Security Score", "Risk Level", "Total Findings", "Critical", "High"],
[
f"{security_score} / 100",
score_risk_level,
str(total),
str(summary.get("critical", 0)),
str(summary.get("high", 0)),
],
]
summary_tbl = Table(summary_table_data, colWidths=[100, 95, 95, 70, 70])
summary_tbl.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), _DARK),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 10),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 8),
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
("BACKGROUND", (0, 1), (0, 1), colors.HexColor("#f8fafc")),
("TEXTCOLOR", (0, 1), (0, 1), score_color),
("FONTNAME", (0, 1), (0, 1), "Helvetica-Bold"),
("FONTSIZE", (0, 1), (0, 1), 13),
("TEXTCOLOR", (1, 1), (1, 1), score_color),
("FONTNAME", (1, 1), (1, 1), "Helvetica-Bold"),
("TEXTCOLOR", (3, 1), (3, 1), colors.HexColor("#c026d3")),
("TEXTCOLOR", (4, 1), (4, 1), _HIGH),
]))
story.append(summary_tbl)
story.append(Spacer(1, 14))
exec_summary_text = (
f"This assessment identified <b>{total}</b> finding(s) across the scanned "
f"{'repository' if source.startswith('http') else 'submission'}, resulting in an overall "
f"security score of <b>{security_score}/100</b> "
f"(<font color='#{score_color.hexval()[2:]}'><b>{score_risk_level}</b></font>). "
)
if summary.get("critical", 0) > 0:
exec_summary_text += (
f"<b>{summary['critical']} CRITICAL</b> finding(s) require immediate attention "
f"as they represent direct exposure of credentials or code-execution risks. "
)
if not findings:
exec_summary_text = (
"No security findings were detected in this scan. The codebase appears to "
"follow secure coding practices for the patterns checked."
)
story.append(Paragraph(
exec_summary_text,
ParagraphStyle("ExecSum", parent=styles["Normal"], fontSize=10,
textColor=_DARK, spaceAfter=14, leading=15),
))
if truncated:
story.append(Paragraph(
"β This report shows a partial view based on your current plan. "
"Upgrade to SafeAIScan Pro to see all findings and unlock full executive reports.",
ParagraphStyle("Warn", parent=styles["Normal"], fontSize=9,
textColor=_MEDIUM, backColor=colors.HexColor("#fff7ed"),
borderPadding=8, spaceAfter=14),
))
# ββ Repository Health βββββββββββββββββββββββββββββββββββββ
if repo_health:
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
story.append(Paragraph(
"Repository Health",
ParagraphStyle("H2RH", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
health_data = [
["Critical", "High", "Medium", "Low", "Secrets", "Dependencies", "Outdated"],
[
str(repo_health.get("critical_count", 0)),
str(repo_health.get("high_count", 0)),
str(repo_health.get("medium_count", 0)),
str(repo_health.get("low_count", 0)),
str(repo_health.get("secret_count", 0)),
str(repo_health.get("dependency_count", 0)),
str(repo_health.get("outdated_packages", 0)),
],
]
health_tbl = Table(health_data, colWidths=[58]*7)
health_tbl.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f1f5f9")),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 9),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
("TEXTCOLOR", (0, 1), (0, 1), colors.HexColor("#c026d3")),
("TEXTCOLOR", (1, 1), (1, 1), _HIGH),
("TEXTCOLOR", (2, 1), (2, 1), _MEDIUM),
("TEXTCOLOR", (3, 1), (3, 1), _GOOD),
]))
story.append(health_tbl)
story.append(Spacer(1, 14))
# ββ Critical & High Findings (detailed) ββββββββββββββββββ
critical_high = [f for f in findings if (f.get("severity") or "").upper() in ("CRITICAL", "HIGH")]
if critical_high:
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
story.append(Paragraph(
f"Critical & High Findings ({len(critical_high)})",
ParagraphStyle("H2CH", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
for idx, f in enumerate(critical_high, 1):
_render_finding(story, styles, f, idx, show_compliance=True)
# ββ Detected Secrets (Secrets Exposure category) ββββββββββ
secrets = [f for f in findings if str(f.get("category", "")).lower() == "secrets exposure"]
if secrets:
story.append(PageBreak())
story.append(Paragraph(
f"Detected Secrets ({len(secrets)})",
ParagraphStyle("H2Sec", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
for idx, f in enumerate(secrets, 1):
_render_finding(story, styles, f, idx, show_compliance=False, compact=True)
# ββ Dependency Risks ββββββββββββββββββββββββββββββββββββββ
if dep_findings:
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
story.append(Paragraph(
f"Dependency Risks ({len(dep_findings)})",
ParagraphStyle("H2Dep", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
dep_table_data = [["Package", "Version", "Severity", "CVE", "Issue"]]
for d in dep_findings[:20]:
dep_table_data.append([
d.get("package", "?"),
d.get("version", "?"),
d.get("severity", "LOW"),
d.get("cve", "N/A"),
(d.get("title", "") or d.get("description", ""))[:50],
])
dep_tbl = Table(dep_table_data, colWidths=[90, 60, 60, 90, 175])
dep_tbl.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f1f5f9")),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 8),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 5),
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
("ROWBACKGROUNDS",(0, 1), (-1, -1), [_BG_LIGHT, colors.white]),
]))
story.append(dep_tbl)
story.append(Spacer(1, 14))
# ββ Compliance Mapping Summary βββββββββββββββββββββββββββ
owasp_counts: dict = {}
for f in findings:
owasp = f.get("owasp")
if owasp:
owasp_counts[owasp] = owasp_counts.get(owasp, 0) + 1
if owasp_counts:
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
story.append(Paragraph(
"Compliance Mapping β OWASP Top 10 Coverage",
ParagraphStyle("H2Comp", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
comp_data = [["OWASP Category", "Findings"]]
for owasp, count in sorted(owasp_counts.items(), key=lambda x: -x[1]):
comp_data.append([owasp, str(count)])
comp_tbl = Table(comp_data, colWidths=[380, 80])
comp_tbl.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f1f5f9")),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 9),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 5),
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
("ALIGN", (1, 0), (1, -1), "CENTER"),
("ROWBACKGROUNDS",(0, 1), (-1, -1), [_BG_LIGHT, colors.white]),
]))
story.append(comp_tbl)
story.append(Spacer(1, 14))
# ββ Recommendations βββββββββββββββββββββββββββββββββββββββ
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
story.append(Paragraph(
"Recommendations",
ParagraphStyle("H2Rec", parent=styles["Heading2"], fontSize=13,
textColor=_DARK, spaceAfter=8),
))
recs = []
if summary.get("critical", 0) > 0:
recs.append("Rotate all exposed credentials immediately β treat CRITICAL findings as already compromised.")
if secrets:
recs.append("Move all secrets to environment variables or a secrets manager (e.g. HashiCorp Vault, AWS Secrets Manager, or your platform's secret store).")
if dep_findings:
recs.append("Update vulnerable dependencies to the versions specified in this report, prioritising CRITICAL and HIGH severity packages.")
if summary.get("high", 0) > 0:
recs.append("Review and remediate HIGH severity findings β these represent significant exploitable risk.")
recs.append("Add automated SafeAIScan checks to your CI/CD pipeline to catch new issues before merge.")
recs.append("Re-run this scan after remediation to confirm your security score has improved.")
for r in recs:
story.append(Paragraph(f"β’ {r}", ParagraphStyle(
"Rec", parent=styles["Normal"], fontSize=9.5, textColor=_DARK,
spaceAfter=4, leading=14,
)))
# ββ Footer ββββββββββββββββββββββββββββββββββββββββββββββββ
story.append(Spacer(1, 24))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#e2e8f0"), spaceAfter=6))
story.append(Paragraph(
f"Generated by SafeAIScan Β· {now_str} Β· Scan ID {scan_id[:8]}β¦ Β· safeaiscan.io",
ParagraphStyle("Footer", parent=styles["Normal"],
fontSize=8, textColor=_MUTED, alignment=1),
))
doc.build(story)
logger.info(f"Executive PDF generated: {out_path} ({len(findings)} findings, score={security_score})")
def _render_finding(story: list, styles, f: dict, idx: int,
show_compliance: bool = False, compact: bool = False) -> None:
"""Helper: render a single finding block into the PDF story."""
sev = (f.get("severity") or "LOW").upper()
color = _SEV_COLOR.get(sev, _LOW) if sev != "CRITICAL" else colors.HexColor("#c026d3")
header = (
f"{idx}. <b>{f.get('type', f.get('title', 'Issue'))}</b>"
f" <font color='#{color.hexval()[2:]}' size='9'>[{sev}]</font>"
)
story.append(Paragraph(header, ParagraphStyle(
f"FH{idx}_{id(f)}", parent=styles["Normal"], fontSize=11, textColor=_DARK, spaceAfter=2,
)))
if f.get("file"):
story.append(Paragraph(
f"<font color='#64748b' size='9'>File: {f.get('file', '?')}"
f"{' Β· Line ' + str(f.get('line')) if f.get('line') else ''}</font>",
styles["Normal"],
))
if f.get("match"):
story.append(Paragraph(
f"<font color='#64748b' size='8'><i>Match: {f['match']}</i></font>",
styles["Normal"],
))
if f.get("description"):
story.append(Paragraph(
f.get("description", ""),
ParagraphStyle(f"FD{idx}_{id(f)}", parent=styles["Normal"],
fontSize=9, textColor=_MUTED, spaceAfter=2),
))
if f.get("fix"):
story.append(Paragraph(
f"<b>Fix:</b> {f.get('fix', '')}",
ParagraphStyle(f"FF{idx}_{id(f)}", parent=styles["Normal"],
fontSize=9, textColor=_DARK, spaceAfter=2),
))
if show_compliance and (f.get("owasp") or f.get("nist")):
story.append(Paragraph(
f"<font size='8' color='#5b7bfe'><b>Compliance:</b> "
f"OWASP {f.get('owasp','')} Β· NIST {f.get('nist','')}</font>",
styles["Normal"],
))
if f.get("auto_fix") and not compact:
af = f["auto_fix"]
story.append(Paragraph(
f"<font size='8' color='#22c55e'><b>Suggested fix (confidence {af.get('confidence',0)}%):</b> "
f"{af.get('after','')}</font>",
styles["Normal"],
))
story.append(Spacer(1, 4))
story.append(HRFlowable(
width="100%", thickness=0.3,
color=colors.HexColor("#e2e8f0"), spaceAfter=8,
))
|