inspectra-cli 2.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.
- inspectra/__init__.py +6 -0
- inspectra/__main__.py +6 -0
- inspectra/analysis/__init__.py +1 -0
- inspectra/analysis/recommendations.py +40 -0
- inspectra/analysis/risk.py +61 -0
- inspectra/baseline.py +94 -0
- inspectra/checks/__init__.py +79 -0
- inspectra/checks/context.py +29 -0
- inspectra/checks/directories.py +126 -0
- inspectra/checks/dns.py +141 -0
- inspectra/checks/fingerprint.py +102 -0
- inspectra/checks/headers.py +90 -0
- inspectra/checks/http.py +301 -0
- inspectra/checks/ports.py +179 -0
- inspectra/checks/robots.py +120 -0
- inspectra/checks/tls.py +212 -0
- inspectra/cli.py +413 -0
- inspectra/data/directory_wordlist.txt +170 -0
- inspectra/data/fingerprints.json +156 -0
- inspectra/data/header_rules.json +77 -0
- inspectra/models.py +138 -0
- inspectra/network.py +113 -0
- inspectra/orchestrator.py +145 -0
- inspectra/py.typed +0 -0
- inspectra/redact.py +92 -0
- inspectra/replay.py +195 -0
- inspectra/report/__init__.py +1 -0
- inspectra/report/html_report.py +69 -0
- inspectra/report/json_report.py +75 -0
- inspectra/report/markdown_report.py +86 -0
- inspectra/report/sarif_report.py +136 -0
- inspectra/report/templates/report.html.j2 +145 -0
- inspectra/safety.py +217 -0
- inspectra/utils.py +116 -0
- inspectra_cli-2.0.0.dist-info/METADATA +468 -0
- inspectra_cli-2.0.0.dist-info/RECORD +39 -0
- inspectra_cli-2.0.0.dist-info/WHEEL +4 -0
- inspectra_cli-2.0.0.dist-info/entry_points.txt +3 -0
- inspectra_cli-2.0.0.dist-info/licenses/LICENSE +21 -0
inspectra/redact.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Secret redaction for Inspectra scan evidence.
|
|
2
|
+
|
|
3
|
+
Redacts sensitive values from finding evidence before any reporter
|
|
4
|
+
serializes them. Applied as a single choke point in the orchestrator.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
#: Header names whose values should be fully redacted.
|
|
12
|
+
SENSITIVE_HEADERS = {
|
|
13
|
+
"authorization",
|
|
14
|
+
"cookie",
|
|
15
|
+
"set-cookie",
|
|
16
|
+
"x-api-key",
|
|
17
|
+
"proxy-authorization",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
#: Pattern for key=value or key: value secrets in evidence text.
|
|
21
|
+
#: Negative lookahead avoids double-redacting [REDACTED] / [REDACTED:jwt] values.
|
|
22
|
+
SECRET_PATTERN = re.compile(
|
|
23
|
+
r"(?i)(api[_-]?key|secret|token|password)\s*[:=]\s*(?!\[REDACTED[:\]])\S+"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
#: JWT pattern: three base64url segments separated by dots.
|
|
27
|
+
JWT_PATTERN = re.compile(r"eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")
|
|
28
|
+
|
|
29
|
+
#: Header-line pattern: Header-Name: value (case-insensitive).
|
|
30
|
+
HEADER_LINE_PATTERN = re.compile(
|
|
31
|
+
r"(?im)^(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*.*$"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
#: URL userinfo credentials: scheme://user:pass@host
|
|
35
|
+
URL_USERINFO_PATTERN = re.compile(r"(?i)(https?://)[^:/?#]+:[^/?#]+(@)")
|
|
36
|
+
|
|
37
|
+
#: URL query tokens: ?key=value or &key=value
|
|
38
|
+
URL_QUERY_PATTERN = re.compile(r"(?i)([?&])(api[_-]?key|token|secret|password)=([^&\s]+)")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def redact_header_value(header_name: str, value: str) -> str:
|
|
42
|
+
"""Redact a sensitive header value.
|
|
43
|
+
|
|
44
|
+
Returns ``[REDACTED:<header>]`` for sensitive headers, or the
|
|
45
|
+
original value for non-sensitive ones.
|
|
46
|
+
"""
|
|
47
|
+
if header_name.lower() in SENSITIVE_HEADERS:
|
|
48
|
+
return f"[REDACTED:{header_name}]"
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def redact_text(text: str) -> str:
|
|
53
|
+
"""Redact secrets and JWTs from arbitrary text.
|
|
54
|
+
|
|
55
|
+
- Header lines: sensitive header names redacted entirely.
|
|
56
|
+
- URL userinfo: credentials replaced.
|
|
57
|
+
- URL query tokens: key kept, value redacted.
|
|
58
|
+
- Key=value secrets: keeps the key, redacts the value.
|
|
59
|
+
- JWTs: replaced with ``[REDACTED:jwt]``.
|
|
60
|
+
"""
|
|
61
|
+
# Redact header lines first.
|
|
62
|
+
text = HEADER_LINE_PATTERN.sub(lambda m: f"{m.group(1)}: [REDACTED]", text)
|
|
63
|
+
# Redact URL userinfo credentials.
|
|
64
|
+
text = URL_USERINFO_PATTERN.sub(lambda m: m.group(1) + "[REDACTED]" + m.group(2), text)
|
|
65
|
+
# Redact URL query tokens.
|
|
66
|
+
text = URL_QUERY_PATTERN.sub(lambda m: m.group(1) + m.group(2) + "= [REDACTED]", text)
|
|
67
|
+
# Redact JWTs (they can contain key=value-like segments).
|
|
68
|
+
text = JWT_PATTERN.sub("[REDACTED:jwt]", text)
|
|
69
|
+
# Redact key=value / key: value secrets.
|
|
70
|
+
text = SECRET_PATTERN.sub(lambda m: m.group(1) + "= [REDACTED]", text)
|
|
71
|
+
return text
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def redact_evidence(evidence: list[str]) -> list[str]:
|
|
75
|
+
"""Redact all strings in an evidence list."""
|
|
76
|
+
return [redact_text(line) for line in evidence]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def redact_headers(headers: dict[str, str]) -> dict[str, str]:
|
|
80
|
+
"""Redact sensitive headers in a dict."""
|
|
81
|
+
return {name: redact_header_value(name, value) for name, value in headers.items()}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def redaction_metadata(disabled: bool = False) -> dict[str, str] | None:
|
|
85
|
+
"""Return report metadata for redaction status.
|
|
86
|
+
|
|
87
|
+
Returns ``{"redaction": "disabled"}`` when redaction is disabled,
|
|
88
|
+
otherwise ``None``.
|
|
89
|
+
"""
|
|
90
|
+
if disabled:
|
|
91
|
+
return {"redaction": "disabled"}
|
|
92
|
+
return None
|
inspectra/replay.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Deterministic replay for Inspectra scans.
|
|
2
|
+
|
|
3
|
+
Record every HTTP request/response to a fixtures directory, then replay scans
|
|
4
|
+
entirely from disk with zero network I/O. Two runs against the same fixtures
|
|
5
|
+
produce byte-identical reports (modulo timestamps), so CI can diff scans and
|
|
6
|
+
detect regressions without touching the network.
|
|
7
|
+
|
|
8
|
+
The Recorder and Replayer both implement the tiny ``get(url, *, headers,
|
|
9
|
+
extensions)`` interface that the HTTP check already uses, so checks do not
|
|
10
|
+
learn about replay.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import base64
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, cast
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
|
|
24
|
+
REPLAY_VERSION = "1"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ReplayMissError(Exception):
|
|
28
|
+
"""Raised when a replayed request has no matching fixture."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, url: str) -> None:
|
|
31
|
+
super().__init__(f"No replay fixture for {url}")
|
|
32
|
+
self.url = url
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _request_key(method: str, url: str) -> str:
|
|
36
|
+
"""Stable fixture key: sha256 of method + space + url."""
|
|
37
|
+
return hashlib.sha256(f"{method} {url}".encode()).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class FixtureStore:
|
|
41
|
+
"""Read/write fixture files for a replay directory.
|
|
42
|
+
|
|
43
|
+
Each request/response pair is stored as ``<key>.json`` with an
|
|
44
|
+
``index.json`` mapping keys to metadata. Keys are content-addressed so the
|
|
45
|
+
same request always maps to the same file.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, directory: Path | str) -> None:
|
|
49
|
+
self.directory = Path(directory)
|
|
50
|
+
self.index: dict[str, dict[str, Any]] = {}
|
|
51
|
+
self._loaded = False
|
|
52
|
+
|
|
53
|
+
def _ensure_loaded(self) -> None:
|
|
54
|
+
if self._loaded:
|
|
55
|
+
return
|
|
56
|
+
index_path = self.directory / "index.json"
|
|
57
|
+
if index_path.exists():
|
|
58
|
+
self.index = json.loads(index_path.read_text(encoding="utf-8"))
|
|
59
|
+
else:
|
|
60
|
+
self.index = {}
|
|
61
|
+
self._loaded = True
|
|
62
|
+
|
|
63
|
+
def _persist_index(self) -> None:
|
|
64
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
index_path = self.directory / "index.json"
|
|
66
|
+
index_path.write_text(
|
|
67
|
+
json.dumps(self.index, indent=2, sort_keys=True) + "\n",
|
|
68
|
+
encoding="utf-8",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def record(
|
|
72
|
+
self,
|
|
73
|
+
method: str,
|
|
74
|
+
url: str,
|
|
75
|
+
response: httpx.Response,
|
|
76
|
+
elapsed_ms: float,
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Persist one request/response pair to a fixture file."""
|
|
79
|
+
self._ensure_loaded()
|
|
80
|
+
key = _request_key(method, url)
|
|
81
|
+
|
|
82
|
+
# Redact headers through the existing redactor so secrets never hit disk.
|
|
83
|
+
from inspectra.redact import redact_headers
|
|
84
|
+
|
|
85
|
+
headers = {k.lower(): v for k, v in response.headers.items()}
|
|
86
|
+
headers = redact_headers(headers)
|
|
87
|
+
|
|
88
|
+
body_b64 = base64.b64encode(response.content).decode("ascii")
|
|
89
|
+
|
|
90
|
+
record = {
|
|
91
|
+
"key": key,
|
|
92
|
+
"method": method,
|
|
93
|
+
"url": str(response.url),
|
|
94
|
+
"status": response.status_code,
|
|
95
|
+
"headers": headers,
|
|
96
|
+
"body_b64": body_b64,
|
|
97
|
+
"elapsed_ms": round(elapsed_ms, 3),
|
|
98
|
+
"recorded_at": datetime.now(UTC).isoformat(),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
fixture_path = self.directory / f"{key}.json"
|
|
102
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
fixture_path.write_text(
|
|
104
|
+
json.dumps(record, indent=2, sort_keys=True) + "\n",
|
|
105
|
+
encoding="utf-8",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
self.index[key] = {
|
|
109
|
+
"method": method,
|
|
110
|
+
"url": str(response.url),
|
|
111
|
+
"file": f"{key}.json",
|
|
112
|
+
}
|
|
113
|
+
self._persist_index()
|
|
114
|
+
|
|
115
|
+
def load(self, method: str, url: str) -> dict[str, Any]:
|
|
116
|
+
"""Load one recorded request/response pair by key.
|
|
117
|
+
|
|
118
|
+
Raises ReplayMissError when no fixture matches.
|
|
119
|
+
"""
|
|
120
|
+
self._ensure_loaded()
|
|
121
|
+
key = _request_key(method, url)
|
|
122
|
+
if key not in self.index:
|
|
123
|
+
raise ReplayMissError(url)
|
|
124
|
+
entry = self.index[key]
|
|
125
|
+
fixture_path = self.directory / entry["file"]
|
|
126
|
+
try:
|
|
127
|
+
return cast(dict[str, Any], json.loads(fixture_path.read_text(encoding="utf-8")))
|
|
128
|
+
except FileNotFoundError as exc:
|
|
129
|
+
raise ReplayMissError(url) from exc
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class Recorder:
|
|
133
|
+
"""Wrap an httpx.Client and record every request/response to a FixtureStore.
|
|
134
|
+
|
|
135
|
+
Implements the ``get(url, *, headers, extensions)`` interface used by the
|
|
136
|
+
HTTP check, so it can be dropped in for ``context.client``.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(self, client: httpx.Client, store: FixtureStore) -> None:
|
|
140
|
+
self._client = client
|
|
141
|
+
self._store = store
|
|
142
|
+
|
|
143
|
+
def get(
|
|
144
|
+
self,
|
|
145
|
+
url: str,
|
|
146
|
+
*,
|
|
147
|
+
headers: dict[str, str] | None = None,
|
|
148
|
+
extensions: dict[str, Any] | None = None,
|
|
149
|
+
) -> httpx.Response:
|
|
150
|
+
start = datetime.now(UTC)
|
|
151
|
+
response = self._client.get(url, headers=headers, extensions=extensions)
|
|
152
|
+
elapsed_ms = (datetime.now(UTC) - start).total_seconds() * 1000
|
|
153
|
+
self._store.record("GET", str(response.url), response, elapsed_ms)
|
|
154
|
+
return response
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Replayer:
|
|
158
|
+
"""Serve responses from disk with zero network I/O.
|
|
159
|
+
|
|
160
|
+
Implements the same ``get(url, *, headers, extensions)`` interface as
|
|
161
|
+
Recorder, but never constructs an httpx.Client or opens a socket. A cache
|
|
162
|
+
miss raises ReplayMissError -- it never falls back to the network.
|
|
163
|
+
|
|
164
|
+
Implements ``close()`` for compatibility with ``build_client()`` context
|
|
165
|
+
manager usage.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
def __init__(self, store: FixtureStore) -> None:
|
|
169
|
+
self._store = store
|
|
170
|
+
|
|
171
|
+
def get(
|
|
172
|
+
self,
|
|
173
|
+
url: str,
|
|
174
|
+
*,
|
|
175
|
+
headers: dict[str, str] | None = None,
|
|
176
|
+
extensions: dict[str, Any] | None = None,
|
|
177
|
+
) -> httpx.Response:
|
|
178
|
+
record = self._store.load("GET", url)
|
|
179
|
+
return _response_from_record(record)
|
|
180
|
+
|
|
181
|
+
def close(self) -> None:
|
|
182
|
+
"""No-op for context-manager compatibility."""
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _response_from_record(record: dict[str, Any]) -> httpx.Response:
|
|
186
|
+
"""Reconstruct an httpx.Response from a recorded fixture."""
|
|
187
|
+
body = base64.b64decode(record["body_b64"])
|
|
188
|
+
headers = httpx.Headers(record["headers"])
|
|
189
|
+
request = httpx.Request(record["method"], record["url"])
|
|
190
|
+
return httpx.Response(
|
|
191
|
+
status_code=record["status"],
|
|
192
|
+
headers=headers,
|
|
193
|
+
content=body,
|
|
194
|
+
request=request,
|
|
195
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Report package: renderers for JSON, Markdown and HTML output."""
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""HTML report renderer: a polished, fully self-contained report.
|
|
2
|
+
|
|
3
|
+
The template ships inline CSS (no external assets), so ``report.html`` can be
|
|
4
|
+
shared, archived or attached to an email and always renders correctly.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from inspectra.models import ScanResult, Severity
|
|
13
|
+
from inspectra.utils import format_ist
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from jinja2 import Environment
|
|
17
|
+
|
|
18
|
+
SEVERITY_ORDER = ["high", "medium", "low", "info"]
|
|
19
|
+
GOOD_GRADES = {"A+", "A", "B"}
|
|
20
|
+
BAD_GRADES = {"D", "F"}
|
|
21
|
+
|
|
22
|
+
_env: Environment | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _get_env() -> Environment:
|
|
26
|
+
"""Build the Jinja environment on first use (defers the jinja2 import)."""
|
|
27
|
+
global _env
|
|
28
|
+
if _env is None:
|
|
29
|
+
from jinja2 import Environment, PackageLoader, select_autoescape
|
|
30
|
+
|
|
31
|
+
_env = Environment(
|
|
32
|
+
loader=PackageLoader("inspectra.report", "templates"),
|
|
33
|
+
autoescape=select_autoescape(["html", "xml"]),
|
|
34
|
+
trim_blocks=True,
|
|
35
|
+
lstrip_blocks=True,
|
|
36
|
+
)
|
|
37
|
+
return _env
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def render(result: ScanResult) -> str:
|
|
41
|
+
"""Render a :class:`ScanResult` as a self-contained HTML document."""
|
|
42
|
+
template = _get_env().get_template("report.html.j2")
|
|
43
|
+
findings = sorted(
|
|
44
|
+
result.findings,
|
|
45
|
+
key=lambda finding: (SEVERITY_ORDER.index(finding.severity.value), finding.rule_id),
|
|
46
|
+
)
|
|
47
|
+
summary = {
|
|
48
|
+
severity: result.count_by_severity(Severity(severity)) for severity in SEVERITY_ORDER
|
|
49
|
+
}
|
|
50
|
+
return template.render(
|
|
51
|
+
result=result,
|
|
52
|
+
findings=findings,
|
|
53
|
+
summary=summary,
|
|
54
|
+
started_display=format_ist(result.metadata.started_at),
|
|
55
|
+
grade_class=_grade_class(result.grade or "F"),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _grade_class(grade: str) -> str:
|
|
60
|
+
if grade in GOOD_GRADES:
|
|
61
|
+
return "good"
|
|
62
|
+
if grade in BAD_GRADES:
|
|
63
|
+
return "bad"
|
|
64
|
+
return "warn"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def write(result: ScanResult, path: Path) -> None:
|
|
68
|
+
"""Write the HTML report to ``path``."""
|
|
69
|
+
path.write_text(render(result), encoding="utf-8")
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""JSON report renderer: the machine-readable source of truth.
|
|
2
|
+
|
|
3
|
+
The JSON report is always written, so other tools can consume scan results
|
|
4
|
+
without parsing human-oriented formats.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from inspectra.models import Finding, ScanResult, Severity
|
|
13
|
+
from inspectra.utils import IST_LABEL, format_ist
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def render(result: ScanResult) -> dict:
|
|
17
|
+
"""Serialize a :class:`ScanResult` into a JSON-serializable dictionary."""
|
|
18
|
+
data = {
|
|
19
|
+
"tool": result.metadata.tool,
|
|
20
|
+
"version": result.metadata.version,
|
|
21
|
+
"target": result.target.input,
|
|
22
|
+
"started_at": result.metadata.started_at.isoformat(),
|
|
23
|
+
"started_at_ist": format_ist(result.metadata.started_at),
|
|
24
|
+
"timezone_display": IST_LABEL,
|
|
25
|
+
"finished_at": (
|
|
26
|
+
result.metadata.finished_at.isoformat() if result.metadata.finished_at else None
|
|
27
|
+
),
|
|
28
|
+
"duration_seconds": result.metadata.duration_seconds,
|
|
29
|
+
"posture_score": result.posture_score,
|
|
30
|
+
"grade": result.grade,
|
|
31
|
+
"summary": _summary(result),
|
|
32
|
+
"findings": [_finding(finding) for finding in result.findings],
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if getattr(result, "_baseline_summary", None):
|
|
36
|
+
data["baseline"] = result._baseline_summary
|
|
37
|
+
|
|
38
|
+
# Emit scope/redaction metadata when set (M3).
|
|
39
|
+
if result.scope:
|
|
40
|
+
data["scope"] = result.scope
|
|
41
|
+
if result.redaction:
|
|
42
|
+
data["redaction"] = result.redaction
|
|
43
|
+
|
|
44
|
+
return data
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _summary(result: ScanResult) -> dict:
|
|
48
|
+
return {
|
|
49
|
+
"total": result.total_findings,
|
|
50
|
+
"info": result.count_by_severity(Severity.INFO),
|
|
51
|
+
"low": result.count_by_severity(Severity.LOW),
|
|
52
|
+
"medium": result.count_by_severity(Severity.MEDIUM),
|
|
53
|
+
"high": result.count_by_severity(Severity.HIGH),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _finding(finding: Finding) -> dict:
|
|
58
|
+
return {
|
|
59
|
+
"rule_id": finding.rule_id,
|
|
60
|
+
"title": finding.title,
|
|
61
|
+
"category": finding.category,
|
|
62
|
+
"severity": finding.severity.value,
|
|
63
|
+
"confidence": finding.confidence.value,
|
|
64
|
+
"description": finding.description,
|
|
65
|
+
"why_it_matters": finding.why_it_matters,
|
|
66
|
+
"evidence": finding.evidence,
|
|
67
|
+
"recommendation": finding.recommendation,
|
|
68
|
+
"fingerprint": finding.fingerprint,
|
|
69
|
+
"evidence_hash": finding.evidence_hash,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def write(result: ScanResult, path: Path) -> None:
|
|
74
|
+
"""Write the JSON report to ``path``."""
|
|
75
|
+
path.write_text(json.dumps(render(result), indent=2) + "\n", encoding="utf-8")
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Markdown report renderer: the default human-readable format."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from inspectra.models import Finding, ScanResult, Severity
|
|
8
|
+
from inspectra.utils import format_ist
|
|
9
|
+
|
|
10
|
+
SEVERITY_ORDER = [Severity.HIGH, Severity.MEDIUM, Severity.LOW, Severity.INFO]
|
|
11
|
+
|
|
12
|
+
FOOTER = (
|
|
13
|
+
"_This report was generated by Inspectra, a passive security assessment "
|
|
14
|
+
"tool. Inspectra never exploits: it observes, assesses, explains and "
|
|
15
|
+
"reports. Only scan systems you own or are authorized to test._"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def render(result: ScanResult) -> str:
|
|
20
|
+
"""Render a :class:`ScanResult` as Markdown."""
|
|
21
|
+
lines = [
|
|
22
|
+
"# Inspectra Security Assessment Report",
|
|
23
|
+
"",
|
|
24
|
+
f"**Target:** `{result.target.input}`",
|
|
25
|
+
f"**Date:** {format_ist(result.metadata.started_at)}",
|
|
26
|
+
f"**Tool:** {result.metadata.tool} {result.metadata.version}",
|
|
27
|
+
f"**Duration:** {result.metadata.duration_seconds:.1f}s",
|
|
28
|
+
"",
|
|
29
|
+
_posture_line(result),
|
|
30
|
+
"",
|
|
31
|
+
"## Summary",
|
|
32
|
+
"",
|
|
33
|
+
"| Severity | Count |",
|
|
34
|
+
"|----------|-------|",
|
|
35
|
+
]
|
|
36
|
+
for severity in SEVERITY_ORDER:
|
|
37
|
+
lines.append(f"| {severity.value.capitalize()} | {result.count_by_severity(severity)} |")
|
|
38
|
+
lines.append(f"| **Total** | **{result.total_findings}** |")
|
|
39
|
+
lines.append("")
|
|
40
|
+
|
|
41
|
+
if not result.findings:
|
|
42
|
+
lines.append("No findings were recorded during this scan.")
|
|
43
|
+
lines.append("")
|
|
44
|
+
else:
|
|
45
|
+
lines.append("## Findings")
|
|
46
|
+
lines.append("")
|
|
47
|
+
for finding in _ordered(result):
|
|
48
|
+
lines.extend(_finding_section(finding))
|
|
49
|
+
|
|
50
|
+
lines.extend(["---", "", FOOTER, ""])
|
|
51
|
+
return "\n".join(lines)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _posture_line(result: ScanResult) -> str:
|
|
55
|
+
if result.posture_score is None:
|
|
56
|
+
return "## Posture Score: not scored"
|
|
57
|
+
return f"## Posture Score: {result.posture_score:.1f} / 100 ({result.grade})"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _ordered(result: ScanResult) -> list[Finding]:
|
|
61
|
+
return sorted(
|
|
62
|
+
result.findings,
|
|
63
|
+
key=lambda finding: (SEVERITY_ORDER.index(finding.severity), finding.rule_id),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _finding_section(finding: Finding) -> list[str]:
|
|
68
|
+
section = [
|
|
69
|
+
f"### [{finding.severity.value.upper()}] {finding.rule_id} — {finding.title}",
|
|
70
|
+
"",
|
|
71
|
+
f"- **Category:** {finding.category}",
|
|
72
|
+
f"- **Confidence:** {finding.confidence.value.capitalize()}",
|
|
73
|
+
f"- **What was observed:** {finding.description}",
|
|
74
|
+
f"- **Why it matters:** {finding.why_it_matters}",
|
|
75
|
+
f"- **Recommendation:** {finding.recommendation}",
|
|
76
|
+
]
|
|
77
|
+
if finding.evidence:
|
|
78
|
+
section.append("- **Evidence:**")
|
|
79
|
+
section.extend(f" - `{line}`" for line in finding.evidence)
|
|
80
|
+
section.append("")
|
|
81
|
+
return section
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write(result: ScanResult, path: Path) -> None:
|
|
85
|
+
"""Write the Markdown report to ``path``."""
|
|
86
|
+
path.write_text(render(result), encoding="utf-8")
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""SARIF report renderer: machine-readable output for CI code scanning.
|
|
2
|
+
|
|
3
|
+
Produces SARIF 2.1.0 compatible output that GitHub Code Scanning can ingest.
|
|
4
|
+
Each Inspectra finding maps to a SARIF result with rule metadata, so GitHub
|
|
5
|
+
shows readable rule names and deduplicates across runs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from inspectra import __version__
|
|
14
|
+
from inspectra.models import Finding, ScanResult, Severity
|
|
15
|
+
|
|
16
|
+
SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
|
|
17
|
+
SARIF_VERSION = "2.1.0"
|
|
18
|
+
TOOL_NAME = "Inspectra"
|
|
19
|
+
TOOL_INFO_URI = "https://github.com/shashu123456/inspectra"
|
|
20
|
+
|
|
21
|
+
_SEVERITY_TO_LEVEL = {
|
|
22
|
+
Severity.INFO: "note",
|
|
23
|
+
Severity.LOW: "note",
|
|
24
|
+
Severity.MEDIUM: "warning",
|
|
25
|
+
Severity.HIGH: "error",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _rule_id(finding: Finding) -> str:
|
|
30
|
+
return finding.rule_id
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _build_rules(findings: list[Finding]) -> list[dict]:
|
|
34
|
+
"""One rule entry per unique check id, in first-seen order."""
|
|
35
|
+
seen: dict[str, Finding] = {}
|
|
36
|
+
for finding in findings:
|
|
37
|
+
if finding.rule_id not in seen:
|
|
38
|
+
seen[finding.rule_id] = finding
|
|
39
|
+
rules = []
|
|
40
|
+
for finding in seen.values():
|
|
41
|
+
rules.append(
|
|
42
|
+
{
|
|
43
|
+
"id": finding.rule_id,
|
|
44
|
+
"name": finding.title,
|
|
45
|
+
"shortDescription": {"text": finding.title},
|
|
46
|
+
"fullDescription": {"text": finding.why_it_matters},
|
|
47
|
+
"help": {
|
|
48
|
+
"text": f"{finding.why_it_matters}\n\nRecommendation: {finding.recommendation}"
|
|
49
|
+
},
|
|
50
|
+
"properties": {
|
|
51
|
+
"confidence": finding.confidence.value,
|
|
52
|
+
"category": finding.category,
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
return rules
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _build_results(findings: list[Finding]) -> list[dict]:
|
|
60
|
+
results = []
|
|
61
|
+
for index, finding in enumerate(findings):
|
|
62
|
+
# Build physical location from evidence if a URL/path exists.
|
|
63
|
+
location = None
|
|
64
|
+
if finding.evidence:
|
|
65
|
+
evidence_text = finding.evidence[0]
|
|
66
|
+
region: dict = {"startLine": 1, "snippet": {"text": evidence_text[:200]}}
|
|
67
|
+
# If the evidence looks like a URL, put it as artifactLocation.
|
|
68
|
+
if evidence_text.startswith(("http://", "https://")):
|
|
69
|
+
location = {
|
|
70
|
+
"physicalLocation": {
|
|
71
|
+
"artifactLocation": {"uri": evidence_text},
|
|
72
|
+
"region": region,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else:
|
|
76
|
+
location = {
|
|
77
|
+
"physicalLocation": {
|
|
78
|
+
"region": region,
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
result: dict = {
|
|
82
|
+
"ruleId": finding.rule_id,
|
|
83
|
+
"ruleIndex": index,
|
|
84
|
+
"level": _SEVERITY_TO_LEVEL[finding.severity],
|
|
85
|
+
"message": {
|
|
86
|
+
"text": finding.title,
|
|
87
|
+
"markdown": finding.why_it_matters,
|
|
88
|
+
},
|
|
89
|
+
"fixes": [
|
|
90
|
+
{
|
|
91
|
+
"description": {"text": finding.recommendation},
|
|
92
|
+
}
|
|
93
|
+
],
|
|
94
|
+
"properties": {
|
|
95
|
+
"confidence": finding.confidence.value,
|
|
96
|
+
"category": finding.category,
|
|
97
|
+
"evidenceHash": finding.evidence_hash,
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
if location is not None:
|
|
101
|
+
result["locations"] = [location]
|
|
102
|
+
results.append(result)
|
|
103
|
+
return results
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def render(result: ScanResult) -> dict:
|
|
107
|
+
"""Serialize a :class:`ScanResult` into a SARIF 2.1.0 dictionary."""
|
|
108
|
+
run_properties: dict = {}
|
|
109
|
+
if result.scope:
|
|
110
|
+
run_properties["scope"] = result.scope["scope"]
|
|
111
|
+
if result.redaction:
|
|
112
|
+
run_properties["redaction"] = result.redaction["redaction"]
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
"$schema": SARIF_SCHEMA,
|
|
116
|
+
"version": SARIF_VERSION,
|
|
117
|
+
"runs": [
|
|
118
|
+
{
|
|
119
|
+
"tool": {
|
|
120
|
+
"driver": {
|
|
121
|
+
"name": TOOL_NAME,
|
|
122
|
+
"version": __version__,
|
|
123
|
+
"informationUri": TOOL_INFO_URI,
|
|
124
|
+
"rules": _build_rules(result.findings),
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
"results": _build_results(result.findings),
|
|
128
|
+
"properties": run_properties,
|
|
129
|
+
}
|
|
130
|
+
],
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def write(result: ScanResult, path: Path) -> None:
|
|
135
|
+
"""Write the SARIF report to ``path``."""
|
|
136
|
+
path.write_text(json.dumps(render(result), indent=2) + "\n", encoding="utf-8")
|