sourcecode 4.7.0__py3-none-any.whl → 4.9.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.
sourcecode/__init__.py CHANGED
@@ -4,4 +4,4 @@ ASK Engine is the product. ``ask`` is the canonical CLI command; ``sourcecode``
4
4
  the legacy compatibility alias and the Python/PyPI package name. See
5
5
  docs/PRODUCT_IDENTITY.md (normative)."""
6
6
 
7
- __version__ = "4.7.0"
7
+ __version__ = "4.9.0"
@@ -0,0 +1,147 @@
1
+ """Signed audit report over existing ASK evidence.
2
+
3
+ This module packages facts other commands already publish. It does not score ROI,
4
+ choose a fix, or introduce a second judgement layer: the report summary is a
5
+ reader-friendly index over the embedded evidence blocks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+ from typing import Any, Optional
16
+
17
+ from sourcecode import __version__
18
+
19
+ AUDIT_REPORT_SCHEMA = "audit-report-v1"
20
+
21
+
22
+ def _canonical_json(data: dict[str, Any]) -> bytes:
23
+ return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
24
+
25
+
26
+ def _sign(payload: dict[str, Any], key: bytes) -> dict[str, str]:
27
+ canonical = _canonical_json(payload)
28
+ return {
29
+ "algorithm": "hmac-sha256",
30
+ "payload_sha256": hashlib.sha256(canonical).hexdigest(),
31
+ "key_id": hashlib.sha256(key).hexdigest()[:12],
32
+ "signature": hmac.new(key, canonical, hashlib.sha256).hexdigest(),
33
+ }
34
+
35
+
36
+ def build_audit_report(
37
+ root: Path,
38
+ *,
39
+ profiles: Optional[set[str]] = None,
40
+ sign_key: Optional[bytes] = None,
41
+ risk_limit: int = 10,
42
+ ) -> dict[str, Any]:
43
+ """Build the buyer-readable audit bundle from existing command payloads."""
44
+ from sourcecode.posture import build_posture
45
+ from sourcecode.risk import build_risk
46
+
47
+ root = Path(root).resolve()
48
+ risk = build_risk(root, limit=risk_limit, min_band="low", profiles=profiles)
49
+ posture = build_posture(root, profiles or set())
50
+ top_risks = risk.get("risks", [])[:risk_limit]
51
+ access = ((posture.get("endpoints") or {}).get("effective_access") or {})
52
+
53
+ unsigned: dict[str, Any] = {
54
+ "schema_version": AUDIT_REPORT_SCHEMA,
55
+ "tool": {"name": "ask", "version": __version__},
56
+ "generated_at": datetime.now(timezone.utc).isoformat(),
57
+ "repository": {"path": str(root)},
58
+ **({"profile_set": sorted(profiles)} if profiles else {}),
59
+ "summary": {
60
+ "risk_model": risk.get("model"),
61
+ "total_defects": risk.get("total_defects"),
62
+ "total_findings": risk.get("total_findings"),
63
+ "risk_bands": risk.get("by_band", {}),
64
+ "top_risks_shown": len(top_risks),
65
+ "endpoint_access": access.get("summary", {}),
66
+ "unresolved_beans": len(posture.get("unresolved") or []),
67
+ },
68
+ "top_risks": top_risks,
69
+ "evidence": {
70
+ "risk": risk,
71
+ "posture": posture,
72
+ },
73
+ "limits": {
74
+ "statement": (
75
+ "This report packages existing ASK evidence. It does not certify "
76
+ "compliance, choose fixes, assign ROI, or replace a human audit decision."
77
+ ),
78
+ "non_coverage": (risk.get("non_coverage") or {}).get("items", []),
79
+ },
80
+ }
81
+ # Sign and publish the same JSON-normalized material. Some embedded evidence
82
+ # may contain tuples or other JSON-coercible values; normalizing before signing
83
+ # avoids a signature over an in-memory shape the user never receives.
84
+ normalized = json.loads(_canonical_json(unsigned).decode("utf-8"))
85
+ if sign_key:
86
+ normalized["signature"] = _sign(normalized, sign_key)
87
+ return normalized
88
+
89
+
90
+ def render_markdown(report: dict[str, Any]) -> str:
91
+ """Human report renderer over the JSON contract."""
92
+ summary = report.get("summary") or {}
93
+ repo = (report.get("repository") or {}).get("path", "")
94
+ profile = ", ".join(report.get("profile_set") or []) or "default"
95
+ lines = [
96
+ "# ASK Audit Report",
97
+ "",
98
+ f"- Repository: `{repo}`",
99
+ f"- ASK version: `{(report.get('tool') or {}).get('version', '')}`",
100
+ f"- Profile set: `{profile}`",
101
+ f"- Total defects: `{summary.get('total_defects')}`",
102
+ f"- Risk bands: `{summary.get('risk_bands')}`",
103
+ f"- Endpoint access: `{summary.get('endpoint_access')}`",
104
+ "",
105
+ "## Top Risks",
106
+ "",
107
+ ]
108
+ risks = report.get("top_risks") or []
109
+ if not risks:
110
+ lines.append("No composed risks were reported.")
111
+ else:
112
+ lines.extend([
113
+ "| Band | Score | Rules | File | Line | Title |",
114
+ "|---|---:|---|---|---:|---|",
115
+ ])
116
+ for row in risks:
117
+ rules = ", ".join(str(r) for r in row.get("rule_ids", []))
118
+ lines.append(
119
+ "| "
120
+ + " | ".join([
121
+ str(row.get("band", "")),
122
+ str(row.get("severity_effective", "")),
123
+ rules,
124
+ str(row.get("source_file", "")),
125
+ str(row.get("first_line", "")),
126
+ str(row.get("title", "")).replace("|", "\\|"),
127
+ ])
128
+ + " |"
129
+ )
130
+ lines.extend([
131
+ "",
132
+ "## Limits",
133
+ "",
134
+ str((report.get("limits") or {}).get("statement", "")),
135
+ ])
136
+ signature = report.get("signature")
137
+ if isinstance(signature, dict):
138
+ lines.extend([
139
+ "",
140
+ "## Signature",
141
+ "",
142
+ f"- Algorithm: `{signature.get('algorithm')}`",
143
+ f"- Payload SHA-256: `{signature.get('payload_sha256')}`",
144
+ f"- Key ID: `{signature.get('key_id')}`",
145
+ f"- Signature: `{signature.get('signature')}`",
146
+ ])
147
+ return "\n".join(lines) + "\n"