from __future__ import annotations import html import os from pathlib import Path from typing import Any, Dict, List from lab.config import ADVISORIES_DIR, CASE_RUNS_DIR, DASHBOARD_DIR, RUNS_DIR from lab.utils import ensure_dir, isoformat, load_json_dir, now_utc, write_json, write_text def mermaid_from_steps(run: Dict[str, Any]) -> str: lines = [ "flowchart LR", 'A["Select Advisory"] --> B["Resolve Repro Profile"]', 'B --> C["Provision Compose Environment"]', 'C --> D["Baseline Snapshot"]', 'D --> E["Controlled Attack Steps"]', 'E --> F["Browser Replay"]', 'F --> G["Collect Logs and Evidence"]', 'G --> H["Update Registry and Reports"]', ] if run.get("blocked_reason"): lines.append(f'H --> I["Blocked: {run["blocked_reason"][:60]}"]') return "\n".join(lines) def _relative_ref(run_dir: Path, ref: str) -> str: try: return str(Path(ref).resolve().relative_to(run_dir.resolve())) except ValueError: return ref def _dashboard_ref(run: Dict[str, Any], ref: str) -> str: try: bundle_dir = Path(run["report_refs"]["bundle_dir"]).resolve() relative = Path(ref).resolve().relative_to(bundle_dir) return f"./runs/{run['run_id']}/{relative.as_posix()}" except Exception: return ref def render_run(run: Dict[str, Any]) -> Dict[str, str]: run_dir = CASE_RUNS_DIR / run["run_id"] ensure_dir(run_dir / "assets") timeline_path = run_dir / "timeline.mmd" write_text(timeline_path, mermaid_from_steps(run)) screenshot_refs = [ref for ref in run.get("browser_refs", []) if ref.endswith((".png", ".jpg", ".jpeg"))] relative_screenshots = [_relative_ref(run_dir, ref) for ref in screenshot_refs] md_lines = [ f"# Run {run['run_id']}", "", "> `LAB ONLY` | `AUTHORIZED TARGETS ONLY` | 自动生成 run bundle", "", f"- Advisory: `{run['advisory_id']}`", f"- 系统: `{run['system_id']}`", f"- Repro Profile: `{run['repro_profile_id']}`", f"- 实证状态: `{run['verification_status']}`", f"- 实证方式: `{run['verification_mode']}`", f"- Artifact 模式: `{run['artifact_mode']}`", f"- 启动时间: `{run['started_at']}`", f"- 完成时间: `{run['finished_at']}`", f"- 阻塞原因: `{run.get('blocked_reason') or '-'}`", f"- Compose 服务: `{', '.join(run.get('compose_services', [])) or '-'}`", "", "## 运行时间线", "", f"- Mermaid: [{timeline_path.name}]({timeline_path})", "", "| 时间 | 步骤 | 状态 | 说明 |", "|------|------|------|------|", ] if run.get("timeline"): for item in run["timeline"]: md_lines.append( f"| `{item.get('at', '')}` | `{item.get('step', '')}` | `{item.get('status', '')}` | {item.get('detail', '') or '-'} |" ) else: md_lines.append("| `-` | `-` | `-` | 无时间线 |") md_lines.extend( [ "", "## Compose 拓扑", "", f"- Compose 文件: `{', '.join(run.get('compose_refs', [])) or '-'}`", f"- 服务列表: `{', '.join(run.get('compose_services', [])) or '-'}`", "", "## 攻击步骤", "", "| 工具/步骤 | 状态 | 结果 |", "|-----------|------|------|", ] ) if run.get("attack_steps"): for step in run["attack_steps"]: outcome = step.get("result_path") or step.get("detail") or "-" md_lines.append(f"| `{step.get('tool') or step.get('kind')}` | `{step.get('status', '-')}` | `{outcome}` |") else: md_lines.append("| `-` | `skipped` | `no attack steps` |") md_lines.extend( [ "", "## 证据摘要", "", f"- Baseline: `{len(run.get('baseline_refs', []))}`", f"- 攻击步骤: `{len(run.get('attack_steps', []))}`", f"- 浏览器证据: `{len(run.get('browser_refs', []))}`", f"- 容器日志: `{len(run.get('container_log_refs', []))}`", f"- 请求日志: `{len(run.get('request_log_refs', []))}`", "", ] ) if relative_screenshots: md_lines.extend(["## 浏览器截图", ""]) for ref in relative_screenshots: md_lines.append(f"![{Path(ref).stem}]({ref})") md_lines.append("") if run.get("browser_refs"): md_lines.extend(["## 浏览器证据", ""]) for ref in run["browser_refs"]: md_lines.append(f"- `{_relative_ref(run_dir, ref)}`") md_lines.append("") if run.get("container_log_refs"): md_lines.extend(["## 容器日志", ""]) for ref in run["container_log_refs"]: md_lines.append(f"- `{_relative_ref(run_dir, ref)}`") md_lines.append("") if run.get("request_log_refs"): md_lines.extend(["## 请求与基线日志", ""]) for ref in run["request_log_refs"]: md_lines.append(f"- `{_relative_ref(run_dir, ref)}`") md_lines.append("") md_lines.extend( [ "## 最小化验证说明", "", "- 仅限自有资产、本地靶场或已授权实验目标。", "- 默认执行 minimal-proof;不会把破坏性或不可回滚动作作为默认路径。", "- 若浏览器证据缺失,前端类案例不会被标为 `verified-*`。", "", ] ) report_md = run_dir / "report.md" write_text(report_md, "\n".join(md_lines)) html_body = [ "", "websafe run report", "", "", f"

Run {html.escape(run['run_id'])}

", "
", f"
Advisory
{html.escape(run['advisory_id'])}
", f"
Status
{html.escape(run['verification_status'])}
", f"
Profile
{html.escape(run['repro_profile_id'])}
", f"
Artifact Mode
{html.escape(run['artifact_mode'])}
", "
", "

Mermaid Timeline

", f"
{html.escape(mermaid_from_steps(run))}
", "

Timeline

", "", ] if run.get("timeline"): for item in run["timeline"]: html_body.append( "" f"" f"" f"" f"" "" ) html_body.extend(["
TimeStepStatusDetail
{html.escape(item.get('at', ''))}{html.escape(item.get('step', ''))}{html.escape(item.get('status', ''))}{html.escape(item.get('detail', '') or '-')}
", "

Attack Steps

", ""]) if run.get("attack_steps"): for step in run["attack_steps"]: html_body.append( "" f"" f"" f"" "" ) else: html_body.append("") html_body.extend(["
ToolStatusOutput
{html.escape(step.get('tool') or step.get('kind') or '-')}{html.escape(step.get('status', '-'))}{html.escape(step.get('result_path') or '-')}
-skippedno attack steps
"]) if relative_screenshots: html_body.extend(["

Browser Screenshots

", "") html_body.extend(["

Evidence

", ""]) report_html = run_dir / "report.html" write_text(report_html, "\n".join(html_body)) return {"bundle_dir": str(run_dir), "report_md": str(report_md), "report_html": str(report_html), "timeline": str(timeline_path)} def render_dashboard() -> Dict[str, str]: ensure_dir(DASHBOARD_DIR) advisory_records = load_json_dir(ADVISORIES_DIR) runs = load_json_dir(RUNS_DIR) runs_dir = DASHBOARD_DIR / "runs" ensure_dir(runs_dir) for item in runs: bundle_dir = Path(item.get("report_refs", {}).get("bundle_dir", "")) if not bundle_dir.exists(): continue symlink_path = runs_dir / item["run_id"] try: if symlink_path.is_symlink() or symlink_path.exists(): if symlink_path.is_symlink() and symlink_path.resolve() == bundle_dir.resolve(): pass else: symlink_path.unlink() os.symlink(bundle_dir, symlink_path, target_is_directory=True) else: os.symlink(bundle_dir, symlink_path, target_is_directory=True) except OSError: continue systems: Dict[str, Dict[str, Any]] = {} for advisory in advisory_records: system = systems.setdefault( advisory["system_id"], { "system_id": advisory["system_id"], "display_name": advisory.get("display_name", advisory["system_id"]), "total": 0, "verified_real": 0, "verified_synthetic": 0, "blocked": 0, "manual": 0, "browser_required": 0, "browser_present": 0, "latest_update": "", }, ) system["total"] += 1 status = advisory.get("verification_status", "triage-manual") if status == "verified-real": system["verified_real"] += 1 elif status == "verified-synthetic": system["verified_synthetic"] += 1 elif status.startswith("blocked-"): system["blocked"] += 1 else: system["manual"] += 1 browser = advisory.get("browser_evidence", {}) if browser.get("required"): system["browser_required"] += 1 if browser.get("present"): system["browser_present"] += 1 latest = advisory.get("updated_at") or advisory.get("published_at") or "" if latest > system["latest_update"]: system["latest_update"] = latest recent_runs = sorted(runs, key=lambda item: item.get("finished_at") or "", reverse=True)[:100] decorated_runs: List[Dict[str, Any]] = [] for item in recent_runs: cloned = dict(item) cloned["dashboard_refs"] = { "report_html": f"./runs/{item['run_id']}/report.html", "report_md": f"./runs/{item['run_id']}/report.md", "timeline": f"./runs/{item['run_id']}/timeline.mmd", "bundle": f"./runs/{item['run_id']}/run.json", } cloned["browser_links"] = [_dashboard_ref(item, ref) for ref in item.get("browser_refs", [])] cloned["container_links"] = [_dashboard_ref(item, ref) for ref in item.get("container_log_refs", [])] cloned["request_links"] = [_dashboard_ref(item, ref) for ref in item.get("request_log_refs", [])] decorated_runs.append(cloned) summary = { "generated_at": isoformat(now_utc()), "advisory_count": len(advisory_records), "run_count": len(runs), "statuses": {}, "recent_failures": [], } for item in runs: status = item.get("verification_status", "triage-manual") summary["statuses"][status] = summary["statuses"].get(status, 0) + 1 summary["systems"] = sorted(systems.values(), key=lambda item: (-item["total"], item["system_id"])) summary["recent_failures"] = [ { "run_id": item["run_id"], "advisory_id": item["advisory_id"], "status": item.get("verification_status"), "blocked_reason": item.get("blocked_reason"), } for item in decorated_runs if item.get("verification_status") in {"triage-manual", "blocked-artifact", "blocked-destructive"} ][:20] write_json(DASHBOARD_DIR / "summary.json", summary) write_json(DASHBOARD_DIR / "runs.json", decorated_runs) write_json(DASHBOARD_DIR / "systems.json", summary["systems"]) html_page = """ websafe dashboard

websafe Local Lab Dashboard

LAB ONLY | AUTHORIZED TARGETS ONLY | 本地静态看板

System Coverage

SystemTotalVerified RealVerified SyntheticBlockedManualBrowserLatest

Recent Runs

RunSystemAdvisoryStatusModeProfileFinishedArtifacts
""" write_text(DASHBOARD_DIR / "index.html", html_page) return { "dashboard_dir": str(DASHBOARD_DIR), "index_html": str(DASHBOARD_DIR / "index.html"), }