stackparity 1.0.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.
- stackparity/__init__.py +17 -0
- stackparity/_engine/agents/investigator.py +294 -0
- stackparity/_engine/agents/memory_agent.py +37 -0
- stackparity/_engine/agents/pipeline_agent.py +152 -0
- stackparity/_engine/agents/remediation_agent.py +248 -0
- stackparity/_engine/agents/runtime.py +177 -0
- stackparity/_engine/agents/specialists.py +709 -0
- stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
- stackparity/_engine/cli/__init__.py +2 -0
- stackparity/_engine/cli/main.py +1252 -0
- stackparity/_engine/cli/remediate.py +461 -0
- stackparity/_engine/cli/term.py +44 -0
- stackparity/_engine/config/__init__.py +0 -0
- stackparity/_engine/config/constants.py +88 -0
- stackparity/_engine/config/loader.py +155 -0
- stackparity/_engine/config/settings.py +108 -0
- stackparity/_engine/containers/__init__.py +12 -0
- stackparity/_engine/containers/discovery.py +143 -0
- stackparity/_engine/containers/models.py +72 -0
- stackparity/_engine/containers/trivy_image_scanner.py +165 -0
- stackparity/_engine/core/__init__.py +0 -0
- stackparity/_engine/core/capabilities.py +107 -0
- stackparity/_engine/core/finding_schema.py +305 -0
- stackparity/_engine/core/git_manager.py +206 -0
- stackparity/_engine/core/http.py +64 -0
- stackparity/_engine/core/models.py +109 -0
- stackparity/_engine/core/netpolicy.py +242 -0
- stackparity/_engine/core/plugins.py +43 -0
- stackparity/_engine/core/repository_inspector.py +243 -0
- stackparity/_engine/core/safe_env.py +48 -0
- stackparity/_engine/core/scan_orchestrator.py +289 -0
- stackparity/_engine/core/scan_state.py +58 -0
- stackparity/_engine/core/url_validator.py +135 -0
- stackparity/_engine/ecosystems/__init__.py +1 -0
- stackparity/_engine/ecosystems/registry.py +138 -0
- stackparity/_engine/evidence/__init__.py +1 -0
- stackparity/_engine/evidence/store.py +65 -0
- stackparity/_engine/explainability/__init__.py +0 -0
- stackparity/_engine/explainability/evidence_formatter.py +30 -0
- stackparity/_engine/explainability/explanation_engine.py +132 -0
- stackparity/_engine/explainability/explanation_validator.py +54 -0
- stackparity/_engine/explainability/prompt_templates.py +18 -0
- stackparity/_engine/graph/__init__.py +0 -0
- stackparity/_engine/graph/dependency_tracer.py +86 -0
- stackparity/_engine/graph/graph_builder.py +165 -0
- stackparity/_engine/graph/graph_diff.py +57 -0
- stackparity/_engine/graph/graph_exporter.py +194 -0
- stackparity/_engine/graph/graph_validator.py +46 -0
- stackparity/_engine/graph/impact_analyzer.py +23 -0
- stackparity/_engine/graph/tree_view.py +185 -0
- stackparity/_engine/intel/__init__.py +0 -0
- stackparity/_engine/intel/epss.py +53 -0
- stackparity/_engine/llm/__init__.py +1 -0
- stackparity/_engine/llm/client.py +138 -0
- stackparity/_engine/monitor/__init__.py +0 -0
- stackparity/_engine/monitor/watch.py +171 -0
- stackparity/_engine/non_cve/__init__.py +7 -0
- stackparity/_engine/non_cve/base.py +62 -0
- stackparity/_engine/non_cve/iac.py +144 -0
- stackparity/_engine/non_cve/sast.py +272 -0
- stackparity/_engine/non_cve/supply_chain.py +147 -0
- stackparity/_engine/orchestration/__init__.py +1 -0
- stackparity/_engine/orchestration/pipeline.py +279 -0
- stackparity/_engine/orchestration/supervisor.py +167 -0
- stackparity/_engine/pipeline_analysis/__init__.py +0 -0
- stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
- stackparity/_engine/pipeline_analysis/ci.py +189 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
- stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
- stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
- stackparity/_engine/pipeline_analysis/eol.py +62 -0
- stackparity/_engine/pipeline_analysis/models.py +37 -0
- stackparity/_engine/policy/__init__.py +0 -0
- stackparity/_engine/policy/engine.py +216 -0
- stackparity/_engine/policy/resources/default.yaml +56 -0
- stackparity/_engine/policy/resources/strict.yaml +35 -0
- stackparity/_engine/reachability/__init__.py +0 -0
- stackparity/_engine/reachability/app_reachability.py +186 -0
- stackparity/_engine/reachability/scanners.py +215 -0
- stackparity/_engine/remediation/__init__.py +0 -0
- stackparity/_engine/remediation/adapters.py +198 -0
- stackparity/_engine/remediation/apply_local.py +309 -0
- stackparity/_engine/remediation/code_fixes.py +383 -0
- stackparity/_engine/remediation/compat.py +156 -0
- stackparity/_engine/remediation/container_plan.py +127 -0
- stackparity/_engine/remediation/delivery.py +31 -0
- stackparity/_engine/remediation/export.py +44 -0
- stackparity/_engine/remediation/lifecycle.py +623 -0
- stackparity/_engine/remediation/local_trial.py +358 -0
- stackparity/_engine/remediation/patchers.py +215 -0
- stackparity/_engine/remediation/planner.py +285 -0
- stackparity/_engine/remediation/pr_template_engine.py +234 -0
- stackparity/_engine/remediation/reachability_impact.py +147 -0
- stackparity/_engine/remediation/versions.py +92 -0
- stackparity/_engine/remediation/whatif.py +64 -0
- stackparity/_engine/remediation/worktree_pr.py +434 -0
- stackparity/_engine/reporting/__init__.py +0 -0
- stackparity/_engine/reporting/counts.py +63 -0
- stackparity/_engine/reporting/fix_pdf.py +343 -0
- stackparity/_engine/reporting/fix_report.py +135 -0
- stackparity/_engine/reporting/json_exporter.py +61 -0
- stackparity/_engine/reporting/report_generator.py +200 -0
- stackparity/_engine/reporting/sarif.py +71 -0
- stackparity/_engine/reporting/vex.py +57 -0
- stackparity/_engine/reporting/view.py +166 -0
- stackparity/_engine/risk_analysis/__init__.py +0 -0
- stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
- stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
- stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
- stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
- stackparity/_engine/risk_analysis/function_impact.py +184 -0
- stackparity/_engine/risk_analysis/production_context.py +252 -0
- stackparity/_engine/risk_analysis/risk_rules.py +81 -0
- stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
- stackparity/_engine/sandbox/__init__.py +0 -0
- stackparity/_engine/sandbox/runner.py +142 -0
- stackparity/_engine/sbom/__init__.py +0 -0
- stackparity/_engine/sbom/adapters/__init__.py +19 -0
- stackparity/_engine/sbom/adapters/builtin.py +29 -0
- stackparity/_engine/sbom/adapters/syft.py +26 -0
- stackparity/_engine/sbom/adapters/trivy.py +76 -0
- stackparity/_engine/sbom/builtin_generator.py +227 -0
- stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
- stackparity/_engine/sbom/exporters.py +153 -0
- stackparity/_engine/sbom/fusion/__init__.py +5 -0
- stackparity/_engine/sbom/fusion/engine.py +315 -0
- stackparity/_engine/sbom/fusion/hashes.py +47 -0
- stackparity/_engine/sbom/fusion/ledger.py +96 -0
- stackparity/_engine/sbom/fusion/registries.py +271 -0
- stackparity/_engine/sbom/fusion/resolver.py +143 -0
- stackparity/_engine/sbom/fusion/writer.py +114 -0
- stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
- stackparity/_engine/sbom/merge.py +71 -0
- stackparity/_engine/sbom/package_extractors/common.py +104 -0
- stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
- stackparity/_engine/sbom/package_extractors/npm.py +206 -0
- stackparity/_engine/sbom/package_extractors/others.py +267 -0
- stackparity/_engine/sbom/package_extractors/python.py +143 -0
- stackparity/_engine/sbom/quality_analyzer.py +191 -0
- stackparity/_engine/sbom/scanner_engine.py +98 -0
- stackparity/_engine/sbom/syft_runner.py +100 -0
- stackparity/_engine/sbom/tool_locator.py +69 -0
- stackparity/_engine/sbom/trivy_runner.py +82 -0
- stackparity/_engine/storage/__init__.py +0 -0
- stackparity/_engine/storage/cache.py +56 -0
- stackparity/_engine/storage/database.py +295 -0
- stackparity/_engine/storage/memory.py +146 -0
- stackparity/_engine/suspicious_changes/__init__.py +12 -0
- stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
- stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
- stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
- stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
- stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
- stackparity/_engine/suspicious_changes/package_risk.py +78 -0
- stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
- stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
- stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
- stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
- stackparity/_engine/tools/__init__.py +1 -0
- stackparity/_engine/tools/builtin.py +93 -0
- stackparity/_engine/tools/registry.py +66 -0
- stackparity/_engine/ui/__init__.py +0 -0
- stackparity/_engine/ui/components/__init__.py +0 -0
- stackparity/_engine/ui/components/common.py +238 -0
- stackparity/_engine/ui/components/live_progress.py +157 -0
- stackparity/_engine/ui/components/memory_panel.py +82 -0
- stackparity/_engine/ui/pages/__init__.py +0 -0
- stackparity/_engine/ui/pages/agents_page.py +76 -0
- stackparity/_engine/ui/pages/architecture_page.py +44 -0
- stackparity/_engine/ui/pages/fixes_page.py +98 -0
- stackparity/_engine/ui/pages/graph_page.py +203 -0
- stackparity/_engine/ui/pages/health_page.py +117 -0
- stackparity/_engine/ui/pages/monitor_page.py +67 -0
- stackparity/_engine/ui/pages/pipeline_page.py +219 -0
- stackparity/_engine/ui/pages/remediation_page.py +409 -0
- stackparity/_engine/ui/pages/reports_page.py +54 -0
- stackparity/_engine/ui/pages/sbom_page.py +210 -0
- stackparity/_engine/ui/pages/scan_page.py +131 -0
- stackparity/_engine/ui/pages/suspicious_page.py +551 -0
- stackparity/_engine/ui/pages/vulns_page.py +201 -0
- stackparity/_engine/ui/state.py +116 -0
- stackparity/_engine/ui/theme.py +201 -0
- stackparity/_engine/ui/visualizations/__init__.py +0 -0
- stackparity/_engine/ui/visualizations/graphs.py +373 -0
- stackparity/_engine/vulnerability/__init__.py +0 -0
- stackparity/_engine/vulnerability/cvss.py +58 -0
- stackparity/_engine/vulnerability/kev_client.py +47 -0
- stackparity/_engine/vulnerability/nvd_client.py +74 -0
- stackparity/_engine/vulnerability/osv_client.py +139 -0
- stackparity/_engine/vulnerability/remediation_engine.py +50 -0
- stackparity/_engine/vulnerability/verification.py +94 -0
- stackparity/_engine/vulnerability/version_matcher.py +299 -0
- stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
- stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
- stackparity/cli.py +30 -0
- stackparity/dashboard_app.py +95 -0
- stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
- stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
- stackparity/web_dist/index.html +13 -0
- stackparity/web_server.py +533 -0
- stackparity-1.0.0.dist-info/METADATA +204 -0
- stackparity-1.0.0.dist-info/RECORD +212 -0
- stackparity-1.0.0.dist-info/WHEEL +4 -0
- stackparity-1.0.0.dist-info/entry_points.txt +2 -0
- stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Fix Report: every remediation that was fixed, with its scoring, the files that changed and a one-page PDF per fix."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import streamlit as st
|
|
5
|
+
|
|
6
|
+
from remediation.apply_local import applied_record
|
|
7
|
+
from remediation.local_trial import trial_record
|
|
8
|
+
from reporting.fix_pdf import HAS_REPORTLAB, build_pdf
|
|
9
|
+
from reporting.fix_report import SEV_ORDER, collect_fixes, totals
|
|
10
|
+
from ui.components.common import df, page_header, require_result
|
|
11
|
+
|
|
12
|
+
SEV_ICON = {"CRITICAL": "CRITICAL", "HIGH": "HIGH", "MEDIUM": "MEDIUM", "LOW": "LOW", "UNKNOWN": "UNKNOWN"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def render() -> None:
|
|
16
|
+
page_header("Fix Report", "Every remediation that was fixed: what it resolved, how the risk changed, which files were edited, and a one-page PDF to share.")
|
|
17
|
+
r = require_result()
|
|
18
|
+
if not r:
|
|
19
|
+
return
|
|
20
|
+
repo = r["repo"]
|
|
21
|
+
vulns = r.get("vulnerabilities") or []
|
|
22
|
+
items = (r.get("remediation") or {}).get("items") or []
|
|
23
|
+
delivered = {k[len("pr_res_"):]: v for k, v in st.session_state.items() if k.startswith("pr_res_") and isinstance(v, dict)}
|
|
24
|
+
fixes = collect_fixes(r, trial_loader=trial_record, delivered=delivered)
|
|
25
|
+
t = totals(fixes, len(vulns))
|
|
26
|
+
|
|
27
|
+
m = st.columns(4)
|
|
28
|
+
m[0].metric("Fixes applied", t["fixes"])
|
|
29
|
+
m[1].metric("Findings fixed", t["findings_fixed"])
|
|
30
|
+
m[2].metric("Findings remaining", t["remaining"], help="Total findings minus those resolved by the fixes below (rescan the project to confirm)")
|
|
31
|
+
m[3].metric("Proposals still open", max(len(items) - len(fixes), 0))
|
|
32
|
+
|
|
33
|
+
if not fixes:
|
|
34
|
+
st.info("No fix has been applied yet. Open **Remediation**, press **Resolve** on a proposal, then **Accept & Apply Changes**; it will appear here with a downloadable PDF."
|
|
35
|
+
if repo.get("source") == "local" else
|
|
36
|
+
"No fix has been committed yet. On **Remediation**, create a branch for a proposal; it will appear here with a downloadable PDF.")
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
name = (repo.get("name") or "project").replace(" ", "-")
|
|
40
|
+
c1, c2 = st.columns([3, 1])
|
|
41
|
+
c1.caption(f"{len(fixes)} fix(es), newest first. Each PDF is a single page with the vulnerability scoring, the fix, the files and the validation record.")
|
|
42
|
+
if HAS_REPORTLAB:
|
|
43
|
+
c2.download_button("All fixes (PDF)", build_pdf(fixes), file_name=f"{name}-fix-report.pdf", mime="application/pdf", type="primary", use_container_width=True, key="pdf_all", icon=":material/download:")
|
|
44
|
+
else:
|
|
45
|
+
c2.caption("PDF export disabled (install 'reportlab')")
|
|
46
|
+
|
|
47
|
+
for n, f in enumerate(fixes):
|
|
48
|
+
top = next((k for k in SEV_ORDER if f["severity_counts"].get(k)), "UNKNOWN")
|
|
49
|
+
with st.expander(f"{f['id']} · {f['title']} · {len(f['findings'])} finding(s) fixed", expanded=(n == 0)):
|
|
50
|
+
h1, h2 = st.columns([4, 1])
|
|
51
|
+
h1.caption(f"{f['how']} · {(f['applied_at'] or '').replace('T', ' ').replace('Z', ' UTC')} · priority {f['priority'] or '-'}")
|
|
52
|
+
if HAS_REPORTLAB:
|
|
53
|
+
h2.download_button("PDF", build_pdf([f]), file_name=f"{name}-{f['id']}.pdf", mime="application/pdf", key=f"pdf_{f['id']}", use_container_width=True, icon=":material/download:")
|
|
54
|
+
else:
|
|
55
|
+
h2.caption("PDF disabled")
|
|
56
|
+
|
|
57
|
+
k = st.columns(4)
|
|
58
|
+
k[0].metric("Findings fixed", len(f["findings"]))
|
|
59
|
+
k[1].metric("Highest severity", top.title() if f["findings"] else "n/a")
|
|
60
|
+
k[2].metric("Top risk score", f"{f['max_score']:.0f} → 0" if f["max_score"] is not None else "n/a", help="Highest contextual score among the fixed findings, before and after")
|
|
61
|
+
v = f["validation"]
|
|
62
|
+
k[3].metric("Validation", {"passed": "Passed", "failed": "Failed", "static": "Static"}.get(v["status"], "n/a"), help=f"tests: {str(v.get('tests', 'n/a')).replace('_', ' ')}")
|
|
63
|
+
|
|
64
|
+
t_vuln, t_chg, t_val = st.tabs(["Vulnerabilities fixed", "What changed", "Validation"])
|
|
65
|
+
with t_vuln:
|
|
66
|
+
df([{"ID": x["id"], "Package": f"{x['package']}@{x['version']}", "Severity": x["severity"].title(),
|
|
67
|
+
"CVSS": x["cvss"] if x["cvss"] is not None else "n/a", "Risk": (x["risk"] or "n/a").title(),
|
|
68
|
+
"Score": f"{x['score']:.0f}/100" if x["score"] is not None else "n/a", "Priority": x["priority"] or "-", "Fixed in": x["fixed_in"]} for x in f["findings"]],
|
|
69
|
+
height="content")
|
|
70
|
+
rc = f["risk_counts"]
|
|
71
|
+
st.caption("Contextual risk before this fix: " + " · ".join(f"{rc[q]} {q.lower()}" for q in ("CRITICAL", "HIGH", "MEDIUM", "LOW") if rc.get(q)) + " · after: all resolved.")
|
|
72
|
+
if f["rationale"]:
|
|
73
|
+
st.markdown("**Why this fix**")
|
|
74
|
+
st.markdown(f["rationale"])
|
|
75
|
+
with t_chg:
|
|
76
|
+
tg = f["target"]
|
|
77
|
+
st.markdown(f"**{tg.get('package', '-')}** · `{tg.get('from') or '-'}` → `{tg.get('to') or '-'}`" + (f" · {f['repo']['path']}" if f["repo"].get("path") else ""))
|
|
78
|
+
for ch in f["changes"]:
|
|
79
|
+
st.markdown(f"`{ch['path']}` · {ch['kind']} · **+{ch['added']}** / **−{ch['removed']}**")
|
|
80
|
+
if ch["lines"] and ch["kind"] != "lockfile":
|
|
81
|
+
st.code("\n".join(ch["lines"][:30]), language="diff")
|
|
82
|
+
if f["lock"].get("note"):
|
|
83
|
+
st.caption(f"Lockfile: {f['lock']['note']}")
|
|
84
|
+
with t_val:
|
|
85
|
+
if v["steps"]:
|
|
86
|
+
for stp in v["steps"]:
|
|
87
|
+
st.markdown(f":material/{'check_circle' if stp['ok'] else 'cancel'}: **{stp['step']}** · {stp['detail']}")
|
|
88
|
+
else:
|
|
89
|
+
st.caption("No clone validation record for this fix (static what-if only).")
|
|
90
|
+
for w in v["warnings"]:
|
|
91
|
+
st.warning(w)
|
|
92
|
+
if repo.get("source") == "local":
|
|
93
|
+
prop = next((x for x in items if x["id"] == f["id"]), None)
|
|
94
|
+
root = repo.get("local_path") or repo.get("repo_dir") or repo.get("path") or "."
|
|
95
|
+
rec = applied_record(root, prop) if prop else None
|
|
96
|
+
if rec:
|
|
97
|
+
st.caption(f"To revert: `git restore {' '.join(rec.get('files') or [])}` in {root}, after checking nothing else changed in those files "
|
|
98
|
+
f"(originals were backed up to `{rec.get('backup_dir')}`). StackParity no longer restores files itself, so it never overwrites later edits.")
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Page 3: dependency graph - direct vs transitive views, severity alerts, and tracing to source packages."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import networkx as nx
|
|
5
|
+
import streamlit as st
|
|
6
|
+
|
|
7
|
+
from graph.dependency_tracer import trace_component
|
|
8
|
+
from graph.graph_builder import roots_of
|
|
9
|
+
from graph.graph_exporter import dependency_payload, graph_from_json
|
|
10
|
+
from graph.impact_analyzer import impact_of
|
|
11
|
+
from graph.tree_view import build_reverse_tree, build_tree, graph_stats, tree_html, vulnerable_ancestors
|
|
12
|
+
from ui.components.common import df, download_json, page_header, require_result
|
|
13
|
+
from ui.visualizations.graphs import render_dependency_graph
|
|
14
|
+
|
|
15
|
+
SEV_RANK = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, "UNKNOWN": 0}
|
|
16
|
+
SEV_ICON = {"CRITICAL": "CRITICAL", "HIGH": "HIGH", "MEDIUM": "MEDIUM", "LOW": "LOW", "UNKNOWN": "UNKNOWN"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@st.cache_data(show_spinner=False)
|
|
20
|
+
def _graph(scan_id: str, data: dict):
|
|
21
|
+
return graph_from_json(data)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@st.cache_data(show_spinner=False)
|
|
25
|
+
def _cached_dependency_payload(scan_id: str, _g: nx.DiGraph, rel: dict, vmap: dict, advisories: dict, info: dict, fixes: dict) -> dict:
|
|
26
|
+
return dependency_payload(_g, rel, vmap, advisories, info, fixes)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _vuln_map(r: dict) -> dict[str, str]:
|
|
30
|
+
m: dict[str, str] = {}
|
|
31
|
+
for f in r.get("vulnerabilities", []):
|
|
32
|
+
sev = f["severity"] or "UNKNOWN"
|
|
33
|
+
for ref in f.get("component_refs") or [f["component_ref"]]:
|
|
34
|
+
if SEV_RANK[sev] >= SEV_RANK.get(m.get(ref, "UNKNOWN"), -1):
|
|
35
|
+
m[ref] = sev
|
|
36
|
+
return m
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _changes_since_previous(r: dict) -> None:
|
|
40
|
+
"""Graph diff against the previous scan of the same repository (read from the persisted graph tables)."""
|
|
41
|
+
from config.settings import get_settings
|
|
42
|
+
from graph.graph_diff import diff_graphs
|
|
43
|
+
from storage.database import Database
|
|
44
|
+
try:
|
|
45
|
+
db = Database(get_settings().db_path)
|
|
46
|
+
prev = db.previous_scan(r["repo"]["url"], r["repo"]["scan_id"])
|
|
47
|
+
old, new = (db.load_graph(prev) if prev else None), db.load_graph(r["repo"]["scan_id"])
|
|
48
|
+
except Exception:
|
|
49
|
+
return
|
|
50
|
+
if not (prev and old and new):
|
|
51
|
+
return
|
|
52
|
+
d = diff_graphs(old, new)
|
|
53
|
+
with st.expander("Changes since the previous scan" + (" - identical" if d["identical"] else f" - {len(d['added_components'])} added, {len(d['removed_components'])} removed, {len(d['version_changes'])} version change(s)")):
|
|
54
|
+
if d["identical"]:
|
|
55
|
+
st.caption("The dependency graph is identical to the previous scan.")
|
|
56
|
+
return
|
|
57
|
+
st.caption(f"Components {d['totals']['before']['components']} -> {d['totals']['after']['components']}; edges +{d['added_edges']} / -{d['removed_edges']}")
|
|
58
|
+
for label, items in (("Added", d["added_components"]), ("Removed", d["removed_components"]), ("Version changes", d["version_changes"])):
|
|
59
|
+
if items:
|
|
60
|
+
st.markdown(f"**{label}**")
|
|
61
|
+
for x in items[:30]:
|
|
62
|
+
st.markdown(f"- `{x}`")
|
|
63
|
+
if len(items) > 30:
|
|
64
|
+
st.caption(f"... {len(items) - 30} more")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def render() -> None:
|
|
68
|
+
page_header("Dependency Graph", "Directed dependency topology, direct vs transitive classification, and transitive alerts.")
|
|
69
|
+
r = require_result()
|
|
70
|
+
if not r:
|
|
71
|
+
return
|
|
72
|
+
|
|
73
|
+
_changes_since_previous(r)
|
|
74
|
+
gd = r["graph"]
|
|
75
|
+
g = _graph(r["repo"]["scan_id"], {k: gd[k] for k in ("nodes", "edges")})
|
|
76
|
+
val, rel = gd.get("validation", {}), gd.get("relationships", {})
|
|
77
|
+
vmap = _vuln_map(r)
|
|
78
|
+
vulns = r.get("vulnerabilities", [])
|
|
79
|
+
roots = roots_of(g)
|
|
80
|
+
if not roots or not any(a.get("kind") == "component" for _, a in g.nodes(data=True)):
|
|
81
|
+
st.info("This repository has no package dependencies to graph (no lockfile/manifest packages were found). "
|
|
82
|
+
"Container images and CI actions are listed on the Pipeline & Containers page.")
|
|
83
|
+
return
|
|
84
|
+
labels = {n: g.nodes[n].get("label", n) for n in g.nodes}
|
|
85
|
+
comps = [n for n, a in g.nodes(data=True) if a.get("kind") == "component"]
|
|
86
|
+
direct_nodes = {n for n, per in rel.items() if any(v.startswith("direct") for v in per.values())}
|
|
87
|
+
trans_nodes = {n for n, per in rel.items() if any(v == "transitive" for v in per.values()) and n not in direct_nodes}
|
|
88
|
+
|
|
89
|
+
# Transitive alert banner
|
|
90
|
+
tv = [f for f in vulns if f["dependency_type"] == "transitive"]
|
|
91
|
+
hi = [f for f in tv if f["severity"] in ("CRITICAL", "HIGH")]
|
|
92
|
+
if hi:
|
|
93
|
+
src = {p for f in hi for p in f["source_packages"]}
|
|
94
|
+
st.error(f"**{len(hi)}** Critical/High vulnerabilities sit in **transitive** dependencies (introduced by **{len(src)}** direct dependencies).", icon=":material/error:")
|
|
95
|
+
elif tv:
|
|
96
|
+
st.warning(f"{len(tv)} lower-severity vulnerabilities are in transitive dependencies.")
|
|
97
|
+
|
|
98
|
+
c = st.columns(6)
|
|
99
|
+
c[0].metric("Service Roots", len(roots))
|
|
100
|
+
c[1].metric("Direct Deps", len(direct_nodes))
|
|
101
|
+
c[2].metric("Transitive Deps", len(trans_nodes))
|
|
102
|
+
c[3].metric("Vulnerable direct pkgs", len({n for n in vmap if n in direct_nodes}))
|
|
103
|
+
c[4].metric("Vulnerable transitive pkgs", len({n for n in vmap if n in trans_nodes}))
|
|
104
|
+
c[5].metric("Total Edges", g.number_of_edges())
|
|
105
|
+
|
|
106
|
+
info = {}
|
|
107
|
+
for cmp_ in r.get("components", []):
|
|
108
|
+
info[cmp_["bom_ref"]] = {"scope": cmp_.get("scope"), "license": ", ".join(cmp_.get("licenses") or []), "install_script": cmp_.get("install_script"),
|
|
109
|
+
"resolution": cmp_.get("resolution"), "deprecated": cmp_.get("deprecated"), "integrity": (cmp_.get("integrity") or {}).get("status")}
|
|
110
|
+
|
|
111
|
+
tab_graph, tab_tree, tab_alert, tab_inspect = st.tabs(["Interactive Graph", "Dependency Tree", "Alerts & Source Packages", "Package Tracer"])
|
|
112
|
+
|
|
113
|
+
with tab_tree:
|
|
114
|
+
stats = graph_stats(g, vmap)
|
|
115
|
+
s1, s2 = st.columns([1, 1])
|
|
116
|
+
with s1:
|
|
117
|
+
st.markdown("**How deep does the dependency chain go?**")
|
|
118
|
+
st.caption("Packages per depth (shortest distance from the service root: 1 = direct, 2+ = transitive)")
|
|
119
|
+
st.bar_chart({f"depth {k}": v for k, v in stats["depth_histogram"].items()})
|
|
120
|
+
if stats["vulnerable_by_depth"]:
|
|
121
|
+
st.caption("Vulnerable packages per depth: " + ", ".join(f"depth {k}: {v}" for k, v in stats["vulnerable_by_depth"].items()))
|
|
122
|
+
with s2:
|
|
123
|
+
st.markdown("**Longest chain** (" + str(max(len(stats["longest_chain"]) - 1, 0)) + " hops)")
|
|
124
|
+
st.code(" -> ".join(stats["longest_chain"][:14]) + (" -> ..." if len(stats["longest_chain"]) > 14 else ""), language="text")
|
|
125
|
+
if stats["most_shared"]:
|
|
126
|
+
st.markdown("**Most shared** (many parents; upgrading one affects them all)")
|
|
127
|
+
df([{"Package": n, "Parents": k} for n, k in stats["most_shared"][:6]], height="content")
|
|
128
|
+
if stats["has_cycles"]:
|
|
129
|
+
st.caption("The graph contains dependency cycles; each package is expanded once.")
|
|
130
|
+
|
|
131
|
+
mode = st.radio("Direction", ["Top-down: what a service brings in", "Bottom-up: who pulls a package in"], horizontal=True, key="tree_dir")
|
|
132
|
+
if mode.startswith("Top"):
|
|
133
|
+
c1, c2, c3, c4 = st.columns([2, 1, 1, 1])
|
|
134
|
+
root = c1.selectbox("Service root", roots, format_func=lambda n: labels[n], key="tree_root")
|
|
135
|
+
depth = c2.slider("Max depth", 1, 15, 6, key="tree_depth")
|
|
136
|
+
only_vuln = c3.checkbox("Only vulnerable branches", False, key="tree_vuln")
|
|
137
|
+
hide_dev = c4.checkbox("Hide dev deps", False, key="tree_dev")
|
|
138
|
+
only = vulnerable_ancestors(g, vmap) | {root} if only_vuln else None
|
|
139
|
+
t = build_tree(g, root, vmap, info, max_depth=depth, only=only, hide_dev=hide_dev)
|
|
140
|
+
top = t["tree"]
|
|
141
|
+
st.caption(f"{top['descendants']} unique packages below this root · {top['vuln_below']} vulnerable · showing {t['shown']} rows"
|
|
142
|
+
+ (" · output truncated, narrow with the filters" if t["truncated"] else "") + " · '↪ shown above' marks a package already expanded elsewhere")
|
|
143
|
+
st.html(tree_html(top, open_levels=1))
|
|
144
|
+
else:
|
|
145
|
+
q = st.text_input("Find package", placeholder="e.g. minimist", key="tree_q")
|
|
146
|
+
pool = [n for n in comps if (q.lower() in labels[n].lower())] if q else sorted(vmap, key=lambda n: -SEV_RANK.get(vmap[n], 0)) or comps
|
|
147
|
+
if pool:
|
|
148
|
+
pick = st.selectbox("Package", pool, format_func=lambda n: labels[n], key="tree_pick")
|
|
149
|
+
rt_ = build_reverse_tree(g, pick, vmap, info)
|
|
150
|
+
st.caption(f"{rt_['tree']['descendants']} package(s)/roots above it. Read upward: each level is a package that depends on the one beneath.")
|
|
151
|
+
st.html(tree_html(rt_["tree"], open_levels=6, reverse=True))
|
|
152
|
+
else:
|
|
153
|
+
st.info("No packages match.")
|
|
154
|
+
|
|
155
|
+
with tab_graph:
|
|
156
|
+
advisories: dict[str, list[str]] = {}
|
|
157
|
+
fixes: dict[str, str] = {}
|
|
158
|
+
for f in vulns:
|
|
159
|
+
for ref in f.get("component_refs") or [f["component_ref"]]:
|
|
160
|
+
advisories.setdefault(ref, []).append(f["primary_id"])
|
|
161
|
+
if f.get("recommended_fix"):
|
|
162
|
+
fixes.setdefault(ref, f["recommended_fix"])
|
|
163
|
+
payload = _cached_dependency_payload(r["repo"]["scan_id"], g, rel, vmap, advisories, info, fixes)
|
|
164
|
+
render_dependency_graph(payload, 620)
|
|
165
|
+
download_json("Download complete graph (JSON)", gd, f"{r['repo']['name']}-dependency-graph.json")
|
|
166
|
+
|
|
167
|
+
with tab_alert:
|
|
168
|
+
rows = []
|
|
169
|
+
for f in sorted(tv, key=lambda f: -SEV_RANK[f["severity"] or "UNKNOWN"]):
|
|
170
|
+
e = next((x for x in f["exposures"] if x["relationship"] == "transitive"), f["exposures"][0] if f["exposures"] else None)
|
|
171
|
+
path = e["paths"][0] if e and e["paths"] else []
|
|
172
|
+
rows.append({
|
|
173
|
+
"Severity": f"{SEV_ICON[f['severity'] or 'UNKNOWN']} {f['severity'] or 'n/a'}",
|
|
174
|
+
"Vulnerability": f["primary_id"],
|
|
175
|
+
"Package": f"{f['package_name']}@{f['installed_version']}",
|
|
176
|
+
"Source (Direct)": ", ".join(f["source_packages"][:2]),
|
|
177
|
+
"Depth": e["depth"] if e else "n/a",
|
|
178
|
+
"Full Path": " → ".join(path[1:]) if path else "",
|
|
179
|
+
"Fixed in": f["recommended_fix"] or "none",
|
|
180
|
+
})
|
|
181
|
+
st.markdown(f"**{len(rows)} transitive vulnerability alert(s)**")
|
|
182
|
+
df(rows, height=320)
|
|
183
|
+
st.markdown("**Source packages** (the direct dependencies that bring in the risk)")
|
|
184
|
+
spv = r.get("source_package_view", [])
|
|
185
|
+
df([{"Risk": x["worst_risk"], "Severity": x["worst_severity"] or "n/a", "Source Package": x["source_package"],
|
|
186
|
+
"Itself Vulnerable": "Yes" if x["is_itself_vulnerable"] else "No",
|
|
187
|
+
"Vulnerable packages": x["vulnerable_packages"], "Findings": x["findings"],
|
|
188
|
+
"Suggested Fix": x["top_fix"] or ""} for x in spv], height=360)
|
|
189
|
+
|
|
190
|
+
with tab_inspect:
|
|
191
|
+
q2 = st.text_input("Search package to trace", placeholder="e.g. minimist")
|
|
192
|
+
pool = [n for n in comps if q2.lower() in labels[n].lower()][:150] if q2 else list(vmap)[:150]
|
|
193
|
+
if pool:
|
|
194
|
+
target = st.selectbox("Select package", pool, format_func=lambda n: labels.get(n, n))
|
|
195
|
+
t = trace_component(g, target, max_paths=15)
|
|
196
|
+
imp = impact_of(g, target)
|
|
197
|
+
st.markdown(f"**{t['label']}** — dependents: `{imp['dependents']}` · blast radius: `{imp['blast_radius_components']}` packages")
|
|
198
|
+
for ro in t["roots"]:
|
|
199
|
+
with st.expander(f"Path to Root: {ro['root_label']} ({ro['relationship']}, depth {ro['depth']})", expanded=True):
|
|
200
|
+
for p in ro["paths"][:4]:
|
|
201
|
+
st.code(" → ".join(p), language="text")
|
|
202
|
+
|
|
203
|
+
download_json("Download Graph JSON", {**gd}, f"{r['repo']['name']}-graph.json", "dl_graph")
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Settings & Health: effective configuration (with sources), tools, database, cache and disk usage."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import shutil
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import streamlit as st
|
|
9
|
+
|
|
10
|
+
from config.loader import effective
|
|
11
|
+
from config.settings import get_settings
|
|
12
|
+
from sbom.syft_runner import resolve_syft, syft_version
|
|
13
|
+
from sbom.trivy_runner import resolve_trivy, trivy_version
|
|
14
|
+
from storage.cache import Cache
|
|
15
|
+
from storage.database import Database
|
|
16
|
+
from ui.components.common import df, page_header
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _size(path: Path) -> int:
|
|
20
|
+
total = 0
|
|
21
|
+
try:
|
|
22
|
+
for p in path.rglob("*"):
|
|
23
|
+
if p.is_file():
|
|
24
|
+
total += p.stat().st_size
|
|
25
|
+
except OSError:
|
|
26
|
+
pass
|
|
27
|
+
return total
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _mb(n: int | None) -> str:
|
|
31
|
+
return f"{(n or 0) / 1024 / 1024:.1f} MB"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def render() -> None:
|
|
35
|
+
page_header("Settings & Health", "Effective configuration, external tools, database, cache and disk usage.")
|
|
36
|
+
s = get_settings()
|
|
37
|
+
db = Database(s.db_path)
|
|
38
|
+
|
|
39
|
+
if s.problems:
|
|
40
|
+
for p in s.problems:
|
|
41
|
+
st.warning(p)
|
|
42
|
+
else:
|
|
43
|
+
st.success("Configuration is valid.")
|
|
44
|
+
st.caption(f"Config file: `{s.config_file or 'none (scanner.toml not found)'}` · precedence: environment `SCANNER_<NAME>` > `.env` > `scanner.toml` > defaults · secrets only via environment")
|
|
45
|
+
|
|
46
|
+
from llm.client import detect_provider
|
|
47
|
+
from sandbox.runner import docker_status
|
|
48
|
+
llm_on = bool(s.llm_api_key)
|
|
49
|
+
prov = (s.llm_provider or detect_provider(s.llm_api_key)) if llm_on else None
|
|
50
|
+
if not llm_on:
|
|
51
|
+
st.warning("⚠️ **LLM Provider API Key Missing**: Please add an LLM provider API key in `.env` (Groq, Gemini, Anthropic, or OpenAI) since requirements for this phase require an active LLM.")
|
|
52
|
+
elif not prov:
|
|
53
|
+
st.error("❌ **Invalid LLM API Key**: Key format unrecognized. Please check your `LLM_API_KEY` in `.env`.")
|
|
54
|
+
else:
|
|
55
|
+
st.success(f"🤖 LLM: **enabled** — {prov} (model: {s.llm_model or 'provider default'}); used for validated reasoning text.")
|
|
56
|
+
st.caption("Docker sandbox: " + ("available ✓" if docker_status()["available"] else "not available (optional)"))
|
|
57
|
+
t_cfg, t_tools, t_db, t_cache, t_disk = st.tabs(["Configuration", "Tools", "Database", "Cache", "Disk"])
|
|
58
|
+
|
|
59
|
+
with t_cfg:
|
|
60
|
+
df(effective(s), height=520)
|
|
61
|
+
|
|
62
|
+
with t_tools:
|
|
63
|
+
rows = []
|
|
64
|
+
git = shutil.which("git")
|
|
65
|
+
rows.append({"Tool": "git", "Status": "found" if git else "MISSING (required)", "Path": git or "", "Version": ""})
|
|
66
|
+
sy, tr = resolve_syft(s), resolve_trivy(s)
|
|
67
|
+
rows.append({"Tool": "Syft", "Status": "found" if sy else "not installed (optional)", "Path": sy or "", "Version": (syft_version(sy) if sy else "") or ""})
|
|
68
|
+
trivy_status = "found (opt-in enabled)" if (tr and s.container_scan_enabled) else ("found (opt-in disabled)" if tr else "not installed (optional)")
|
|
69
|
+
rows.append({"Tool": "Trivy (Container Image Scanner)", "Status": trivy_status, "Path": tr or "", "Version": (trivy_version(tr) if tr else "") or ""})
|
|
70
|
+
rows.append({"Tool": "Multi-CI Platform Engine", "Status": "active (5 platforms: GHA, GitLab, Jenkins, CircleCI, Azure)", "Path": "pipeline_analysis/ci_adapters", "Version": "2.2.0"})
|
|
71
|
+
rows.append({"Tool": "Built-in rule engine", "Status": "always available", "Path": "sbom/builtin_generator.py", "Version": "1.0"})
|
|
72
|
+
df(rows, height="content")
|
|
73
|
+
st.caption("Auto mode uses Syft, then Trivy, then the built-in rule engine; Multi-CI engine statically parses GitHub Actions, GitLab CI/CD, Jenkins, CircleCI, and Azure Pipelines.")
|
|
74
|
+
|
|
75
|
+
with t_db:
|
|
76
|
+
h = db.health()
|
|
77
|
+
c = st.columns(4)
|
|
78
|
+
c[0].metric("Schema version", h["schema_version"])
|
|
79
|
+
c[1].metric("Integrity", h["integrity"])
|
|
80
|
+
c[2].metric("Size", _mb(h["size_bytes"]))
|
|
81
|
+
c[3].metric("Journal", h["journal_mode"])
|
|
82
|
+
df([{"Table": k, "Rows": v} for k, v in h["tables"].items()], height="content")
|
|
83
|
+
st.caption(f"`{h['path']}`")
|
|
84
|
+
if st.button("Run VACUUM (reclaim space)"):
|
|
85
|
+
import sqlite3
|
|
86
|
+
con = sqlite3.connect(h["path"])
|
|
87
|
+
con.execute("VACUUM")
|
|
88
|
+
con.close()
|
|
89
|
+
st.success("Done.")
|
|
90
|
+
|
|
91
|
+
with t_cache:
|
|
92
|
+
cache = Cache(db)
|
|
93
|
+
stt = cache.stats()
|
|
94
|
+
c = st.columns(3)
|
|
95
|
+
c[0].metric("Rows", f"{stt['total_rows']:,}")
|
|
96
|
+
c[1].metric("Payload", _mb(stt["total_bytes"]))
|
|
97
|
+
c[2].metric("Limits", f"{s.cache_max_age_days} d / {s.cache_max_rows:,} rows")
|
|
98
|
+
now = time.time()
|
|
99
|
+
df([{"Namespace": n["namespace"], "Rows": n["rows"], "Size": _mb(n["bytes"]), "Oldest (days)": round((now - n["oldest"]) / 86400, 1), "Newest (min)": round((now - n["newest"]) / 60, 1)}
|
|
100
|
+
for n in stt["namespaces"]], height="content")
|
|
101
|
+
st.caption("OSV advisories, NVD, CISA KEV, registry metadata (30 days) and deps.dev resolution (7 days) are cached; outages fall back to stale cache and are reported as such.")
|
|
102
|
+
a, b = st.columns(2)
|
|
103
|
+
if a.button("Purge expired / over-limit rows"):
|
|
104
|
+
st.success(str(cache.maintain(s.cache_max_age_days, s.cache_max_rows)))
|
|
105
|
+
ns = b.selectbox("Clear a namespace", [""] + [n["namespace"] for n in stt["namespaces"]], format_func=lambda x: x or "(choose)")
|
|
106
|
+
if ns and b.button(f"Clear '{ns}'"):
|
|
107
|
+
st.success(f"{cache.clear(ns)} rows removed")
|
|
108
|
+
st.rerun()
|
|
109
|
+
|
|
110
|
+
with t_disk:
|
|
111
|
+
rows = [{"Location": "Artifacts (SBOMs, reports, graphs)", "Path": str(s.artifacts_dir), "Size": _mb(_size(s.artifacts_dir))},
|
|
112
|
+
{"Location": "Data (databases)", "Path": str(s.data_dir), "Size": _mb(_size(s.data_dir))},
|
|
113
|
+
{"Location": "Temporary clones", "Path": str(s.workspace_dir), "Size": _mb(_size(s.workspace_dir))}]
|
|
114
|
+
df(rows, height="content")
|
|
115
|
+
left = [d for d in s.workspace_dir.iterdir() if d.is_dir()] if s.workspace_dir.exists() else []
|
|
116
|
+
if left:
|
|
117
|
+
st.warning(f"{len(left)} temporary clone folder(s) present (a scan may be running, or a previous one was interrupted; folders older than {s.workspace_max_age_s // 60} min are swept at the next scan).")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Monitoring: watch list and alerts for newly disclosed / newly exploited vulnerabilities in stored inventories."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import streamlit as st
|
|
5
|
+
|
|
6
|
+
from config.settings import get_settings
|
|
7
|
+
from monitor.watch import acknowledge, add_watch, events, remove_watch, run_monitor, watchlist
|
|
8
|
+
from storage.database import Database
|
|
9
|
+
from ui.components.common import df, page_header
|
|
10
|
+
|
|
11
|
+
SEV_ICON = {"CRITICAL": "🟥", "HIGH": "🟧", "MEDIUM": "🟨", "LOW": "🟦"}
|
|
12
|
+
KIND = {"new_vulnerability": "New advisory", "now_exploited": "Now exploited (KEV)", "epss_rise": "Exploit probability rose"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def render() -> None:
|
|
16
|
+
page_header("Continuous Monitoring", "Re-assess stored inventories against newly disclosed vulnerabilities - no re-clone, no re-scan.")
|
|
17
|
+
s = get_settings()
|
|
18
|
+
db = Database(s.db_path)
|
|
19
|
+
repos = []
|
|
20
|
+
seen = set()
|
|
21
|
+
for x in db.list_scans(300):
|
|
22
|
+
if x["status"] != "failed" and not x["repo_url"].startswith(("local:", "local-fixture")) and x["repo_url"] not in seen:
|
|
23
|
+
seen.add(x["repo_url"])
|
|
24
|
+
repos.append(x)
|
|
25
|
+
wl = {w["repo_url"]: w for w in watchlist(db)}
|
|
26
|
+
|
|
27
|
+
c1, c2 = st.columns([2, 1])
|
|
28
|
+
with c1:
|
|
29
|
+
st.markdown("**Watch list**")
|
|
30
|
+
df([{"Repository": x["repo_url"], "Last scan": x["scan_timestamp"], "Commit": x["commit_sha"][:8], "Watched": "yes" if x["repo_url"] in wl else "no", "Last monitor run": (wl.get(x["repo_url"]) or {}).get("last_run") or ""} for x in repos], height=220)
|
|
31
|
+
with c2:
|
|
32
|
+
pick = st.selectbox("Repository", [x["repo_url"] for x in repos] or [""], key="mon_pick")
|
|
33
|
+
a, b = st.columns(2)
|
|
34
|
+
if pick and a.button("Watch", use_container_width=True):
|
|
35
|
+
add_watch(db, pick)
|
|
36
|
+
st.rerun()
|
|
37
|
+
if pick and b.button("Unwatch", use_container_width=True):
|
|
38
|
+
remove_watch(db, pick)
|
|
39
|
+
st.rerun()
|
|
40
|
+
|
|
41
|
+
scope = st.radio("Run against", ["Watched repositories (or all if none watched)", "Selected repository only"], horizontal=True)
|
|
42
|
+
if st.button("Run monitor now", type="primary"):
|
|
43
|
+
with st.spinner("Re-querying OSV, CISA KEV and EPSS for stored inventories..."):
|
|
44
|
+
out = run_monitor(s, db, repo_url=pick if scope.startswith("Selected") else None)
|
|
45
|
+
st.session_state["mon_out"] = out
|
|
46
|
+
out = st.session_state.get("mon_out")
|
|
47
|
+
if out:
|
|
48
|
+
st.success(f"Checked {out['repos_checked']} repository inventory(ies) at {out['checked_at']}: {len(out['alerts'])} new alert(s). Sources: {out['sources']}") if not out["errors"] else st.warning("; ".join(out["errors"][:3]))
|
|
49
|
+
|
|
50
|
+
st.markdown("#### Alerts")
|
|
51
|
+
ev = events(db)
|
|
52
|
+
open_ev = [e for e in ev if not e["acknowledged"]]
|
|
53
|
+
m = st.columns(3)
|
|
54
|
+
m[0].metric("Unacknowledged", len(open_ev))
|
|
55
|
+
m[1].metric("Total recorded", len(ev))
|
|
56
|
+
m[2].metric("Watched", len(wl))
|
|
57
|
+
if not ev:
|
|
58
|
+
st.info("No alerts yet. Alerts appear when an advisory is disclosed (or a CVE becomes known-exploited) after a stored scan.")
|
|
59
|
+
return
|
|
60
|
+
for e in ev[:40]:
|
|
61
|
+
with st.container(border=True):
|
|
62
|
+
l, r_ = st.columns([6, 1])
|
|
63
|
+
l.markdown(f"{SEV_ICON.get(e['severity'], '⬜')} **{KIND.get(e['kind'], e['kind'])}** · {e['title']} \n<span style='opacity:.7'>{e['repo_url']} · {e['at']}</span>", unsafe_allow_html=True)
|
|
64
|
+
if not e["acknowledged"] and r_.button("Acknowledge", key=f"ack{e['id']}"):
|
|
65
|
+
acknowledge(db, e["id"])
|
|
66
|
+
st.rerun()
|
|
67
|
+
st.caption("Schedule it: `python guardian.py monitor` (exit code 1 when there are new alerts) from cron / Task Scheduler / `.github/workflows/guardian.yml`.")
|