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
pentrep/diagnostics.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Exit codes, diagnostic codes and diagnostic formatting shared by all pentrep commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum, IntEnum, StrEnum
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ExitCode(IntEnum):
|
|
13
|
+
"""Process exit codes (PRD FR-00c)."""
|
|
14
|
+
|
|
15
|
+
OK = 0
|
|
16
|
+
VALIDATION_FAILED = 1
|
|
17
|
+
USAGE_ERROR = 2
|
|
18
|
+
RENDER_ERROR = 3
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Level(StrEnum):
|
|
22
|
+
"""Severity of a diagnostic."""
|
|
23
|
+
|
|
24
|
+
ERROR = "error"
|
|
25
|
+
WARNING = "warning"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ErrorCode(Enum):
|
|
29
|
+
"""Stable diagnostic codes (PRD §4.2.4). The value is the code, ``summary`` its meaning."""
|
|
30
|
+
|
|
31
|
+
E100 = ("E100", "YAML syntax error")
|
|
32
|
+
E101 = ("E101", "Unknown field")
|
|
33
|
+
E102 = ("E102", "Missing required field")
|
|
34
|
+
E103 = ("E103", "Wrong type, length or pattern; or a field not allowed for this evidence type")
|
|
35
|
+
E104 = ("E104", "Duplicate finding id")
|
|
36
|
+
E105 = ("E105", "end_date is before start_date")
|
|
37
|
+
E106 = ("E106", "Unsupported schema_version")
|
|
38
|
+
E201 = ("E201", "CVSS vector missing the CVSS:3.1/ prefix, or an unsupported version")
|
|
39
|
+
E202 = ("E202", "Unknown CVSS metric")
|
|
40
|
+
E203 = ("E203", "Invalid value for a CVSS metric")
|
|
41
|
+
E204 = ("E204", "Missing CVSS base metric(s)")
|
|
42
|
+
E205 = ("E205", "Duplicate CVSS metric")
|
|
43
|
+
E206 = ("E206", "Both cvss_vector and severity given, or neither")
|
|
44
|
+
E301 = ("E301", "Referenced file not found")
|
|
45
|
+
E302 = ("E302", "Path resolves outside the project directory")
|
|
46
|
+
E303 = ("E303", "Unsupported file type, or file too large")
|
|
47
|
+
E304 = ("E304", "Invalid custom redaction regex, or invalid pattern name")
|
|
48
|
+
W101 = ("W101", "Placeholder text found")
|
|
49
|
+
W102 = ("W102", "Finding has no evidence")
|
|
50
|
+
W201 = ("W201", "Temporal/environmental CVSS metrics present; ignored in v0.1")
|
|
51
|
+
|
|
52
|
+
def __new__(cls, code: str, summary: str) -> ErrorCode:
|
|
53
|
+
"""Use the code string as the enum value and keep the summary alongside it."""
|
|
54
|
+
obj = object.__new__(cls)
|
|
55
|
+
obj._value_ = code
|
|
56
|
+
obj.summary = summary
|
|
57
|
+
return obj
|
|
58
|
+
|
|
59
|
+
summary: str
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def level(self) -> Level:
|
|
63
|
+
"""``warning`` for W-codes, ``error`` otherwise."""
|
|
64
|
+
return Level.WARNING if self.value.startswith("W") else Level.ERROR
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, order=False)
|
|
68
|
+
class Diagnostic:
|
|
69
|
+
"""One error or warning, located in a file (FR-12)."""
|
|
70
|
+
|
|
71
|
+
code: ErrorCode
|
|
72
|
+
message: str
|
|
73
|
+
file: str
|
|
74
|
+
line: int
|
|
75
|
+
column: int
|
|
76
|
+
path: str = ""
|
|
77
|
+
hint: str | None = None
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def level(self) -> Level:
|
|
81
|
+
"""The diagnostic's severity, derived from its code."""
|
|
82
|
+
return self.code.level
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
MAX_DIAGNOSTICS: Final = 100
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def sort_and_cap(
|
|
89
|
+
diagnostics: Iterable[Diagnostic], limit: int = MAX_DIAGNOSTICS
|
|
90
|
+
) -> list[Diagnostic]:
|
|
91
|
+
"""Drop exact duplicates, sort by position (then code and path) and keep at most ``limit``."""
|
|
92
|
+
unique = set(diagnostics)
|
|
93
|
+
ordered = sorted(unique, key=lambda d: (d.line, d.column, d.code.value, d.path, d.message))
|
|
94
|
+
return ordered[:limit]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def format_text(diagnostic: Diagnostic) -> str:
|
|
98
|
+
"""Format one diagnostic in the PRD §4.2.4 text format (hint on a second line)."""
|
|
99
|
+
d = diagnostic
|
|
100
|
+
where = f"{d.path}: " if d.path else ""
|
|
101
|
+
text = f"{d.file}:{d.line}:{d.column}: {d.level}[{d.code.value}] {where}{d.message}"
|
|
102
|
+
if d.hint:
|
|
103
|
+
text += f"\n hint: {d.hint}"
|
|
104
|
+
return text
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def format_json(diagnostics: Iterable[Diagnostic]) -> str:
|
|
108
|
+
"""Format diagnostics as a JSON array (FR-02 ``--format json``)."""
|
|
109
|
+
items = [
|
|
110
|
+
{
|
|
111
|
+
"code": d.code.value,
|
|
112
|
+
"severity": d.level.value,
|
|
113
|
+
"path": d.path,
|
|
114
|
+
"line": d.line,
|
|
115
|
+
"column": d.column,
|
|
116
|
+
"message": d.message,
|
|
117
|
+
"hint": d.hint,
|
|
118
|
+
}
|
|
119
|
+
for d in diagnostics
|
|
120
|
+
]
|
|
121
|
+
return json.dumps(items, indent=2, ensure_ascii=False)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
DIAGNOSTICS_JSON_SCHEMA: Final[dict[str, object]] = {
|
|
125
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
126
|
+
"title": "pentrep validate --format json output",
|
|
127
|
+
"type": "array",
|
|
128
|
+
"items": {
|
|
129
|
+
"type": "object",
|
|
130
|
+
"additionalProperties": False,
|
|
131
|
+
"required": ["code", "severity", "path", "line", "column", "message", "hint"],
|
|
132
|
+
"properties": {
|
|
133
|
+
"code": {"type": "string", "pattern": "^[EW][0-9]{3}$"},
|
|
134
|
+
"severity": {"enum": ["error", "warning"]},
|
|
135
|
+
"path": {"type": "string"},
|
|
136
|
+
"line": {"type": "integer", "minimum": 1},
|
|
137
|
+
"column": {"type": "integer", "minimum": 1},
|
|
138
|
+
"message": {"type": "string", "minLength": 1},
|
|
139
|
+
"hint": {"type": ["string", "null"]},
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
}
|
pentrep/loader.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""Load ``findings.yaml`` safely and keep the line/column of every node (FR-10, FR-12)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import difflib
|
|
6
|
+
import io
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from dataclasses import dataclass, field, replace
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from types import UnionType
|
|
12
|
+
from typing import Annotated, Final, Union, get_args, get_origin
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ValidationError
|
|
15
|
+
from pydantic_core import ErrorDetails
|
|
16
|
+
from ruamel.yaml import YAML
|
|
17
|
+
from ruamel.yaml.error import MarkedYAMLError, YAMLError
|
|
18
|
+
from ruamel.yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode
|
|
19
|
+
|
|
20
|
+
from pentrep.cvss import parse_vector
|
|
21
|
+
from pentrep.diagnostics import Diagnostic, ErrorCode, Level, sort_and_cap
|
|
22
|
+
from pentrep.models import EVIDENCE_TYPES, Issue, Report, cross_checks
|
|
23
|
+
|
|
24
|
+
MAX_FILE_BYTES: Final = 10 * 1024 * 1024
|
|
25
|
+
MAX_ALIAS_EXPANSION: Final = 1_000
|
|
26
|
+
MAX_DEPTH: Final = 100
|
|
27
|
+
|
|
28
|
+
_TAG_PREFIX: Final = "tag:yaml.org,2002:"
|
|
29
|
+
_SCALAR_TAGS: Final = frozenset(
|
|
30
|
+
_TAG_PREFIX + name for name in ("str", "int", "float", "bool", "null", "timestamp")
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# A plain YAML value: what json-like data from findings.yaml is made of.
|
|
34
|
+
Position = tuple[int, int]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LoadError(Exception):
|
|
38
|
+
"""The YAML file could not be loaded; carries one diagnostic."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, diagnostic: Diagnostic) -> None:
|
|
41
|
+
super().__init__(diagnostic.message)
|
|
42
|
+
self.diagnostic = diagnostic
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def join_path(parent: str, part: str | int) -> str:
|
|
46
|
+
"""Append a key or list index to a dotted path (``findings[0].id``)."""
|
|
47
|
+
if isinstance(part, int):
|
|
48
|
+
return f"{parent}[{part}]"
|
|
49
|
+
return f"{parent}.{part}" if parent else part
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parent_path(path: str) -> str:
|
|
53
|
+
"""Return the dotted path one level up (``findings[0].id`` → ``findings[0]``)."""
|
|
54
|
+
cut = max(path.rfind("."), path.rfind("["))
|
|
55
|
+
return path[:cut] if cut > 0 else ""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class LoadedYaml:
|
|
60
|
+
"""Plain data loaded from YAML plus the position of every value and mapping key."""
|
|
61
|
+
|
|
62
|
+
data: object
|
|
63
|
+
file: str
|
|
64
|
+
values: dict[str, Position] = field(default_factory=dict)
|
|
65
|
+
keys: dict[str, Position] = field(default_factory=dict)
|
|
66
|
+
|
|
67
|
+
def position(self, path: str) -> Position:
|
|
68
|
+
"""Line/column of the value at ``path``, or of its nearest existing ancestor."""
|
|
69
|
+
while path not in self.values and path:
|
|
70
|
+
path = parent_path(path)
|
|
71
|
+
return self.values.get(path, (1, 1))
|
|
72
|
+
|
|
73
|
+
def key_position(self, path: str) -> Position:
|
|
74
|
+
"""Line/column of the mapping key for ``path``; falls back like :meth:`position`."""
|
|
75
|
+
return self.keys.get(path) or self.position(parent_path(path))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _diag(
|
|
79
|
+
file: str,
|
|
80
|
+
message: str,
|
|
81
|
+
pos: Position = (1, 1),
|
|
82
|
+
path: str = "",
|
|
83
|
+
code: ErrorCode = ErrorCode.E100,
|
|
84
|
+
) -> Diagnostic:
|
|
85
|
+
return Diagnostic(code, message, file=file, line=pos[0], column=pos[1], path=path)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _pos(node: Node) -> Position:
|
|
89
|
+
return (node.start_mark.line + 1, node.start_mark.column + 1)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _Builder:
|
|
93
|
+
"""Turn a composed node graph into plain Python data, recording positions.
|
|
94
|
+
|
|
95
|
+
Only standard JSON-like tags are accepted, and alias expansion is bounded, so the
|
|
96
|
+
result never contains arbitrary objects and a "billion laughs" file is rejected.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self, yaml: YAML, doc: LoadedYaml) -> None:
|
|
100
|
+
self._constructor = yaml.constructor
|
|
101
|
+
self._doc = doc
|
|
102
|
+
self._seen: set[int] = set()
|
|
103
|
+
self._expanded = 0
|
|
104
|
+
|
|
105
|
+
def build(self, node: Node, path: str, depth: int = 0) -> object:
|
|
106
|
+
if id(node) in self._seen:
|
|
107
|
+
self._expanded += 1
|
|
108
|
+
if self._expanded > MAX_ALIAS_EXPANSION:
|
|
109
|
+
raise self._error(
|
|
110
|
+
node, path, f"alias expansion exceeds {MAX_ALIAS_EXPANSION} nodes"
|
|
111
|
+
)
|
|
112
|
+
self._seen.add(id(node))
|
|
113
|
+
if depth > MAX_DEPTH:
|
|
114
|
+
raise self._error(node, path, f"nesting deeper than {MAX_DEPTH} levels")
|
|
115
|
+
self._doc.values.setdefault(path, _pos(node))
|
|
116
|
+
if isinstance(node, MappingNode):
|
|
117
|
+
return self._mapping(node, path, depth)
|
|
118
|
+
if isinstance(node, SequenceNode):
|
|
119
|
+
return self._sequence(node, path, depth)
|
|
120
|
+
return self._scalar(node, path)
|
|
121
|
+
|
|
122
|
+
def _mapping(self, node: MappingNode, path: str, depth: int) -> dict[object, object]:
|
|
123
|
+
if node.tag != _TAG_PREFIX + "map":
|
|
124
|
+
raise self._unsupported_tag(node, path)
|
|
125
|
+
result: dict[object, object] = {}
|
|
126
|
+
for key_node, value_node in node.value:
|
|
127
|
+
if key_node.tag == _TAG_PREFIX + "merge":
|
|
128
|
+
raise self._error(key_node, path, "merge keys ('<<') are not supported")
|
|
129
|
+
if not isinstance(key_node, ScalarNode):
|
|
130
|
+
raise self._error(key_node, path, "mapping keys must be plain scalars")
|
|
131
|
+
key = self._scalar(key_node, path)
|
|
132
|
+
if not isinstance(key, str | int | float | bool):
|
|
133
|
+
raise self._error(key_node, path, "mapping keys must be strings")
|
|
134
|
+
if key in result:
|
|
135
|
+
raise self._error(key_node, path, f"duplicate key '{key}'")
|
|
136
|
+
child = join_path(path, str(key))
|
|
137
|
+
self._doc.keys.setdefault(child, _pos(key_node))
|
|
138
|
+
result[key] = self.build(value_node, child, depth + 1)
|
|
139
|
+
return result
|
|
140
|
+
|
|
141
|
+
def _sequence(self, node: SequenceNode, path: str, depth: int) -> list[object]:
|
|
142
|
+
if node.tag != _TAG_PREFIX + "seq":
|
|
143
|
+
raise self._unsupported_tag(node, path)
|
|
144
|
+
return [
|
|
145
|
+
self.build(item, join_path(path, i), depth + 1) for i, item in enumerate(node.value)
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
def _scalar(self, node: Node, path: str) -> object:
|
|
149
|
+
if node.tag not in _SCALAR_TAGS:
|
|
150
|
+
raise self._unsupported_tag(node, path)
|
|
151
|
+
return self._constructor.construct_object(node, deep=True)
|
|
152
|
+
|
|
153
|
+
def _unsupported_tag(self, node: Node, path: str) -> LoadError:
|
|
154
|
+
tag = str(node.tag).replace(_TAG_PREFIX, "!!")
|
|
155
|
+
return self._error(node, path, f"unsupported YAML tag '{tag}'")
|
|
156
|
+
|
|
157
|
+
def _error(self, node: Node, path: str, message: str) -> LoadError:
|
|
158
|
+
return LoadError(_diag(self._doc.file, message, _pos(node), path))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def parse_yaml(text: str, file: str) -> LoadedYaml:
|
|
162
|
+
"""Parse YAML 1.2 ``text`` into plain data with positions; raise :class:`LoadError`."""
|
|
163
|
+
yaml = YAML(typ="safe", pure=True)
|
|
164
|
+
yaml.version = (1, 2)
|
|
165
|
+
doc = LoadedYaml(data=None, file=file)
|
|
166
|
+
try:
|
|
167
|
+
node = yaml.compose(io.StringIO(text))
|
|
168
|
+
except MarkedYAMLError as exc:
|
|
169
|
+
mark = exc.problem_mark or exc.context_mark
|
|
170
|
+
pos = (mark.line + 1, mark.column + 1) if mark else (1, 1)
|
|
171
|
+
message = exc.problem or exc.context or "invalid YAML"
|
|
172
|
+
if "expected a single document" in str(exc):
|
|
173
|
+
message = "only one YAML document is allowed per file"
|
|
174
|
+
diag = _diag(file, message, pos)
|
|
175
|
+
hint = "check the indentation, quoting and brackets on this line and the one above"
|
|
176
|
+
raise LoadError(replace(diag, hint=hint)) from None
|
|
177
|
+
except YAMLError as exc:
|
|
178
|
+
raise LoadError(_diag(file, f"invalid YAML: {exc}")) from None
|
|
179
|
+
except RecursionError:
|
|
180
|
+
raise LoadError(_diag(file, f"nesting deeper than {MAX_DEPTH} levels")) from None
|
|
181
|
+
if node is not None:
|
|
182
|
+
doc.data = _Builder(yaml, doc).build(node, "")
|
|
183
|
+
return doc
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def load_yaml(path: Path, display: str | None = None) -> LoadedYaml:
|
|
187
|
+
"""Read ``path`` (≤ 10 MB, UTF-8) and parse it; ``display`` is the name used in diagnostics."""
|
|
188
|
+
file = display if display is not None else str(path)
|
|
189
|
+
if path.stat().st_size > MAX_FILE_BYTES:
|
|
190
|
+
raise LoadError(_diag(file, "file is larger than 10 MB", code=ErrorCode.E303))
|
|
191
|
+
raw = path.read_bytes()
|
|
192
|
+
try:
|
|
193
|
+
text = raw.decode("utf-8-sig")
|
|
194
|
+
except UnicodeDecodeError as exc:
|
|
195
|
+
line = raw[: exc.start].count(b"\n") + 1
|
|
196
|
+
column = exc.start - (raw.rfind(b"\n", 0, exc.start) + 1) + 1
|
|
197
|
+
raise LoadError(_diag(file, "file is not valid UTF-8", (line, column))) from None
|
|
198
|
+
return parse_yaml(text, file)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# --- Referenced files (FR-14, E301-E303) ---------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
LOGO_MAX_BYTES: Final = 2 * 1024 * 1024
|
|
204
|
+
IMAGE_MAX_BYTES: Final = 5 * 1024 * 1024
|
|
205
|
+
SNIFF_BYTES: Final = 1024
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def sniff_image_type(head: bytes) -> str | None:
|
|
209
|
+
"""Detect an image type from its first bytes (the extension is not trusted)."""
|
|
210
|
+
if head.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
211
|
+
return "PNG"
|
|
212
|
+
if head.startswith(b"\xff\xd8\xff"):
|
|
213
|
+
return "JPEG"
|
|
214
|
+
if head.startswith((b"GIF87a", b"GIF89a")):
|
|
215
|
+
return "GIF"
|
|
216
|
+
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
|
|
217
|
+
return "WebP"
|
|
218
|
+
text = head.decode("utf-8", errors="ignore").lstrip("\ufeff \t\r\n").lower()
|
|
219
|
+
if text.startswith("<") and "<svg" in text:
|
|
220
|
+
return "SVG"
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass(frozen=True)
|
|
225
|
+
class _FileRule:
|
|
226
|
+
kinds: tuple[str, ...]
|
|
227
|
+
max_bytes: int
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def kinds_text(self) -> str:
|
|
231
|
+
return ", ".join(self.kinds[:-1]) + f" or {self.kinds[-1]}"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
_LOGO_RULE: Final = _FileRule(("PNG", "JPEG", "SVG"), LOGO_MAX_BYTES)
|
|
235
|
+
_IMAGE_RULE: Final = _FileRule(("PNG", "JPEG", "GIF", "WebP"), IMAGE_MAX_BYTES)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _referenced_files(data: object) -> list[tuple[str, str, _FileRule]]:
|
|
239
|
+
"""``(dotted path, file path, rule)`` for the logo and every image evidence item."""
|
|
240
|
+
if not isinstance(data, dict):
|
|
241
|
+
return []
|
|
242
|
+
refs: list[tuple[str, str, _FileRule]] = []
|
|
243
|
+
branding = data.get("branding")
|
|
244
|
+
if isinstance(branding, dict) and isinstance(branding.get("logo"), str) and branding["logo"]:
|
|
245
|
+
refs.append(("branding.logo", branding["logo"], _LOGO_RULE))
|
|
246
|
+
findings = data.get("findings")
|
|
247
|
+
for i, finding in enumerate(findings if isinstance(findings, list) else []):
|
|
248
|
+
evidence = finding.get("evidence") if isinstance(finding, dict) else None
|
|
249
|
+
for j, item in enumerate(evidence if isinstance(evidence, list) else []):
|
|
250
|
+
if isinstance(item, dict) and item.get("type") == "image":
|
|
251
|
+
ref = item.get("path")
|
|
252
|
+
if isinstance(ref, str) and ref:
|
|
253
|
+
refs.append((f"findings[{i}].evidence[{j}].path", ref, _IMAGE_RULE))
|
|
254
|
+
return refs
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _check_file(base_dir: Path, ref: str, rule: _FileRule) -> tuple[ErrorCode, str] | None:
|
|
258
|
+
"""Return ``(code, message)`` if the referenced file is unusable, else ``None``."""
|
|
259
|
+
target = (base_dir / ref).resolve() # resolves ".." and symlinks
|
|
260
|
+
if not target.is_relative_to(base_dir):
|
|
261
|
+
return ErrorCode.E302, f"path '{ref}' resolves outside the project directory"
|
|
262
|
+
if not target.is_file():
|
|
263
|
+
return ErrorCode.E301, f"file '{ref}' not found"
|
|
264
|
+
size = target.stat().st_size
|
|
265
|
+
if size > rule.max_bytes:
|
|
266
|
+
limit = rule.max_bytes // (1024 * 1024)
|
|
267
|
+
return ErrorCode.E303, f"file '{ref}' is larger than {limit} MB"
|
|
268
|
+
with target.open("rb") as handle:
|
|
269
|
+
kind = sniff_image_type(handle.read(SNIFF_BYTES))
|
|
270
|
+
if kind not in rule.kinds:
|
|
271
|
+
found = kind or "unknown"
|
|
272
|
+
return ErrorCode.E303, (
|
|
273
|
+
f"unsupported file type for '{ref}' (found {found}; expected {rule.kinds_text})"
|
|
274
|
+
)
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def check_files(doc: LoadedYaml, base_dir: Path) -> list[Diagnostic]:
|
|
279
|
+
"""Check the logo and image evidence: confinement (E302), existence (E301), type/size (E303)."""
|
|
280
|
+
root = base_dir.resolve()
|
|
281
|
+
diagnostics: list[Diagnostic] = []
|
|
282
|
+
for path, ref, rule in _referenced_files(doc.data):
|
|
283
|
+
problem = _check_file(root, ref, rule)
|
|
284
|
+
if problem:
|
|
285
|
+
line, column = doc.position(path)
|
|
286
|
+
diagnostics.append(Diagnostic(problem[0], problem[1], doc.file, line, column, path))
|
|
287
|
+
return diagnostics
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# --- CVSS vectors (E201-E205, W201) --------------------------------------------------------------
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def check_cvss(doc: LoadedYaml) -> list[Diagnostic]:
|
|
294
|
+
"""Report every issue in each finding's ``cvss_vector``, at the vector's position."""
|
|
295
|
+
diagnostics: list[Diagnostic] = []
|
|
296
|
+
findings = doc.data.get("findings") if isinstance(doc.data, dict) else None
|
|
297
|
+
for index, finding in enumerate(findings if isinstance(findings, list) else []):
|
|
298
|
+
vector = finding.get("cvss_vector") if isinstance(finding, dict) else None
|
|
299
|
+
if not isinstance(vector, str) or not vector:
|
|
300
|
+
continue # wrong type or empty: the model reports E103
|
|
301
|
+
path = f"findings[{index}].cvss_vector"
|
|
302
|
+
line, column = doc.position(path)
|
|
303
|
+
diagnostics.extend(
|
|
304
|
+
Diagnostic(issue.code, issue.message, doc.file, line, column, path, issue.hint)
|
|
305
|
+
for issue in parse_vector(vector).issues
|
|
306
|
+
)
|
|
307
|
+
return diagnostics
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# --- Warnings (W101, W102) ------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
PLACEHOLDER_RE: Final = re.compile(r"\b(?:TODO|TBD|FIXME)\b|\blorem\s+ipsum\b", re.IGNORECASE)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _strings(value: object, path: str) -> Iterator[tuple[str, str]]:
|
|
316
|
+
"""Yield ``(dotted path, text)`` for every string value (not key) in the data."""
|
|
317
|
+
if isinstance(value, str):
|
|
318
|
+
yield path, value
|
|
319
|
+
elif isinstance(value, dict):
|
|
320
|
+
for key, child in value.items():
|
|
321
|
+
yield from _strings(child, join_path(path, str(key)))
|
|
322
|
+
elif isinstance(value, list):
|
|
323
|
+
for index, child in enumerate(value):
|
|
324
|
+
yield from _strings(child, join_path(path, index))
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def check_warnings(doc: LoadedYaml) -> list[Diagnostic]:
|
|
328
|
+
"""Placeholder text (W101) and findings without evidence (W102)."""
|
|
329
|
+
diagnostics: list[Diagnostic] = []
|
|
330
|
+
for path, text in _strings(doc.data, ""):
|
|
331
|
+
match = PLACEHOLDER_RE.search(text)
|
|
332
|
+
if match:
|
|
333
|
+
line, column = doc.position(path)
|
|
334
|
+
diagnostics.append(
|
|
335
|
+
Diagnostic(
|
|
336
|
+
ErrorCode.W101,
|
|
337
|
+
f"placeholder text '{match.group(0)}' found",
|
|
338
|
+
doc.file,
|
|
339
|
+
line,
|
|
340
|
+
column,
|
|
341
|
+
path,
|
|
342
|
+
hint="replace it with real content before sending the report",
|
|
343
|
+
)
|
|
344
|
+
)
|
|
345
|
+
findings = doc.data.get("findings") if isinstance(doc.data, dict) else None
|
|
346
|
+
for index, finding in enumerate(findings if isinstance(findings, list) else []):
|
|
347
|
+
if not isinstance(finding, dict) or finding.get("evidence"):
|
|
348
|
+
continue
|
|
349
|
+
path = f"findings[{index}]"
|
|
350
|
+
if "evidence" in finding:
|
|
351
|
+
path = join_path(path, "evidence")
|
|
352
|
+
finding_id = finding.get("id")
|
|
353
|
+
name = f"finding {finding_id}" if isinstance(finding_id, str) else "finding"
|
|
354
|
+
line, column = doc.position(path)
|
|
355
|
+
diagnostics.append(
|
|
356
|
+
Diagnostic(ErrorCode.W102, f"{name} has no evidence", doc.file, line, column, path)
|
|
357
|
+
)
|
|
358
|
+
return diagnostics
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# --- Validation ---------------------------------------------------------------------------------
|
|
362
|
+
|
|
363
|
+
SUGGESTION_CUTOFF: Final = 0.6
|
|
364
|
+
EVIDENCE_TYPE_NAMES: Final = "text, http, image"
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@dataclass
|
|
368
|
+
class ValidationResult:
|
|
369
|
+
"""The outcome of validating a findings file: the report (if valid) and all diagnostics."""
|
|
370
|
+
|
|
371
|
+
report: Report | None
|
|
372
|
+
diagnostics: list[Diagnostic]
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def errors(self) -> list[Diagnostic]:
|
|
376
|
+
"""Error-level diagnostics."""
|
|
377
|
+
return [d for d in self.diagnostics if d.level is Level.ERROR]
|
|
378
|
+
|
|
379
|
+
@property
|
|
380
|
+
def warnings(self) -> list[Diagnostic]:
|
|
381
|
+
"""Warning-level diagnostics."""
|
|
382
|
+
return [d for d in self.diagnostics if d.level is Level.WARNING]
|
|
383
|
+
|
|
384
|
+
@property
|
|
385
|
+
def ok(self) -> bool:
|
|
386
|
+
"""True when there are no errors (warnings are allowed)."""
|
|
387
|
+
return not self.errors
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _models_in(annotation: object) -> list[type[BaseModel]]:
|
|
391
|
+
"""The model classes an annotation refers to, looking through Annotated/Optional/list/Union."""
|
|
392
|
+
origin = get_origin(annotation)
|
|
393
|
+
if origin is Annotated:
|
|
394
|
+
return _models_in(get_args(annotation)[0])
|
|
395
|
+
if origin in (list, Union, UnionType):
|
|
396
|
+
return [m for arg in get_args(annotation) for m in _models_in(arg)]
|
|
397
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
398
|
+
return [annotation]
|
|
399
|
+
return []
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _type_tag(model: type[BaseModel]) -> str | None:
|
|
403
|
+
"""The literal ``type`` value of a discriminated-union member, if it has one."""
|
|
404
|
+
field_info = model.model_fields.get("type")
|
|
405
|
+
if field_info is None:
|
|
406
|
+
return None
|
|
407
|
+
args = get_args(field_info.annotation)
|
|
408
|
+
return args[0] if len(args) == 1 and isinstance(args[0], str) else None
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _resolve(loc: tuple[str | int, ...]) -> tuple[tuple[str | int, ...], list[type[BaseModel]]]:
|
|
412
|
+
"""Walk a Pydantic ``loc`` from :class:`Report`.
|
|
413
|
+
|
|
414
|
+
Returns the location without discriminated-union tags (which don't exist in the YAML) and
|
|
415
|
+
the model classes that the location's parent mapping may be.
|
|
416
|
+
"""
|
|
417
|
+
clean: list[str | int] = []
|
|
418
|
+
models: list[type[BaseModel]] = [Report]
|
|
419
|
+
parents: list[type[BaseModel]] = []
|
|
420
|
+
for part in loc:
|
|
421
|
+
parents = models
|
|
422
|
+
if isinstance(part, int):
|
|
423
|
+
clean.append(part)
|
|
424
|
+
continue
|
|
425
|
+
tagged = [m for m in models if _type_tag(m) == part and part not in m.model_fields]
|
|
426
|
+
if tagged:
|
|
427
|
+
models = tagged
|
|
428
|
+
continue
|
|
429
|
+
clean.append(part)
|
|
430
|
+
fields = [m.model_fields[part] for m in models if part in m.model_fields]
|
|
431
|
+
models = [m for f in fields for m in _models_in(f.annotation)]
|
|
432
|
+
return tuple(clean), parents
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _path(loc: tuple[str | int, ...]) -> str:
|
|
436
|
+
path = ""
|
|
437
|
+
for part in loc:
|
|
438
|
+
path = join_path(path, part)
|
|
439
|
+
return path
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _sentence(msg: str) -> str:
|
|
443
|
+
return msg[:1].lower() + msg[1:]
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _from_pydantic(error: ErrorDetails, doc: LoadedYaml) -> Diagnostic:
|
|
447
|
+
"""Map one Pydantic error to a diagnostic with the YAML position (FR-11, FR-12)."""
|
|
448
|
+
kind = error["type"]
|
|
449
|
+
loc, parents = _resolve(tuple(error["loc"]))
|
|
450
|
+
path = _path(loc)
|
|
451
|
+
ctx = error.get("ctx", {})
|
|
452
|
+
hint: str | None = None
|
|
453
|
+
pos = doc.position(path)
|
|
454
|
+
|
|
455
|
+
if kind in ErrorCode.__members__:
|
|
456
|
+
code, message = ErrorCode[kind], error["msg"]
|
|
457
|
+
hint = ctx.get("hint")
|
|
458
|
+
elif kind == "extra_forbidden":
|
|
459
|
+
key = str(loc[-1])
|
|
460
|
+
allowed = sorted({name for m in parents for name in m.model_fields})
|
|
461
|
+
pos = doc.key_position(path)
|
|
462
|
+
other_types = [m for m in EVIDENCE_TYPES if key in m.model_fields and m not in parents]
|
|
463
|
+
if other_types and all(m in EVIDENCE_TYPES for m in parents):
|
|
464
|
+
code = ErrorCode.E103
|
|
465
|
+
evidence_type = _type_tag(parents[0])
|
|
466
|
+
message = f"field '{key}' is not allowed for evidence type '{evidence_type}'"
|
|
467
|
+
hint = "use 'content' for text/http evidence and 'path' for image evidence"
|
|
468
|
+
else:
|
|
469
|
+
code = ErrorCode.E101
|
|
470
|
+
message = f"unknown field '{key}'"
|
|
471
|
+
close = difflib.get_close_matches(key, allowed, n=1, cutoff=SUGGESTION_CUTOFF)
|
|
472
|
+
if close:
|
|
473
|
+
message += f"; did you mean '{close[0]}'?"
|
|
474
|
+
hint = "allowed fields: " + ", ".join(allowed)
|
|
475
|
+
elif kind == "missing":
|
|
476
|
+
code, message = ErrorCode.E102, f"missing required field '{loc[-1]}'"
|
|
477
|
+
elif kind == "union_tag_not_found":
|
|
478
|
+
path = join_path(path, "type")
|
|
479
|
+
code, message = ErrorCode.E102, "missing required field 'type'"
|
|
480
|
+
hint = f"evidence type must be one of: {EVIDENCE_TYPE_NAMES}"
|
|
481
|
+
elif kind == "union_tag_invalid":
|
|
482
|
+
path = join_path(path, "type")
|
|
483
|
+
pos = doc.position(path)
|
|
484
|
+
code, message = ErrorCode.E103, f"invalid evidence type {ctx.get('tag')!r}"
|
|
485
|
+
hint = f"evidence type must be one of: {EVIDENCE_TYPE_NAMES}"
|
|
486
|
+
elif not loc and kind == "model_type" and doc.data is None:
|
|
487
|
+
code, message = ErrorCode.E103, "file is empty; expected a findings.yaml document"
|
|
488
|
+
elif not loc and kind == "model_type":
|
|
489
|
+
code, message = ErrorCode.E103, "the top level of the file must be a mapping"
|
|
490
|
+
else:
|
|
491
|
+
code, message = ErrorCode.E103, _sentence(error["msg"])
|
|
492
|
+
if kind.endswith("_type") and isinstance(error["input"], str | int | float | bool):
|
|
493
|
+
message += f", got {error['input']!r}"
|
|
494
|
+
if kind == "literal_error":
|
|
495
|
+
hint = f"allowed values: {ctx.get('expected')}"
|
|
496
|
+
return Diagnostic(code, message, doc.file, pos[0], pos[1], path, hint)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _from_issue(issue: Issue, doc: LoadedYaml) -> Diagnostic:
|
|
500
|
+
path = _path(issue.loc)
|
|
501
|
+
line, column = doc.key_position(path) if issue.at_key else doc.position(path)
|
|
502
|
+
return Diagnostic(issue.code, issue.message, doc.file, line, column, path, issue.hint)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def validate_document(doc: LoadedYaml, base_dir: Path | None = None) -> ValidationResult:
|
|
506
|
+
"""Validate loaded YAML and collect every diagnostic (FR-02).
|
|
507
|
+
|
|
508
|
+
Referenced files are checked only when ``base_dir`` (the findings file's directory) is given.
|
|
509
|
+
"""
|
|
510
|
+
diagnostics = [_from_issue(issue, doc) for issue in cross_checks(doc.data)]
|
|
511
|
+
if base_dir is not None:
|
|
512
|
+
diagnostics.extend(check_files(doc, base_dir))
|
|
513
|
+
diagnostics.extend(check_cvss(doc))
|
|
514
|
+
diagnostics.extend(check_warnings(doc))
|
|
515
|
+
report: Report | None = None
|
|
516
|
+
try:
|
|
517
|
+
report = Report.model_validate(doc.data)
|
|
518
|
+
except ValidationError as exc:
|
|
519
|
+
diagnostics.extend(_from_pydantic(error, doc) for error in exc.errors())
|
|
520
|
+
result = ValidationResult(report, sort_and_cap(diagnostics))
|
|
521
|
+
if not result.ok:
|
|
522
|
+
result.report = None
|
|
523
|
+
return result
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def load_report(path: Path, display: str | None = None) -> ValidationResult:
|
|
527
|
+
"""Load and validate a findings file; loader failures become diagnostics."""
|
|
528
|
+
try:
|
|
529
|
+
doc = load_yaml(path, display)
|
|
530
|
+
except LoadError as exc:
|
|
531
|
+
return ValidationResult(None, [exc.diagnostic])
|
|
532
|
+
return validate_document(doc, base_dir=path.parent)
|