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.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,37 @@
1
+ """Findings produced by the Pipeline Agent (container and CI/CD hygiene)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Any, Optional
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+ SEVERITIES = ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO")
10
+ # secret-looking literals; the matched value is NEVER stored or shown (only the rule and the redacted line)
11
+ SECRET_LITERAL = re.compile(r"(gsk_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_\-]{30,}|sk-ant-[A-Za-z0-9_\-]{20,}|sk-[A-Za-z0-9]{32,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|"
12
+ r"AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9\-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)")
13
+
14
+
15
+ def redact_line(s: str) -> str:
16
+ return SECRET_LITERAL.sub("[REDACTED]", s)
17
+
18
+
19
+ class PipelineFinding(BaseModel):
20
+ finding_id: str = ""
21
+ kind: str = "pipeline"
22
+ rule_id: str # e.g. DF003, GHA001
23
+ category: str # container | ci
24
+ ecosystem: str # Docker | GitHub Actions | CI (generic)
25
+ title: str
26
+ severity: str # CRITICAL | HIGH | MEDIUM | LOW | INFO
27
+ file: str
28
+ line: int = 0
29
+ snippet: str = ""
30
+ subject: str = "" # image reference / action reference / command, used for dedup + memory fingerprint
31
+ why: str = ""
32
+ remediation: str = ""
33
+ evidence_strength: str = "high" # high = directly visible in the file; medium = heuristic
34
+ references: list[str] = Field(default_factory=list)
35
+ evidence_id: Optional[str] = None
36
+ scan_timestamp: str = ""
37
+ extra: dict[str, Any] = Field(default_factory=dict)
File without changes
@@ -0,0 +1,216 @@
1
+ """Policy-as-code: declarative YAML rules evaluated over the Guardian's findings, producing a pass/fail gate with the violating evidence.
2
+
3
+ Policy file (see ``policies/default.yaml``)::
4
+
5
+ name: default
6
+ rules:
7
+ - id: no-known-exploited
8
+ description: ...
9
+ when: {kind: vulnerability, kev: true} # all conditions must match (AND)
10
+ action: block # block | warn | info
11
+ exceptions: # optional, time-boxed waivers
12
+ - {rule: epss-high, subject: "lodash@4.17.4", reason: "...", expires: "2027-01-31"}
13
+
14
+ Condition operators: ``field: value`` (equality), ``field: [a, b]`` (any of), ``field_gte/_lte/_gt/_lt: number``, ``license_any: [...]``,
15
+ and ``unless: {...}`` to exclude. A *block* violation fails the gate; *warn* and *info* are reported only. Analyst decisions stored in memory
16
+ (accepted risk / false positive / suppress, with expiry) waive matching findings - waived items stay visible.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any, Optional
23
+
24
+ import yaml
25
+
26
+ ACTIONS = ("block", "warn", "info")
27
+ KNOWN_KEYS = {"kind", "severity", "kev", "epss", "verdict", "reachability", "dependency_type", "ecosystem", "fix_available", "priority", "risk", "confirmed", "rule_id", "category", "third_party",
28
+ "classification", "strength", "scope", "install_script", "deprecated", "integrity", "licenses", "published_age_days", "name", "confidence"}
29
+ POLICY_DIR = Path(__file__).resolve().parent / "resources"
30
+ if not POLICY_DIR.is_dir():
31
+ POLICY_DIR = Path(__file__).resolve().parents[2] / "policies"
32
+
33
+
34
+ class PolicyError(ValueError):
35
+ pass
36
+
37
+
38
+ def load_policy(name_or_path: str) -> dict:
39
+ p = Path(name_or_path)
40
+ if name_or_path in {"default", "strict"} or not p.exists():
41
+ p = POLICY_DIR / (name_or_path if name_or_path.endswith((".yaml", ".yml")) else name_or_path + ".yaml")
42
+ if not p.exists():
43
+ raise PolicyError(f"policy '{name_or_path}' not found (looked in {POLICY_DIR})")
44
+ return parse_policy(p.read_text(encoding="utf-8"), p.stem)
45
+
46
+
47
+ def parse_policy(text: str, default_name: str = "custom") -> dict:
48
+ try:
49
+ d = yaml.safe_load(text) or {}
50
+ except yaml.YAMLError as e:
51
+ raise PolicyError(f"invalid YAML: {e}") from e
52
+ if not isinstance(d, dict) or not isinstance(d.get("rules"), list) or not d["rules"]:
53
+ raise PolicyError("a policy needs a non-empty `rules:` list")
54
+ seen = set()
55
+ for r in d["rules"]:
56
+ if not isinstance(r, dict) or not r.get("id") or not isinstance(r.get("when"), dict):
57
+ raise PolicyError("every rule needs `id` and a `when:` mapping")
58
+ if r["id"] in seen:
59
+ raise PolicyError(f"duplicate rule id '{r['id']}'")
60
+ seen.add(r["id"])
61
+ if r.get("action", "block") not in ACTIONS:
62
+ raise PolicyError(f"rule '{r['id']}': action must be one of {ACTIONS}")
63
+ for blk in (r["when"], r.get("unless") or {}):
64
+ for k in blk:
65
+ base = k.rsplit("_", 1)[0] if k.endswith(("_gte", "_lte", "_gt", "_lt")) else k
66
+ if base not in KNOWN_KEYS and k != "license_any":
67
+ raise PolicyError(f"rule '{r['id']}': unknown condition '{k}' (known: {sorted(KNOWN_KEYS)})")
68
+ d.setdefault("name", default_name)
69
+ return d
70
+
71
+
72
+ def _num(v: Any) -> Optional[float]:
73
+ try:
74
+ return float(v)
75
+ except (TypeError, ValueError):
76
+ return None
77
+
78
+
79
+ def _match_block(fact: dict, cond: dict) -> bool:
80
+ for k, v in cond.items():
81
+ if k == "license_any":
82
+ lic = [str(x).lower() for x in (fact.get("licenses") or [])]
83
+ want = [str(x).lower() for x in (v if isinstance(v, list) else [v])]
84
+ if not any(any(w == l or w in l for w in want) for l in lic):
85
+ return False
86
+ continue
87
+ op = None
88
+ for suf, name in (("_gte", "gte"), ("_lte", "lte"), ("_gt", "gt"), ("_lt", "lt")):
89
+ if k.endswith(suf):
90
+ k, op = k[:-len(suf)], name
91
+ break
92
+ have = fact.get(k)
93
+ if op:
94
+ a, b = _num(have), _num(v)
95
+ if a is None or b is None or not {"gte": a >= b, "lte": a <= b, "gt": a > b, "lt": a < b}[op]:
96
+ return False
97
+ elif isinstance(v, list):
98
+ if have not in v:
99
+ return False
100
+ elif have != v:
101
+ return False
102
+ return True
103
+
104
+
105
+ def matches(fact: dict, rule: dict) -> bool:
106
+ return _match_block(fact, rule["when"]) and not (rule.get("unless") and _match_block(fact, rule["unless"]))
107
+
108
+
109
+ def facts_from_result(r: dict, waivers: Optional[dict[str, dict]] = None) -> list[dict]:
110
+ """Flatten a scan result into evaluable facts (one per finding / component)."""
111
+ risks = {a["finding_id"]: a for a in r.get("risk_assessments", [])}
112
+ fps = (r.get("memory") or {}).get("fingerprints") or {}
113
+ inv = r.get("investigations") or {}
114
+ out: list[dict] = []
115
+ for f in r.get("vulnerabilities", []):
116
+ a = risks.get(f["finding_id"], {})
117
+ out.append({"kind": "vulnerability", "id": f["finding_id"], "subject": f"{f['package_name']}@{f['installed_version']} {f['primary_id']}", "severity": f["severity"], "kev": bool(f["kev"]),
118
+ "epss": f.get("epss"), "verdict": f.get("verdict"), "reachability": (f.get("reachability") or {}).get("status"), "dependency_type": f["dependency_type"], "ecosystem": f["ecosystem"],
119
+ "fix_available": bool(f["fixed_versions"]), "priority": a.get("priority"), "risk": a.get("label"), "confirmed": f["affected_status"] == "confirmed_affected", "name": f["package_name"],
120
+ "confidence": (a.get("confidence") or {}).get("label"), "evidence_ids": (inv.get(f["finding_id"]) or {}).get("evidence_ids", []), "fingerprint": fps.get(f["finding_id"])})
121
+ for kind, lst in (("pipeline", (r.get("pipeline") or {}).get("findings", [])), ("package_risk", (r.get("package_risk") or {}).get("findings", []))):
122
+ for f in lst:
123
+ a = risks.get(f["finding_id"], {})
124
+ out.append({"kind": kind, "id": f["finding_id"], "subject": f"{f['rule_id']} {f['title']}" + (f" ({f['file']})" if kind == "pipeline" else ""), "severity": f["severity"], "rule_id": f["rule_id"],
125
+ "category": f.get("category"), "third_party": bool((f.get("extra") or {}).get("third_party")), "ecosystem": f.get("ecosystem"), "priority": a.get("priority"), "risk": a.get("label"),
126
+ "evidence_ids": [f["evidence_id"]] if f.get("evidence_id") else [], "fingerprint": fps.get(f["finding_id"])})
127
+ for t in r.get("typosquatting", []):
128
+ out.append({"kind": "typosquatting", "id": t["finding_id"], "subject": f"{t['package_name']} resembles {t['similar_to']}", "strength": t["evidence_strength"], "ecosystem": t["ecosystem"],
129
+ "risk": risks.get(t["finding_id"], {}).get("label"), "fingerprint": fps.get(t["finding_id"]), "evidence_ids": []})
130
+ for c in r.get("lockfile_changes", []):
131
+ out.append({"kind": "lockfile_change", "id": c["finding_id"], "subject": f"{c['change_type']} {c['package_name']} ({c['file']})", "classification": c["classification"], "strength": c["evidence_strength"],
132
+ "ecosystem": c["ecosystem"], "risk": risks.get(c["finding_id"], {}).get("label"), "fingerprint": fps.get(c["finding_id"]), "evidence_ids": []})
133
+ # no rule in the shipped policies targets the kinds below; custom policies may, e.g. {kind: sast, severity: [CRITICAL]}
134
+ for kind, key in (("sast", "sast_findings"), ("iac", "iac_findings"), ("supply_chain", "supply_chain_anomalies"),
135
+ ("suspicious_change", "suspicious_changes")):
136
+ found = r.get(key) or []
137
+ if isinstance(found, dict):
138
+ found = found.get("findings") or []
139
+ for f in found:
140
+ fid = str(f.get("finding_id") or f.get("id") or "")
141
+ out.append({"kind": kind, "id": fid, "subject": f"{f.get('rule_id') or ''} {f.get('title') or ''} ({f.get('file_path') or f.get('affected_file') or ''})".strip(),
142
+ "severity": str(f.get("severity") or "UNKNOWN").upper(), "rule_id": f.get("rule_id"), "category": f.get("category"),
143
+ "classification": f.get("classification") or f.get("evidence_type"), "fingerprint": fps.get(fid), "evidence_ids": []})
144
+ scan_ts = (r.get("repo") or {}).get("scan_timestamp", "")
145
+ for c in r.get("components", []):
146
+ if c.get("is_self") or c.get("type") in ("file", "container"):
147
+ continue
148
+ age = None
149
+ if c.get("published_at") and scan_ts:
150
+ try:
151
+ age = (time.mktime(time.strptime(scan_ts, "%Y-%m-%dT%H:%M:%SZ")) - time.mktime(time.strptime(c["published_at"][:19], "%Y-%m-%dT%H:%M:%S"))) / 86400
152
+ except ValueError:
153
+ age = None
154
+ out.append({"kind": "component", "id": c["bom_ref"], "subject": f"{c['name']}@{c['version']}", "name": c["name"], "ecosystem": c.get("ecosystem"), "licenses": c.get("licenses") or [], "scope": c.get("scope"),
155
+ "install_script": bool(c.get("install_script")), "deprecated": bool(c.get("deprecated")), "integrity": (c.get("integrity") or {}).get("status"), "published_age_days": age,
156
+ "evidence_ids": [], "fingerprint": None})
157
+ return out
158
+
159
+
160
+ def evaluate(policy: dict, result: dict, waivers: Optional[dict[str, dict]] = None, today: Optional[str] = None) -> dict[str, Any]:
161
+ """Evaluate ``policy`` against a scan result. ``waivers``: fingerprint -> active memory decision."""
162
+ waivers = waivers or {}
163
+ today = today or time.strftime("%Y-%m-%d", time.gmtime())
164
+ exc = [e for e in policy.get("exceptions") or [] if isinstance(e, dict) and (not e.get("expires") or str(e["expires"]) >= today)]
165
+ facts = facts_from_result(result)
166
+ violations, waived = [], []
167
+ for rule in policy["rules"]:
168
+ action = rule.get("action", "block")
169
+ for f in facts:
170
+ if f["kind"] != rule["when"].get("kind", f["kind"]) and "kind" in rule["when"] and not isinstance(rule["when"]["kind"], list):
171
+ continue
172
+ if not matches(f, rule):
173
+ continue
174
+ v = {"rule_id": rule["id"], "action": action, "description": rule.get("description", ""), "finding_id": f["id"], "kind": f["kind"], "subject": f["subject"], "evidence_ids": f.get("evidence_ids", [])}
175
+ wf = waivers.get(f.get("fingerprint") or "")
176
+ fe = next((e for e in exc if e.get("rule") == rule["id"] and (not e.get("subject") or e["subject"] in f["subject"])), None)
177
+ if wf or fe:
178
+ v["waiver"] = {"source": "analyst decision" if wf else "policy exception", "reason": (wf or fe).get("reason", ""), "expires": (wf or fe).get("expires_at") or (wf or fe).get("expires")}
179
+ waived.append(v)
180
+ else:
181
+ violations.append(v)
182
+ blocking = [v for v in violations if v["action"] == "block"]
183
+ by_rule: dict[str, int] = {}
184
+ for v in violations:
185
+ by_rule[v["rule_id"]] = by_rule.get(v["rule_id"], 0) + 1
186
+ from reporting.view import coverage
187
+ cov = coverage(result)
188
+ return {"coverage_complete": cov["complete"], "coverage_gaps": cov["gaps"],
189
+ "policy": policy.get("name"), "description": policy.get("description", ""), "passed": not blocking, "blocking": len(blocking), "warnings": sum(1 for v in violations if v["action"] == "warn"),
190
+ "info": sum(1 for v in violations if v["action"] == "info"), "waived": len(waived), "violations": violations, "waived_items": waived, "by_rule": by_rule,
191
+ "rules_evaluated": len(policy["rules"]), "facts_evaluated": len(facts), "evaluated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
192
+
193
+
194
+ def to_rego(policy: dict) -> str:
195
+ """Illustrative Rego (OPA/Conftest) export of the same rules over the flattened facts. The YAML engine remains authoritative."""
196
+ def cond(k, v):
197
+ for suf, op in (("_gte", ">="), ("_lte", "<="), ("_gt", ">"), ("_lt", "<")):
198
+ if k.endswith(suf):
199
+ return f"f.{k[:-len(suf)]} {op} {v}"
200
+ if k == "license_any":
201
+ return "some l in f.licenses; some w in " + str([str(x).lower() for x in v]) + "; contains(lower(l), w)"
202
+ if isinstance(v, list):
203
+ return f"f.{k} in {v!r}".replace("'", '"')
204
+ return f"f.{k} == " + (str(v).lower() if isinstance(v, bool) else f'"{v}"' if isinstance(v, str) else str(v))
205
+ lines = ["package guardian", "", "import rego.v1", "", "# Generated from policies/*.yaml - input.facts is the flattened findings/components list.", ""]
206
+ for action in ("block", "warn", "info"):
207
+ lines.append(f"{'deny' if action == 'block' else action} contains msg if {{" if False else "")
208
+ for r in policy["rules"]:
209
+ name = {"block": "deny", "warn": "warn", "info": "info"}[r.get("action", "block")]
210
+ body = [f" some f in input.facts"] + [f" {cond(k, v)}" for k, v in r["when"].items()]
211
+ lines.append(f"{name} contains msg if {{")
212
+ lines += body
213
+ lines.append(f' msg := sprintf("{r["id"]}: %v", [f.subject])')
214
+ lines.append("}")
215
+ lines.append("")
216
+ return "\n".join(lines)
@@ -0,0 +1,56 @@
1
+ name: default
2
+ description: Balanced gate - block what is exploited, reachable and severe, or tampered; warn on hygiene.
3
+ rules:
4
+ - id: no-known-exploited
5
+ description: A vulnerability listed in the CISA KEV catalog is being exploited in the wild.
6
+ when: {kind: vulnerability, kev: true, confirmed: true}
7
+ action: block
8
+ - id: no-reachable-critical
9
+ description: A CRITICAL vulnerability in a package the application imports (directly or through its parent).
10
+ when: {kind: vulnerability, severity: [CRITICAL], reachability: [used_by_app, reachable_via_dependency], confirmed: true}
11
+ action: block
12
+ - id: likely-exploitable
13
+ description: The Investigator judged the finding likely exploitable (imported + KEV/EPSS/CVSS support).
14
+ when: {kind: vulnerability, verdict: [exploitable_likely]}
15
+ action: block
16
+ - id: high-exploit-probability
17
+ description: EPSS estimates at least a 50% chance of exploitation within 30 days.
18
+ when: {kind: vulnerability, epss_gte: 0.5, confirmed: true}
19
+ action: warn
20
+ - id: high-severity-with-fix
21
+ description: A HIGH/CRITICAL vulnerability that already has a fixed version.
22
+ when: {kind: vulnerability, severity: [HIGH, CRITICAL], fix_available: true, confirmed: true}
23
+ action: warn
24
+ - id: lockfile-digest-mismatch
25
+ description: A lockfile digest differs from the registry digest for the same version (possible tampering).
26
+ when: {kind: package_risk, rule_id: [PKG-INT]}
27
+ action: block
28
+ - id: critical-pipeline-finding
29
+ description: A critical CI/CD or container configuration flaw (e.g. privileged workflow running PR code, committed credential).
30
+ when: {kind: pipeline, severity: [CRITICAL]}
31
+ action: block
32
+ - id: high-pipeline-finding
33
+ description: A high-severity CI/CD or container configuration flaw.
34
+ when: {kind: pipeline, severity: [HIGH]}
35
+ action: warn
36
+ - id: unpinned-third-party-action
37
+ description: A third-party GitHub Action is not pinned to a commit SHA.
38
+ when: {kind: pipeline, rule_id: [GHA001], third_party: true}
39
+ action: warn
40
+ - id: suspicious-lockfile-change
41
+ description: A lockfile change classified as potentially suspicious.
42
+ when: {kind: lockfile_change, classification: [potentially_suspicious]}
43
+ action: block
44
+ - id: typosquat-high
45
+ description: A package name that strongly resembles a popular package and is corroborated by the registry.
46
+ when: {kind: typosquatting, strength: [high]}
47
+ action: warn
48
+ - id: copyleft-license
49
+ description: A strong-copyleft licence in a dependency (review compatibility with your distribution model).
50
+ when: {kind: component, license_any: [GPL-2.0, GPL-3.0, AGPL-3.0, AGPL-1.0]}
51
+ unless: {scope: dev}
52
+ action: warn
53
+ - id: very-new-direct-release
54
+ description: A package version published less than 7 days before the scan.
55
+ when: {kind: component, published_age_days_lt: 7}
56
+ action: info
@@ -0,0 +1,35 @@
1
+ name: strict
2
+ description: Strict gate for release pipelines - every confirmed HIGH/CRITICAL with a fix, any reachable vulnerability and any pipeline weakness above LOW blocks.
3
+ rules:
4
+ - id: no-known-exploited
5
+ when: {kind: vulnerability, kev: true, confirmed: true}
6
+ action: block
7
+ - id: no-high-or-critical-with-fix
8
+ description: HIGH/CRITICAL vulnerabilities that can be fixed by upgrading must be fixed.
9
+ when: {kind: vulnerability, severity: [HIGH, CRITICAL], fix_available: true, confirmed: true}
10
+ action: block
11
+ - id: no-reachable-vulnerability
12
+ description: Any confirmed vulnerability in a package the application imports.
13
+ when: {kind: vulnerability, reachability: [used_by_app], confirmed: true}
14
+ action: block
15
+ - id: lockfile-digest-mismatch
16
+ when: {kind: package_risk, rule_id: [PKG-INT]}
17
+ action: block
18
+ - id: pipeline-medium-and-above
19
+ description: Container/CI findings of MEDIUM severity or higher.
20
+ when: {kind: pipeline, severity: [CRITICAL, HIGH, MEDIUM]}
21
+ action: block
22
+ - id: any-lockfile-anomaly
23
+ when: {kind: lockfile_change, classification: [potentially_suspicious, unexplained_change]}
24
+ action: block
25
+ - id: typosquat
26
+ when: {kind: typosquatting}
27
+ action: block
28
+ - id: copyleft-license
29
+ when: {kind: component, license_any: [GPL-2.0, GPL-3.0, AGPL-3.0, AGPL-1.0, LGPL-3.0]}
30
+ action: block
31
+ - id: install-script-unattested
32
+ description: Packages that run code at install time.
33
+ when: {kind: component, install_script: true}
34
+ unless: {scope: dev}
35
+ action: warn
File without changes
@@ -0,0 +1,186 @@
1
+ """Application Reachability Analysis for Contextual Risk Scoring v2.0.
2
+
3
+ Extracts vulnerable symbols from advisories and evaluates application code reachability:
4
+ Confirmed reachable: 100
5
+ Potentially reachable: 60
6
+ Unreachable with evidence: 0
7
+ Unknown: None (preserved for missing-evidence policy)
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import Any, Optional
13
+
14
+ from reachability.scanners import LANG_ECO, SourceIndex, Usage, _matches
15
+ from risk_analysis.contextual_scorer import DimensionScore
16
+
17
+ # Patterns for extracting functions, methods, classes, and backticked symbols from advisories
18
+ _SYMBOL_PATTERN = re.compile(r"""(?:`([A-Za-z_][A-Za-z0-9_.]*(?:\(\))?)`|in\s+function\s+['"]?([A-Za-z_][A-Za-z0-9_.]*)['"]?|method\s+['"]?([A-Za-z_][A-Za-z0-9_.]*)['"]?|class\s+['"]?([A-Za-z_][A-Za-z0-9_.]*)['"]?)""", re.IGNORECASE)
19
+
20
+ _COMMON_VULN_TERMS = {
21
+ "parse", "parser", "load", "loads", "eval", "execute", "render", "template", "serialize", "deserialize",
22
+ "validate", "sanitize", "decode", "encode", "query", "request", "format", "read", "write", "upload",
23
+ "authenticate", "verify", "sign", "verify_token", "hash", "decrypt", "encrypt", "check", "exec", "run"
24
+ }
25
+
26
+
27
+ def extract_vulnerable_symbols(summary: Optional[str] = None, details: Optional[str] = None) -> list[str]:
28
+ """Extract named functions, methods, and classes mentioned in the vulnerability advisory."""
29
+ text = f"{summary or ''}\n{details or ''}"
30
+ if not text.strip():
31
+ return []
32
+
33
+ found = set()
34
+ for m in _SYMBOL_PATTERN.finditer(text):
35
+ for g in m.groups():
36
+ if g:
37
+ clean = g.strip().rstrip("()").split(".")[-1]
38
+ if clean and len(clean) >= 3 and not clean.isupper() and not clean.startswith(("CVE-", "GHSA-")):
39
+ found.add(clean)
40
+
41
+ # Check for prominent function-like keywords in backticks
42
+ words = set(re.findall(r"\b[a-zA-Z_][a-zA-Z0-9_]{2,}\b", text.lower()))
43
+ for term in _COMMON_VULN_TERMS:
44
+ if term in words and (f"`{term}`" in text.lower() or f"{term}(" in text.lower()):
45
+ found.add(term)
46
+
47
+ return sorted(found)[:10]
48
+
49
+
50
+ def evaluate_app_reachability(
51
+ package_name: str,
52
+ ecosystem: str,
53
+ source_index: Optional[SourceIndex],
54
+ vulnerable_symbols: Optional[list[str]] = None,
55
+ dependency_type: str = "direct",
56
+ roots: Optional[list[str]] = None,
57
+ is_dev: bool = False,
58
+ ) -> DimensionScore:
59
+ """Evaluate Dimension A (Application Code Reachability) on a 0-100 scale."""
60
+ dim_name = "Application Code Reachability"
61
+ weight = 0.20
62
+
63
+ if not source_index:
64
+ return DimensionScore(
65
+ dimension="A",
66
+ name=dim_name,
67
+ weight=weight,
68
+ raw_value="unindexed",
69
+ normalized_score=None,
70
+ status="unknown",
71
+ weighted_contribution=0.0,
72
+ evidence=["Source code index was not available for reachability assessment"],
73
+ confidence="none",
74
+ )
75
+
76
+ lang = next((l for l, e in LANG_ECO.items() if e == ecosystem), None)
77
+ if not lang or not source_index.files_by_lang.get(lang):
78
+ return DimensionScore(
79
+ dimension="A",
80
+ name=dim_name,
81
+ weight=weight,
82
+ raw_value="no_ecosystem_files",
83
+ normalized_score=None,
84
+ status="unknown",
85
+ weighted_contribution=0.0,
86
+ evidence=[f"No {ecosystem} source files found in repository"],
87
+ confidence="none",
88
+ )
89
+
90
+ # Search for matching usages
91
+ usages = [u for u in source_index.by_lang.get(lang, []) if _matches(ecosystem, package_name, u.module)]
92
+ app_usages = [u for u in usages if not u.test]
93
+ test_usages = [u for u in usages if u.test]
94
+
95
+ app_files = sorted({u.path for u in app_usages})
96
+ test_files = sorted({u.path for u in test_usages})
97
+ symbols = vulnerable_symbols or []
98
+
99
+ # Check for vulnerable symbol call sites if symbols were extracted
100
+ matched_symbols: list[str] = []
101
+ if symbols and app_usages:
102
+ for u in app_usages:
103
+ for s in symbols:
104
+ if s.lower() in u.module.lower():
105
+ matched_symbols.append(s)
106
+
107
+ # Evaluation logic
108
+ if app_files:
109
+ loc_sample = [f"{u.path}:{u.line}" for u in app_usages[:3]]
110
+ if matched_symbols:
111
+ return DimensionScore(
112
+ dimension="A",
113
+ name=dim_name,
114
+ weight=weight,
115
+ raw_value={"app_files": len(app_files), "matched_symbols": matched_symbols},
116
+ normalized_score=100.0,
117
+ status="confirmed_reachable",
118
+ weighted_contribution=round(weight * 100.0, 2),
119
+ evidence=[
120
+ f"Confirmed reachable: vulnerable symbol(s) {matched_symbols} matched in application code",
121
+ f"Imported in {len(app_files)} application file(s): {', '.join(loc_sample)}",
122
+ ],
123
+ confidence="high",
124
+ )
125
+ # Package imported without direct symbol proof
126
+ score = 80.0 if len(app_files) >= 5 else 60.0
127
+ return DimensionScore(
128
+ dimension="A",
129
+ name=dim_name,
130
+ weight=weight,
131
+ raw_value={"app_files": len(app_files), "symbols": [u.module for u in app_usages[:5]]},
132
+ normalized_score=score,
133
+ status="potentially_reachable",
134
+ weighted_contribution=round(weight * score, 2),
135
+ evidence=[
136
+ f"Potentially reachable: imported in {len(app_files)} application file(s)",
137
+ f"Locations: {', '.join(loc_sample)}",
138
+ ],
139
+ confidence="medium",
140
+ )
141
+
142
+ if test_files:
143
+ return DimensionScore(
144
+ dimension="A",
145
+ name=dim_name,
146
+ weight=weight,
147
+ raw_value={"test_files": len(test_files)},
148
+ normalized_score=0.0,
149
+ status="test_only",
150
+ weighted_contribution=0.0,
151
+ evidence=[
152
+ f"Excluded from application runtime: imported only in {len(test_files)} test file(s)",
153
+ f"Test files: {', '.join(test_files[:3])}",
154
+ ],
155
+ confidence="high",
156
+ )
157
+
158
+ # If it's a transitive dependency, check if its parent roots are imported
159
+ if dependency_type == "transitive" and roots:
160
+ return DimensionScore(
161
+ dimension="A",
162
+ name=dim_name,
163
+ weight=weight,
164
+ raw_value={"transitive_roots": roots},
165
+ normalized_score=40.0,
166
+ status="transitive_reachable",
167
+ weighted_contribution=round(weight * 40.0, 2),
168
+ evidence=[
169
+ f"Transitive dependency pulled in by application root(s): {', '.join(roots[:3])}",
170
+ "Direct application import not found, but execution path exists via parent dependency",
171
+ ],
172
+ confidence="medium",
173
+ )
174
+
175
+ # Completely unimported
176
+ return DimensionScore(
177
+ dimension="A",
178
+ name=dim_name,
179
+ weight=weight,
180
+ raw_value="not_imported",
181
+ normalized_score=0.0,
182
+ status="unreachable",
183
+ weighted_contribution=0.0,
184
+ evidence=["No imports found in application source code; unreached via static imports"],
185
+ confidence="high",
186
+ )