pentrep 0.1.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.
- pentrep/__init__.py +3 -0
- pentrep/__main__.py +6 -0
- pentrep/cli.py +353 -0
- pentrep/cvss.py +313 -0
- pentrep/diagnostics.py +142 -0
- pentrep/loader.py +532 -0
- pentrep/models.py +358 -0
- pentrep/redact.py +320 -0
- pentrep/render/__init__.py +54 -0
- pentrep/render/context.py +200 -0
- pentrep/render/highlight.py +62 -0
- pentrep/render/html.py +34 -0
- pentrep/render/markdown.py +58 -0
- pentrep/render/md.py +172 -0
- pentrep/render/pdf.py +116 -0
- pentrep/scaffold/assets/logo.png +0 -0
- pentrep/scaffold/evidence/pt-001-sqlmap.png +0 -0
- pentrep/scaffold/findings.yaml +119 -0
- pentrep/stats.py +70 -0
- pentrep/themes/classic/fonts/OFL.txt +104 -0
- pentrep/themes/classic/fonts/SourceCodePro-Regular.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-Bold.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-It.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-Regular.ttf +0 -0
- pentrep/themes/classic/fonts.css +7 -0
- pentrep/themes/classic/partials/appendix.html.j2 +38 -0
- pentrep/themes/classic/partials/cover.html.j2 +17 -0
- pentrep/themes/classic/partials/document_control.html.j2 +22 -0
- pentrep/themes/classic/partials/executive_summary.html.j2 +17 -0
- pentrep/themes/classic/partials/finding.html.j2 +56 -0
- pentrep/themes/classic/partials/macros.html.j2 +7 -0
- pentrep/themes/classic/partials/scope.html.j2 +27 -0
- pentrep/themes/classic/partials/summary_table.html.j2 +13 -0
- pentrep/themes/classic/partials/toc.html.j2 +19 -0
- pentrep/themes/classic/report.html.j2 +35 -0
- pentrep/themes/classic/report.md.j2 +187 -0
- pentrep/themes/classic/style.css +97 -0
- pentrep-0.1.0.dist-info/METADATA +142 -0
- pentrep-0.1.0.dist-info/RECORD +42 -0
- pentrep-0.1.0.dist-info/WHEEL +4 -0
- pentrep-0.1.0.dist-info/entry_points.txt +2 -0
- pentrep-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Report rendering (HTML and Markdown; PDF from M6). Imported lazily by the CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import jinja2
|
|
8
|
+
from markupsafe import Markup
|
|
9
|
+
|
|
10
|
+
from pentrep.render.highlight import highlight
|
|
11
|
+
from pentrep.render.markdown import render_markdown, render_markdown_inline
|
|
12
|
+
|
|
13
|
+
THEME_PACKAGE_PATH = "themes/classic"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _markdown_inline_filter(text: str) -> Markup:
|
|
17
|
+
"""Jinja filter: one line of user Markdown (no paragraph wrapper) → safe HTML."""
|
|
18
|
+
return Markup(render_markdown_inline(text)) # noqa: S704 - markdown-it escapes raw HTML
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _highlight_filter(content: str, language: str | None) -> Markup:
|
|
22
|
+
"""Jinja filter: evidence text → Pygments HTML with inline styles (content escaped)."""
|
|
23
|
+
return Markup(highlight(content, language)) # noqa: S704 - Pygments escapes the content
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _markdown_filter(text: str) -> Markup:
|
|
27
|
+
"""Jinja filter: user Markdown → safe HTML (raw HTML is escaped by the renderer)."""
|
|
28
|
+
return Markup(render_markdown(text)) # noqa: S704 - markdown-it escapes raw HTML (html=False)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def make_environment(template_dir: Path | None) -> jinja2.Environment:
|
|
32
|
+
"""A Jinja environment that searches ``template_dir`` first, then the built-in theme (FR-48).
|
|
33
|
+
|
|
34
|
+
HTML templates (``*.html.j2``) are autoescaped and undefined variables raise. Values from
|
|
35
|
+
findings.yaml are only ever passed as data, never compiled as templates (FR-13).
|
|
36
|
+
"""
|
|
37
|
+
loaders: list[jinja2.BaseLoader] = []
|
|
38
|
+
if template_dir is not None:
|
|
39
|
+
if not template_dir.is_dir():
|
|
40
|
+
raise NotADirectoryError(f"template directory not found: {template_dir}")
|
|
41
|
+
loaders.append(jinja2.FileSystemLoader(template_dir))
|
|
42
|
+
loaders.append(jinja2.PackageLoader("pentrep", THEME_PACKAGE_PATH))
|
|
43
|
+
env = jinja2.Environment(
|
|
44
|
+
loader=jinja2.ChoiceLoader(loaders),
|
|
45
|
+
autoescape=jinja2.select_autoescape(enabled_extensions=("html", "html.j2")),
|
|
46
|
+
undefined=jinja2.StrictUndefined,
|
|
47
|
+
trim_blocks=True,
|
|
48
|
+
lstrip_blocks=True,
|
|
49
|
+
keep_trailing_newline=True,
|
|
50
|
+
)
|
|
51
|
+
env.filters["markdown"] = _markdown_filter
|
|
52
|
+
env.filters["markdown_inline"] = _markdown_inline_filter
|
|
53
|
+
env.filters["highlight"] = _highlight_filter
|
|
54
|
+
return env
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Build the template context documented in docs/templates.md (FR-48)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
from pentrep import __version__
|
|
12
|
+
from pentrep.cvss import Severity
|
|
13
|
+
from pentrep.loader import SNIFF_BYTES, sniff_image_type
|
|
14
|
+
from pentrep.models import Branding, Finding, Report
|
|
15
|
+
from pentrep.redact import RedactionSummary, format_summary
|
|
16
|
+
from pentrep.stats import Stats, compute_stats, finding_severity, sort_findings
|
|
17
|
+
|
|
18
|
+
UNREDACTED_BANNER: Final = "UNREDACTED DRAFT \N{EN DASH} DO NOT DISTRIBUTE" # FR-36 wording
|
|
19
|
+
STATUS_LABELS: Final = {
|
|
20
|
+
"open": "Open",
|
|
21
|
+
"remediated": "Remediated",
|
|
22
|
+
"risk_accepted": "Risk accepted",
|
|
23
|
+
}
|
|
24
|
+
IMAGE_TYPES: Final = { # sniffed type -> (file extension, MIME type)
|
|
25
|
+
"PNG": ("png", "image/png"),
|
|
26
|
+
"JPEG": ("jpg", "image/jpeg"),
|
|
27
|
+
"GIF": ("gif", "image/gif"),
|
|
28
|
+
"WebP": ("webp", "image/webp"),
|
|
29
|
+
"SVG": ("svg", "image/svg+xml"),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _image_info(path: Path) -> tuple[str, str]:
|
|
34
|
+
"""``(extension, MIME type)`` of an image that the loader already validated."""
|
|
35
|
+
with path.open("rb") as handle:
|
|
36
|
+
kind = sniff_image_type(handle.read(SNIFF_BYTES))
|
|
37
|
+
return IMAGE_TYPES[kind or "PNG"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class EvidenceView:
|
|
42
|
+
"""One evidence item, numbered within its finding."""
|
|
43
|
+
|
|
44
|
+
number: int
|
|
45
|
+
type: str
|
|
46
|
+
caption: str
|
|
47
|
+
content: str | None
|
|
48
|
+
language: str | None
|
|
49
|
+
image_path: Path | None
|
|
50
|
+
asset_name: str | None # file name used when the image is copied (Markdown output)
|
|
51
|
+
mime: str | None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class FindingView:
|
|
56
|
+
"""A finding with everything the templates display, precomputed."""
|
|
57
|
+
|
|
58
|
+
id: str
|
|
59
|
+
title: str
|
|
60
|
+
anchor: str
|
|
61
|
+
severity: Severity
|
|
62
|
+
badge: str
|
|
63
|
+
score: float | None
|
|
64
|
+
score_text: str
|
|
65
|
+
vector: str | None
|
|
66
|
+
impact_score: float | None
|
|
67
|
+
exploitability_score: float | None
|
|
68
|
+
status: str
|
|
69
|
+
status_label: str
|
|
70
|
+
cwe: list[tuple[int, str]]
|
|
71
|
+
affected_assets: list[str]
|
|
72
|
+
description: str
|
|
73
|
+
impact: str
|
|
74
|
+
steps_to_reproduce: list[str]
|
|
75
|
+
evidence: list[EvidenceView]
|
|
76
|
+
remediation: str
|
|
77
|
+
references: list[str]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class BrandingView:
|
|
82
|
+
"""Branding with the logo resolved to a file."""
|
|
83
|
+
|
|
84
|
+
company_name: str | None
|
|
85
|
+
accent_color: str
|
|
86
|
+
logo_path: Path | None
|
|
87
|
+
logo_asset_name: str | None
|
|
88
|
+
logo_mime: str | None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class RedactionView:
|
|
93
|
+
"""Redaction state for the cover banner and Appendix B."""
|
|
94
|
+
|
|
95
|
+
enabled: bool
|
|
96
|
+
unredacted: bool
|
|
97
|
+
banner: str
|
|
98
|
+
counts: tuple[tuple[str, int], ...]
|
|
99
|
+
values: int
|
|
100
|
+
images_not_scanned: int
|
|
101
|
+
lines: list[str]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _evidence(finding: Finding, base_dir: Path) -> list[EvidenceView]:
|
|
105
|
+
views = []
|
|
106
|
+
for number, item in enumerate(finding.evidence, 1):
|
|
107
|
+
if item.type == "image":
|
|
108
|
+
path = (base_dir / item.path).resolve()
|
|
109
|
+
ext, mime = _image_info(path)
|
|
110
|
+
views.append(
|
|
111
|
+
EvidenceView(
|
|
112
|
+
number,
|
|
113
|
+
"image",
|
|
114
|
+
item.caption,
|
|
115
|
+
None,
|
|
116
|
+
None,
|
|
117
|
+
path,
|
|
118
|
+
f"{finding.id}-{number}.{ext}",
|
|
119
|
+
mime,
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
language = item.language if item.type == "text" else "http"
|
|
124
|
+
views.append(
|
|
125
|
+
EvidenceView(
|
|
126
|
+
number, item.type, item.caption, item.content, language, None, None, None
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
return views
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _finding_view(finding: Finding, base_dir: Path) -> FindingView:
|
|
133
|
+
severity = finding_severity(finding)
|
|
134
|
+
cvss = finding.cvss
|
|
135
|
+
return FindingView(
|
|
136
|
+
id=finding.id,
|
|
137
|
+
title=finding.title,
|
|
138
|
+
anchor=f"finding-{finding.id.lower()}",
|
|
139
|
+
severity=severity,
|
|
140
|
+
badge=severity.label.lower(),
|
|
141
|
+
score=cvss.base_score if cvss else None,
|
|
142
|
+
score_text=f"{cvss.base_score:.1f}" if cvss else "N/A",
|
|
143
|
+
vector=cvss.vector.canonical() if cvss else None,
|
|
144
|
+
impact_score=cvss.impact if cvss else None,
|
|
145
|
+
exploitability_score=cvss.exploitability if cvss else None,
|
|
146
|
+
status=finding.status,
|
|
147
|
+
status_label=STATUS_LABELS[finding.status],
|
|
148
|
+
cwe=[(n, f"https://cwe.mitre.org/data/definitions/{n}.html") for n in finding.cwe],
|
|
149
|
+
affected_assets=list(finding.affected_assets),
|
|
150
|
+
description=finding.description,
|
|
151
|
+
impact=finding.impact,
|
|
152
|
+
steps_to_reproduce=list(finding.steps_to_reproduce),
|
|
153
|
+
evidence=_evidence(finding, base_dir),
|
|
154
|
+
remediation=finding.remediation,
|
|
155
|
+
references=list(finding.references),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _branding_view(branding: Branding, base_dir: Path) -> BrandingView:
|
|
160
|
+
if branding.logo is None:
|
|
161
|
+
return BrandingView(branding.company_name, branding.accent_color, None, None, None)
|
|
162
|
+
path = (base_dir / branding.logo).resolve()
|
|
163
|
+
ext, mime = _image_info(path)
|
|
164
|
+
return BrandingView(branding.company_name, branding.accent_color, path, f"logo.{ext}", mime)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def generated_at(report: Report) -> str:
|
|
168
|
+
"""``SOURCE_DATE_EPOCH`` as a UTC timestamp when set, else the report date (FR-49)."""
|
|
169
|
+
epoch = os.environ.get("SOURCE_DATE_EPOCH", "").strip()
|
|
170
|
+
if epoch.isdigit():
|
|
171
|
+
moment = dt.datetime.fromtimestamp(int(epoch), tz=dt.UTC)
|
|
172
|
+
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
173
|
+
return report.engagement.report_date.isoformat()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def build_context(report: Report, summary: RedactionSummary, base_dir: Path) -> dict[str, object]:
|
|
177
|
+
"""The template context: ``engagement``, ``branding``, ``findings`` (sorted, FR-42),
|
|
178
|
+
``stats`` (FR-43), ``redaction``, ``generated_at`` and ``pentrep_version``.
|
|
179
|
+
|
|
180
|
+
``report`` must already be redacted; ``base_dir`` is the directory of findings.yaml.
|
|
181
|
+
"""
|
|
182
|
+
stats: Stats = compute_stats(report.findings)
|
|
183
|
+
redaction = RedactionView(
|
|
184
|
+
enabled=summary.enabled,
|
|
185
|
+
unredacted=not summary.enabled,
|
|
186
|
+
banner=UNREDACTED_BANNER,
|
|
187
|
+
counts=summary.counts,
|
|
188
|
+
values=summary.values,
|
|
189
|
+
images_not_scanned=summary.images_not_scanned,
|
|
190
|
+
lines=format_summary(summary),
|
|
191
|
+
)
|
|
192
|
+
return {
|
|
193
|
+
"engagement": report.engagement,
|
|
194
|
+
"branding": _branding_view(report.branding, base_dir),
|
|
195
|
+
"findings": [_finding_view(f, base_dir) for f in sort_findings(report.findings)],
|
|
196
|
+
"stats": stats,
|
|
197
|
+
"redaction": redaction,
|
|
198
|
+
"generated_at": generated_at(report),
|
|
199
|
+
"pentrep_version": __version__,
|
|
200
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Syntax highlighting for evidence with Pygments, as inline styles (no JavaScript, FR-45)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from functools import cache
|
|
8
|
+
from typing import Final
|
|
9
|
+
|
|
10
|
+
from pygments import format as pygments_format
|
|
11
|
+
from pygments.formatters import HtmlFormatter
|
|
12
|
+
from pygments.lexer import Lexer
|
|
13
|
+
from pygments.lexers import HttpLexer, TextLexer, get_lexer_by_name
|
|
14
|
+
from pygments.token import Error, _TokenType
|
|
15
|
+
from pygments.util import ClassNotFound
|
|
16
|
+
|
|
17
|
+
# A line that starts an HTTP message: a request line or a status line.
|
|
18
|
+
_MESSAGE_START: Final = re.compile(
|
|
19
|
+
r"^(?:[A-Z]+ \S+ HTTP/\d(?:\.\d)?|HTTP/\d(?:\.\d)? \d{3}\b)", re.M
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Keep evidence verbatim: Pygments strips leading/trailing newlines and adds one by default.
|
|
23
|
+
VERBATIM: Final = {"stripnl": False, "ensurenl": False}
|
|
24
|
+
|
|
25
|
+
Tokens = list[tuple[_TokenType, str]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@cache
|
|
29
|
+
def _formatter() -> HtmlFormatter[str]:
|
|
30
|
+
return HtmlFormatter(noclasses=True, style="default")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _tokens(lexer: Lexer, text: str) -> Tokens:
|
|
34
|
+
"""Tokens from ``lexer``, or plain text if it reports errors (no red error boxes)."""
|
|
35
|
+
tokens: Tokens = list(lexer.get_tokens(text))
|
|
36
|
+
if any(token is Error for token, _ in tokens):
|
|
37
|
+
return list(TextLexer(**VERBATIM).get_tokens(text))
|
|
38
|
+
return tokens
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _http_messages(content: str) -> Iterator[str]:
|
|
42
|
+
"""Split pasted HTTP traffic into separate messages (request, response, ...)."""
|
|
43
|
+
starts = [m.start() for m in _MESSAGE_START.finditer(content)]
|
|
44
|
+
if not starts or starts[0] != 0:
|
|
45
|
+
starts.insert(0, 0)
|
|
46
|
+
for begin, end in zip(starts, [*starts[1:], len(content)], strict=True):
|
|
47
|
+
yield content[begin:end]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def highlight(content: str, language: str | None) -> str:
|
|
51
|
+
"""Highlighted HTML for evidence text; Pygments escapes the content."""
|
|
52
|
+
if language == "http":
|
|
53
|
+
tokens = [
|
|
54
|
+
t for part in _http_messages(content) for t in _tokens(HttpLexer(**VERBATIM), part)
|
|
55
|
+
]
|
|
56
|
+
else:
|
|
57
|
+
try:
|
|
58
|
+
lexer = get_lexer_by_name(language, **VERBATIM) if language else TextLexer(**VERBATIM)
|
|
59
|
+
except ClassNotFound:
|
|
60
|
+
lexer = TextLexer(**VERBATIM)
|
|
61
|
+
tokens = _tokens(lexer, content)
|
|
62
|
+
return str(pygments_format(tokens, _formatter()))
|
pentrep/render/html.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Self-contained HTML report: inline CSS, images as data: URIs, no scripts (FR-45)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from markupsafe import Markup
|
|
9
|
+
|
|
10
|
+
from pentrep.models import Report
|
|
11
|
+
from pentrep.redact import RedactionSummary
|
|
12
|
+
from pentrep.render import make_environment
|
|
13
|
+
from pentrep.render.context import build_context
|
|
14
|
+
|
|
15
|
+
TEMPLATE = "report.html.j2"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def data_uri(path: Path, mime: str, asset_name: str | None = None) -> str:
|
|
19
|
+
"""Embed a (validated, project-confined) image file as a ``data:`` URI."""
|
|
20
|
+
encoded = base64.b64encode(path.read_bytes()).decode("ascii")
|
|
21
|
+
return f"data:{mime};base64,{encoded}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def render_html(
|
|
25
|
+
report: Report, summary: RedactionSummary, base_dir: Path, template_dir: Path | None = None
|
|
26
|
+
) -> str:
|
|
27
|
+
"""Render the (already redacted) report as one self-contained HTML document."""
|
|
28
|
+
env = make_environment(template_dir)
|
|
29
|
+
if env.loader is None: # pragma: no cover - make_environment always sets a loader
|
|
30
|
+
raise RuntimeError("template loader missing")
|
|
31
|
+
css, _, _ = env.loader.get_source(env, "style.css")
|
|
32
|
+
safe_css = Markup(css) # noqa: S704 - the theme's own stylesheet, not user input
|
|
33
|
+
context = build_context(report, summary, base_dir)
|
|
34
|
+
return env.get_template(TEMPLATE).render(**context, css=safe_css, image_src=data_uri)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Markdown → HTML for user-written fields (FR-13).
|
|
2
|
+
|
|
3
|
+
Raw HTML is escaped, links are limited to http, https and mailto, images are not rendered (so no
|
|
4
|
+
external ``src`` can appear) and headings become bold paragraphs so they don't break the report's
|
|
5
|
+
heading structure (FR-45).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from functools import cache
|
|
12
|
+
from typing import Final
|
|
13
|
+
|
|
14
|
+
from markdown_it import MarkdownIt
|
|
15
|
+
from markdown_it.renderer import RendererHTML
|
|
16
|
+
from markdown_it.token import Token
|
|
17
|
+
from markdown_it.utils import EnvType, OptionsDict
|
|
18
|
+
|
|
19
|
+
SAFE_SCHEMES: Final = ("http://", "https://", "mailto:")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate_link(url: str) -> bool:
|
|
23
|
+
return url.strip().lower().startswith(SAFE_SCHEMES)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _heading_open(
|
|
27
|
+
renderer: RendererHTML, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
|
28
|
+
) -> str:
|
|
29
|
+
return '<p class="md-heading"><strong>'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _heading_close(
|
|
33
|
+
renderer: RendererHTML, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
|
34
|
+
) -> str:
|
|
35
|
+
return "</strong></p>\n"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@cache
|
|
39
|
+
def _parser() -> MarkdownIt:
|
|
40
|
+
md = MarkdownIt("commonmark", {"html": False, "linkify": False, "typographer": False})
|
|
41
|
+
md.enable(["table", "strikethrough"])
|
|
42
|
+
md.disable("image")
|
|
43
|
+
md.validateLink = _validate_link # type: ignore[method-assign] # documented extension point
|
|
44
|
+
md.add_render_rule("heading_open", _heading_open)
|
|
45
|
+
md.add_render_rule("heading_close", _heading_close)
|
|
46
|
+
return md
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def render_markdown(text: str) -> str:
|
|
50
|
+
"""Render CommonMark + GFM tables/strikethrough to safe HTML."""
|
|
51
|
+
html: str = _parser().render(text)
|
|
52
|
+
return html
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def render_markdown_inline(text: str) -> str:
|
|
56
|
+
"""Render one line of Markdown without a surrounding paragraph (list items, steps)."""
|
|
57
|
+
html: str = _parser().renderInline(text)
|
|
58
|
+
return html
|
pentrep/render/md.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""GitHub-Flavored Markdown report (FR-47).
|
|
2
|
+
|
|
3
|
+
Templates are not autoescaped (Markdown is not HTML), so every value goes through a filter:
|
|
4
|
+
``md_inline`` for plain text, ``md_block`` for user Markdown, ``md_cell`` for table cells.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Final
|
|
13
|
+
|
|
14
|
+
from pentrep.models import Report
|
|
15
|
+
from pentrep.redact import RedactionSummary
|
|
16
|
+
from pentrep.render import make_environment
|
|
17
|
+
from pentrep.render.context import build_context
|
|
18
|
+
|
|
19
|
+
TEMPLATE: Final = "report.md.j2"
|
|
20
|
+
ASSETS_DIR: Final = "assets"
|
|
21
|
+
_FENCE_LINE: Final = re.compile(r"^ {0,3}(`{3,}|~{3,})")
|
|
22
|
+
_ATX_HEADING: Final = re.compile(r"^ {0,3}#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$")
|
|
23
|
+
_SETEXT_UNDERLINE: Final = re.compile(r"^ {0,3}(?:=+|-+)[ \t]*$")
|
|
24
|
+
_INLINE_SPECIAL: Final = re.compile(r"([\\`*_\[\]<>|#])")
|
|
25
|
+
_DANGEROUS_SCHEME: Final = r"(?:javascript|vbscript|data|file):"
|
|
26
|
+
_INLINE_LINK: Final = re.compile(rf"\]\((\s*<?\s*)(?={_DANGEROUS_SCHEME})", re.IGNORECASE)
|
|
27
|
+
_LINK_DEFINITION: Final = re.compile(rf"^( {{0,3}})(\[[^\]]+\]:\s*<?\s*{_DANGEROUS_SCHEME})", re.I)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _neutralise(segment: str) -> str:
|
|
31
|
+
"""Outside code: escape raw HTML and break links to dangerous schemes (shown as text)."""
|
|
32
|
+
return _INLINE_LINK.sub(r"\\](\1", segment.replace("<", "<"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class MarkdownReport:
|
|
37
|
+
"""The Markdown text and the images to copy: ``(source file, path relative to output)``."""
|
|
38
|
+
|
|
39
|
+
text: str
|
|
40
|
+
assets: list[tuple[Path, str]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def slug(heading: str) -> str:
|
|
44
|
+
"""GitHub's heading anchor: lower case, punctuation removed, spaces become hyphens."""
|
|
45
|
+
return re.sub(r"[^\w\- ]", "", heading.strip().lower()).replace(" ", "-")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fence(content: str) -> str:
|
|
49
|
+
"""A backtick fence longer than any backtick run in ``content`` (at least three)."""
|
|
50
|
+
longest = max((len(run) for run in re.findall(r"`+", content)), default=0)
|
|
51
|
+
return "`" * max(3, longest + 1)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _escape_inline_code_aware(line: str) -> str:
|
|
55
|
+
"""Escape ``<`` outside code spans (a code span ends at a backtick run of equal length)."""
|
|
56
|
+
out: list[str] = []
|
|
57
|
+
position = 0
|
|
58
|
+
while position < len(line):
|
|
59
|
+
tick = re.compile(r"`+").search(line, position)
|
|
60
|
+
if tick is None:
|
|
61
|
+
out.append(_neutralise(line[position:]))
|
|
62
|
+
break
|
|
63
|
+
out.append(_neutralise(line[position : tick.start()]))
|
|
64
|
+
closing = re.compile(rf"(?<!`){tick.group()}(?!`)").search(line, tick.end())
|
|
65
|
+
if closing is None:
|
|
66
|
+
out.append(tick.group())
|
|
67
|
+
position = tick.end()
|
|
68
|
+
continue
|
|
69
|
+
out.append(line[tick.start() : closing.end()])
|
|
70
|
+
position = closing.end()
|
|
71
|
+
return "".join(out)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def escape_html_outside_code(text: str) -> str:
|
|
75
|
+
"""Escape raw HTML and neutralise javascript:/data:/vbscript:/file: links in user Markdown
|
|
76
|
+
(FR-13), keeping code spans and fenced blocks verbatim."""
|
|
77
|
+
out: list[str] = []
|
|
78
|
+
open_fence: str | None = None
|
|
79
|
+
for line in text.split("\n"):
|
|
80
|
+
match = _FENCE_LINE.match(line)
|
|
81
|
+
if open_fence is not None:
|
|
82
|
+
out.append(line)
|
|
83
|
+
if (
|
|
84
|
+
match
|
|
85
|
+
and match.group(1)[0] == open_fence[0]
|
|
86
|
+
and len(match.group(1)) >= len(open_fence)
|
|
87
|
+
):
|
|
88
|
+
open_fence = None
|
|
89
|
+
elif match:
|
|
90
|
+
open_fence = match.group(1)
|
|
91
|
+
out.append(line)
|
|
92
|
+
else:
|
|
93
|
+
out.append(_escape_inline_code_aware(_LINK_DEFINITION.sub(r"\1\\\2", line)))
|
|
94
|
+
return "\n".join(out)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _demote_headings(text: str) -> str:
|
|
98
|
+
"""Turn headings in user Markdown into bold lines, so the report keeps one ``#`` title."""
|
|
99
|
+
lines = text.split("\n")
|
|
100
|
+
out: list[str] = []
|
|
101
|
+
open_fence: str | None = None
|
|
102
|
+
for line in lines:
|
|
103
|
+
match = _FENCE_LINE.match(line)
|
|
104
|
+
if open_fence is not None or match:
|
|
105
|
+
if open_fence is None and match:
|
|
106
|
+
open_fence = match.group(1)
|
|
107
|
+
elif match and match.group(1)[0] == (open_fence or " ")[0]:
|
|
108
|
+
open_fence = None
|
|
109
|
+
out.append(line)
|
|
110
|
+
continue
|
|
111
|
+
heading = _ATX_HEADING.match(line)
|
|
112
|
+
if heading:
|
|
113
|
+
out.append(f"**{(heading.group(1) or '').strip()}**")
|
|
114
|
+
elif _SETEXT_UNDERLINE.match(line) and out and out[-1].strip() and "=" in line:
|
|
115
|
+
out[-1] = f"**{out[-1].strip()}**"
|
|
116
|
+
else:
|
|
117
|
+
out.append(line)
|
|
118
|
+
return "\n".join(out)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def md_block(text: str) -> str:
|
|
122
|
+
"""Filter: user Markdown, with raw HTML escaped and headings demoted."""
|
|
123
|
+
return escape_html_outside_code(_demote_headings(text.strip()))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def md_inline(text: str) -> str:
|
|
127
|
+
"""Filter: plain text shown literally in Markdown (titles, names, captions)."""
|
|
128
|
+
return _INLINE_SPECIAL.sub(r"\\\1", " ".join(str(text).split()))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def md_cell(text: str) -> str:
|
|
132
|
+
"""Filter: plain text inside a GFM table cell."""
|
|
133
|
+
return md_inline(text)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def md_url(url: str) -> str:
|
|
137
|
+
"""Filter: a URL for an autolink, with characters that could end it percent-encoded."""
|
|
138
|
+
for char, code in (("<", "%3C"), (">", "%3E"), (" ", "%20"), ("`", "%60")):
|
|
139
|
+
url = url.replace(char, code)
|
|
140
|
+
return url
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def md_step(text: str) -> str:
|
|
144
|
+
"""Filter: a list item of user Markdown on one line."""
|
|
145
|
+
return escape_html_outside_code(" ".join(text.split()))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def render_md(
|
|
149
|
+
report: Report, summary: RedactionSummary, base_dir: Path, template_dir: Path | None = None
|
|
150
|
+
) -> MarkdownReport:
|
|
151
|
+
"""Render the (already redacted) report as GitHub-Flavored Markdown."""
|
|
152
|
+
env = make_environment(template_dir)
|
|
153
|
+
env.filters.update(
|
|
154
|
+
md_block=md_block,
|
|
155
|
+
md_inline=md_inline,
|
|
156
|
+
md_cell=md_cell,
|
|
157
|
+
md_step=md_step,
|
|
158
|
+
md_url=md_url,
|
|
159
|
+
slug=slug,
|
|
160
|
+
fence=fence,
|
|
161
|
+
)
|
|
162
|
+
context = build_context(report, summary, base_dir)
|
|
163
|
+
assets: list[tuple[Path, str]] = []
|
|
164
|
+
|
|
165
|
+
def image_src(path: Path, mime: str, asset_name: str) -> str:
|
|
166
|
+
relative = f"{ASSETS_DIR}/{asset_name}"
|
|
167
|
+
if (path, relative) not in assets:
|
|
168
|
+
assets.append((path, relative))
|
|
169
|
+
return relative
|
|
170
|
+
|
|
171
|
+
text = env.get_template(TEMPLATE).render(**context, image_src=image_src)
|
|
172
|
+
return MarkdownReport(text, assets)
|