omids-validator 0.2.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.
- omids_validator/__init__.py +11 -0
- omids_validator/__main__.py +11 -0
- omids_validator/acquisition_profiles.py +478 -0
- omids_validator/cli.py +185 -0
- omids_validator/data/metadata_requirements.json +337 -0
- omids_validator/data/rules.json +364 -0
- omids_validator/file_types.py +46 -0
- omids_validator/inventory.py +133 -0
- omids_validator/models.py +60 -0
- omids_validator/participant_table.py +128 -0
- omids_validator/participants.py +235 -0
- omids_validator/patient_metadata.py +150 -0
- omids_validator/reporters/__init__.py +1 -0
- omids_validator/reporters/html_report.py +607 -0
- omids_validator/reporters/json_report.py +74 -0
- omids_validator/reporters/markdown_report.py +283 -0
- omids_validator/reporters/report_data.py +79 -0
- omids_validator/reporters/terminal.py +18 -0
- omids_validator/rule_catalog.py +279 -0
- omids_validator/rules/__init__.py +5 -0
- omids_validator/rules/layer0_structure.py +316 -0
- omids_validator/rules/layer1_naming.py +191 -0
- omids_validator/rules/layer2_sidecars.py +292 -0
- omids_validator/rules/layer3_metadata.py +144 -0
- omids_validator/rules/layer4_image_headers.py +152 -0
- omids_validator/rules/layer5_dataset.py +261 -0
- omids_validator/rules_document.py +192 -0
- omids_validator/validator.py +274 -0
- omids_validator-0.2.0.dist-info/METADATA +158 -0
- omids_validator-0.2.0.dist-info/RECORD +34 -0
- omids_validator-0.2.0.dist-info/WHEEL +5 -0
- omids_validator-0.2.0.dist-info/entry_points.txt +3 -0
- omids_validator-0.2.0.dist-info/licenses/LICENSE +677 -0
- omids_validator-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Turn a completed validation report into readable Markdown.
|
|
2
|
+
|
|
3
|
+
Small section functions assemble the summary, findings, inventory, and next
|
|
4
|
+
steps into one report.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from omids_validator.models import Finding, Severity, ValidationReport
|
|
11
|
+
from omids_validator.reporters.report_data import (
|
|
12
|
+
ACTIONABLE_SEVERITIES,
|
|
13
|
+
FINDING_EXAMPLE_THRESHOLD,
|
|
14
|
+
SEVERITY_DESCRIPTIONS,
|
|
15
|
+
SEVERITY_HEADINGS,
|
|
16
|
+
SEVERITY_ORDER,
|
|
17
|
+
group_findings,
|
|
18
|
+
inventory_value,
|
|
19
|
+
sort_rule_groups,
|
|
20
|
+
)
|
|
21
|
+
from omids_validator.rule_catalog import NextStep, load_rule_catalog
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _render_path(finding: Finding) -> str:
|
|
25
|
+
"""Render one finding path, or a dataset-level placeholder."""
|
|
26
|
+
|
|
27
|
+
return f"`{finding.path}`" if finding.path else "(dataset-level finding)"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def render_rule_group(
|
|
31
|
+
rule_id: str,
|
|
32
|
+
group: dict[str, Any],
|
|
33
|
+
*,
|
|
34
|
+
example_threshold: int = FINDING_EXAMPLE_THRESHOLD,
|
|
35
|
+
) -> str:
|
|
36
|
+
"""Render one rule group with all or representative paths."""
|
|
37
|
+
|
|
38
|
+
findings: list[Finding] = sorted(
|
|
39
|
+
group["findings"],
|
|
40
|
+
key=lambda finding: (finding.path or "", finding.message),
|
|
41
|
+
)
|
|
42
|
+
count = len(findings)
|
|
43
|
+
lines = [
|
|
44
|
+
f"### {rule_id} — {group['title']}",
|
|
45
|
+
"",
|
|
46
|
+
f"{count} finding(s).",
|
|
47
|
+
"",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
if count <= example_threshold:
|
|
51
|
+
lines.append("Affected paths:")
|
|
52
|
+
lines.extend(
|
|
53
|
+
f"- {_render_path(finding)}"
|
|
54
|
+
+ (f" — {finding.message}" if finding.message else "")
|
|
55
|
+
for finding in findings
|
|
56
|
+
)
|
|
57
|
+
else:
|
|
58
|
+
example = findings[0]
|
|
59
|
+
lines.extend(
|
|
60
|
+
[
|
|
61
|
+
"Representative finding:",
|
|
62
|
+
"",
|
|
63
|
+
f"Message: {example.message}",
|
|
64
|
+
"",
|
|
65
|
+
"Representative path:",
|
|
66
|
+
"```text",
|
|
67
|
+
example.path or "(dataset-level finding)",
|
|
68
|
+
"```",
|
|
69
|
+
"",
|
|
70
|
+
"See [report.json](report.json) for the complete list.",
|
|
71
|
+
]
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return "\n".join(lines)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def render_severity_section(
|
|
78
|
+
severity: Severity,
|
|
79
|
+
groups: list[tuple[str, dict[str, Any]]],
|
|
80
|
+
) -> str:
|
|
81
|
+
"""Render one severity heading and its ordered rule groups."""
|
|
82
|
+
|
|
83
|
+
sections = [
|
|
84
|
+
f"## {SEVERITY_HEADINGS[severity]}",
|
|
85
|
+
SEVERITY_DESCRIPTIONS[severity],
|
|
86
|
+
]
|
|
87
|
+
sections.extend(
|
|
88
|
+
render_rule_group(rule_id, group) for rule_id, group in groups
|
|
89
|
+
)
|
|
90
|
+
return "\n\n".join(sections)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def render_findings(report: ValidationReport) -> str:
|
|
94
|
+
"""Render findings by severity and numeric rule order."""
|
|
95
|
+
|
|
96
|
+
sorted_groups = sort_rule_groups(group_findings(report))
|
|
97
|
+
sections = [
|
|
98
|
+
render_severity_section(severity, sorted_groups[severity])
|
|
99
|
+
for severity in SEVERITY_ORDER
|
|
100
|
+
if sorted_groups[severity]
|
|
101
|
+
]
|
|
102
|
+
return "\n\n".join(sections)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _render_recommended_response(next_step: NextStep) -> str:
|
|
106
|
+
"""Render one catalogue response with an optional command or tool."""
|
|
107
|
+
|
|
108
|
+
lines = [f"**Recommended response:** {next_step.text}"]
|
|
109
|
+
if next_step.command is not None:
|
|
110
|
+
lines.extend(["", f"**Command:** `{next_step.command}`"])
|
|
111
|
+
if next_step.tool is not None:
|
|
112
|
+
lines.extend(["", f"**Tool:** `{next_step.tool}`"])
|
|
113
|
+
return "\n".join(lines)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def render_practical_next_steps(report: ValidationReport) -> str:
|
|
117
|
+
"""Render catalogue guidance for triggered errors and warnings."""
|
|
118
|
+
|
|
119
|
+
sorted_groups = sort_rule_groups(group_findings(report))
|
|
120
|
+
if not any(sorted_groups[severity] for severity in ACTIONABLE_SEVERITIES):
|
|
121
|
+
return ""
|
|
122
|
+
|
|
123
|
+
catalogue = load_rule_catalog()
|
|
124
|
+
sections = [
|
|
125
|
+
"## Practical next steps",
|
|
126
|
+
(
|
|
127
|
+
"The guidance below is generated from the rules triggered in "
|
|
128
|
+
"this validation. Review the affected paths and messages in the "
|
|
129
|
+
"findings sections above before making changes."
|
|
130
|
+
),
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
for severity in ACTIONABLE_SEVERITIES:
|
|
134
|
+
groups = sorted_groups[severity]
|
|
135
|
+
if not groups:
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
guidance = [f"### {SEVERITY_HEADINGS[severity]}"]
|
|
139
|
+
for rule_id, _group in groups:
|
|
140
|
+
rule = catalogue.get(rule_id)
|
|
141
|
+
guidance.append(
|
|
142
|
+
"\n\n".join(
|
|
143
|
+
(
|
|
144
|
+
f"#### {rule.rule_id} — {rule.title}",
|
|
145
|
+
_render_recommended_response(rule.next_step),
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
sections.append("\n\n".join(guidance))
|
|
150
|
+
|
|
151
|
+
return "\n\n".join(sections)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def render_dataset_summary(report: ValidationReport) -> str:
|
|
155
|
+
"""Render the first report section: inherited dataset facts."""
|
|
156
|
+
|
|
157
|
+
subject_count = inventory_value(report, "subject_count", "unknown")
|
|
158
|
+
imaging_session_count = inventory_value(
|
|
159
|
+
report, "imaging_session_count", "unknown"
|
|
160
|
+
)
|
|
161
|
+
image_count = inventory_value(report, "image_count", "unknown")
|
|
162
|
+
images_by_datatype = inventory_value(
|
|
163
|
+
report, "images_by_datatype", {}
|
|
164
|
+
)
|
|
165
|
+
session_counts = inventory_value(report, "session_counts", {})
|
|
166
|
+
|
|
167
|
+
lines = [
|
|
168
|
+
"## Dataset summary",
|
|
169
|
+
"",
|
|
170
|
+
"| Measure | Value |",
|
|
171
|
+
"| --- | ---: |",
|
|
172
|
+
f"| Subjects | {subject_count} |",
|
|
173
|
+
f"| Imaging sessions | {imaging_session_count} |",
|
|
174
|
+
f"| NIfTI images | {image_count} |",
|
|
175
|
+
"",
|
|
176
|
+
"### Sessions",
|
|
177
|
+
"",
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
if session_counts:
|
|
181
|
+
lines.extend(
|
|
182
|
+
[
|
|
183
|
+
"| Session name | Imaging sessions |",
|
|
184
|
+
"| --- | ---: |",
|
|
185
|
+
]
|
|
186
|
+
)
|
|
187
|
+
lines.extend(
|
|
188
|
+
f"| `{name}` | {count} |"
|
|
189
|
+
for name, count in session_counts.items()
|
|
190
|
+
)
|
|
191
|
+
else:
|
|
192
|
+
lines.append("No session directories were found.")
|
|
193
|
+
|
|
194
|
+
lines.extend(["", "### Images by datatype", ""])
|
|
195
|
+
if images_by_datatype:
|
|
196
|
+
lines.extend(["| Datatype | Images |", "| --- | ---: |"])
|
|
197
|
+
lines.extend(
|
|
198
|
+
f"| `{datatype}` | {count} |"
|
|
199
|
+
for datatype, count in images_by_datatype.items()
|
|
200
|
+
)
|
|
201
|
+
else:
|
|
202
|
+
lines.append("No recognized NIfTI images were found.")
|
|
203
|
+
|
|
204
|
+
return "\n".join(lines)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def render_imaging_inventory(report: ValidationReport) -> str:
|
|
208
|
+
"""Render normalized image coverage."""
|
|
209
|
+
|
|
210
|
+
coverage = inventory_value(report, "coverage", [])
|
|
211
|
+
imaging_session_count = inventory_value(
|
|
212
|
+
report, "imaging_session_count", "unknown"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
lines = [
|
|
216
|
+
"## Imaging coverage",
|
|
217
|
+
"",
|
|
218
|
+
"Each imaging session is counted once per coverage type.",
|
|
219
|
+
"",
|
|
220
|
+
"| Coverage type | Count |",
|
|
221
|
+
"| --- | ---: |",
|
|
222
|
+
]
|
|
223
|
+
if coverage:
|
|
224
|
+
lines.extend(
|
|
225
|
+
f"| `{item['type']}` | {item['count']} / {imaging_session_count} |"
|
|
226
|
+
for item in coverage
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
lines.append("| No recognized image types | 0 |")
|
|
230
|
+
|
|
231
|
+
return "\n".join(lines)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def render_imaging_unit_inventory(report: ValidationReport) -> str:
|
|
235
|
+
"""Render the deferred subject/session-level image inventory."""
|
|
236
|
+
|
|
237
|
+
units = inventory_value(report, "imaging_units", [])
|
|
238
|
+
|
|
239
|
+
lines = [
|
|
240
|
+
"## Imaging-unit inventory",
|
|
241
|
+
"",
|
|
242
|
+
"| Imaging unit | Session | Images | Coverage types |",
|
|
243
|
+
"| --- | --- | ---: | --- |",
|
|
244
|
+
]
|
|
245
|
+
lines.extend(
|
|
246
|
+
[
|
|
247
|
+
*(
|
|
248
|
+
f"| `{unit['path']}` | "
|
|
249
|
+
f"{unit['session'] or 'direct data'} | "
|
|
250
|
+
f"{unit['image_count']} | "
|
|
251
|
+
f"{', '.join(f'`{item}`' for item in unit['coverage_types']) or 'none'} |"
|
|
252
|
+
for unit in units
|
|
253
|
+
)
|
|
254
|
+
]
|
|
255
|
+
)
|
|
256
|
+
if not units:
|
|
257
|
+
lines.append("| No imaging units found | — | 0 | none |")
|
|
258
|
+
|
|
259
|
+
return "\n".join(lines)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def render(report: ValidationReport) -> str:
|
|
263
|
+
"""Render the currently implemented Markdown report sections."""
|
|
264
|
+
|
|
265
|
+
sections = [
|
|
266
|
+
"# OMIDS Validator Report",
|
|
267
|
+
render_dataset_summary(report),
|
|
268
|
+
render_imaging_inventory(report),
|
|
269
|
+
render_findings(report),
|
|
270
|
+
# Deferred until the unit-level inventory is more useful:
|
|
271
|
+
# render_imaging_unit_inventory(report),
|
|
272
|
+
]
|
|
273
|
+
practical_next_steps = render_practical_next_steps(report)
|
|
274
|
+
if practical_next_steps:
|
|
275
|
+
sections.append(practical_next_steps)
|
|
276
|
+
|
|
277
|
+
return "\n\n".join(sections) + "\n"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def write(report: ValidationReport, path: Path) -> None:
|
|
281
|
+
"""Write a Markdown report to ``path``."""
|
|
282
|
+
|
|
283
|
+
path.write_text(render(report), encoding="utf-8")
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Shared presentation data for human-readable validation reports."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from omids_validator.models import Severity, ValidationReport
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
FINDING_EXAMPLE_THRESHOLD = 10
|
|
9
|
+
SEVERITY_ORDER = (Severity.ERROR, Severity.WARNING, Severity.INFO)
|
|
10
|
+
SEVERITY_HEADINGS = {
|
|
11
|
+
Severity.ERROR: "Errors",
|
|
12
|
+
Severity.WARNING: "Warnings",
|
|
13
|
+
Severity.INFO: "Informational findings",
|
|
14
|
+
}
|
|
15
|
+
SEVERITY_DESCRIPTIONS = {
|
|
16
|
+
Severity.ERROR: (
|
|
17
|
+
"Convention violations likely to cause downstream pipeline or "
|
|
18
|
+
"interoperability problems. These should be fixed."
|
|
19
|
+
),
|
|
20
|
+
Severity.WARNING: (
|
|
21
|
+
"Probable problems or important inconsistencies that should be "
|
|
22
|
+
"reviewed."
|
|
23
|
+
),
|
|
24
|
+
Severity.INFO: "Non-blocking observations recorded by the validator.",
|
|
25
|
+
}
|
|
26
|
+
ACTIONABLE_SEVERITIES = (Severity.ERROR, Severity.WARNING)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def inventory_value(
|
|
30
|
+
report: ValidationReport,
|
|
31
|
+
key: str,
|
|
32
|
+
default: object,
|
|
33
|
+
) -> object:
|
|
34
|
+
"""Read one optional inventory fact without hiding its default."""
|
|
35
|
+
|
|
36
|
+
return report.inventory.get(key, default)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def rule_number(rule_id: str) -> int:
|
|
40
|
+
"""Return the numeric portion of a rule ID for numeric sorting."""
|
|
41
|
+
|
|
42
|
+
return int(rule_id.rsplit("-", 1)[1])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def group_findings(report: ValidationReport) -> dict[str, dict[str, Any]]:
|
|
46
|
+
"""Group findings by rule for human-readable presentation."""
|
|
47
|
+
|
|
48
|
+
groups: dict[str, dict[str, Any]] = {}
|
|
49
|
+
for finding in report.findings:
|
|
50
|
+
group = groups.setdefault(
|
|
51
|
+
finding.rule_id,
|
|
52
|
+
{
|
|
53
|
+
"severity": finding.severity,
|
|
54
|
+
"title": finding.title,
|
|
55
|
+
"findings": [],
|
|
56
|
+
},
|
|
57
|
+
)
|
|
58
|
+
group["findings"].append(finding)
|
|
59
|
+
|
|
60
|
+
return groups
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sort_rule_groups(
|
|
64
|
+
groups_by_rule: dict[str, dict[str, Any]],
|
|
65
|
+
) -> dict[Severity, list[tuple[str, dict[str, Any]]]]:
|
|
66
|
+
"""Sort rule groups by severity, then numeric rule ID."""
|
|
67
|
+
|
|
68
|
+
groups_by_severity: dict[Severity, list[tuple[str, dict[str, Any]]]] = {
|
|
69
|
+
severity: [] for severity in SEVERITY_ORDER
|
|
70
|
+
}
|
|
71
|
+
for rule_id, group in groups_by_rule.items():
|
|
72
|
+
groups_by_severity[group["severity"]].append((rule_id, group))
|
|
73
|
+
|
|
74
|
+
for severity in SEVERITY_ORDER:
|
|
75
|
+
groups_by_severity[severity].sort(
|
|
76
|
+
key=lambda item: (rule_number(item[0]), item[0])
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
return groups_by_severity
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Render a concise human-readable validation summary for the terminal."""
|
|
2
|
+
|
|
3
|
+
from omids_validator.models import ValidationReport
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def render(report: ValidationReport, report_directory: str) -> str:
|
|
7
|
+
"""Return a short summary without rescanning the dataset."""
|
|
8
|
+
|
|
9
|
+
summary = report.summary
|
|
10
|
+
return (
|
|
11
|
+
"Validation complete: "
|
|
12
|
+
f"{summary['error']} error(s), "
|
|
13
|
+
f"{summary['warning']} warning(s), "
|
|
14
|
+
f"{summary['info']} info finding(s).\n"
|
|
15
|
+
f"HTML report: {report_directory}/report.html\n"
|
|
16
|
+
f"Markdown report: {report_directory}/report.md\n"
|
|
17
|
+
f"JSON report: {report_directory}/report.json"
|
|
18
|
+
)
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Load the rule definitions used by validation, reports, and documentation.
|
|
2
|
+
|
|
3
|
+
Layer functions use ``finding_for_rule`` to give every finding the title,
|
|
4
|
+
severity, and guidance recorded in the packaged ``rules.json`` catalogue.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from importlib.resources import files
|
|
12
|
+
from types import MappingProxyType
|
|
13
|
+
from typing import Any, Mapping
|
|
14
|
+
|
|
15
|
+
from omids_validator.models import Finding, Severity
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
CATALOG_SCHEMA_VERSION = "1.0"
|
|
19
|
+
RULE_ID_PATTERN = re.compile(r"^MIDS-([0-9])([0-9]{2})$")
|
|
20
|
+
RULE_STATUSES = frozenset({"active", "deferred"})
|
|
21
|
+
NEXT_STEP_KINDS = ("command", "tool", "manual", "review", "none")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RuleCatalogError(ValueError):
|
|
25
|
+
"""Raised when the packaged rule catalogue is internally inconsistent."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class NextStep:
|
|
30
|
+
"""One rule-level practical response."""
|
|
31
|
+
|
|
32
|
+
kind: str
|
|
33
|
+
text: str
|
|
34
|
+
command: str | None = None
|
|
35
|
+
tool: str | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class RuleDefinition:
|
|
40
|
+
"""Static definition shared by validation findings and documentation."""
|
|
41
|
+
|
|
42
|
+
rule_id: str
|
|
43
|
+
layer: int
|
|
44
|
+
status: str
|
|
45
|
+
title: str
|
|
46
|
+
severity: Severity
|
|
47
|
+
description: str
|
|
48
|
+
next_step: NextStep
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class RuleCatalog:
|
|
53
|
+
"""Validated rule definitions from one catalogue schema version."""
|
|
54
|
+
|
|
55
|
+
schema_version: str
|
|
56
|
+
rules: Mapping[str, RuleDefinition]
|
|
57
|
+
|
|
58
|
+
def get(self, rule_id: str) -> RuleDefinition:
|
|
59
|
+
"""Return one rule definition or raise a catalogue-specific error."""
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
return self.rules[rule_id]
|
|
63
|
+
except KeyError as error:
|
|
64
|
+
raise RuleCatalogError(
|
|
65
|
+
f"Rule catalogue does not define {rule_id}."
|
|
66
|
+
) from error
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _require_object(value: object, location: str) -> dict[str, Any]:
|
|
70
|
+
if not isinstance(value, dict):
|
|
71
|
+
raise RuleCatalogError(f"{location} must be a JSON object.")
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _require_exact_fields(
|
|
76
|
+
value: dict[str, Any],
|
|
77
|
+
*,
|
|
78
|
+
required: set[str],
|
|
79
|
+
location: str,
|
|
80
|
+
) -> None:
|
|
81
|
+
missing = sorted(required - value.keys())
|
|
82
|
+
unexpected = sorted(value.keys() - required)
|
|
83
|
+
if missing:
|
|
84
|
+
raise RuleCatalogError(
|
|
85
|
+
f"{location} is missing required field(s): {', '.join(missing)}."
|
|
86
|
+
)
|
|
87
|
+
if unexpected:
|
|
88
|
+
raise RuleCatalogError(
|
|
89
|
+
f"{location} has unexpected field(s): {', '.join(unexpected)}."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _require_nonempty_string(value: object, location: str) -> str:
|
|
94
|
+
if not isinstance(value, str) or not value.strip():
|
|
95
|
+
raise RuleCatalogError(f"{location} must be a non-empty string.")
|
|
96
|
+
return value
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse_next_step(value: object, rule_id: str) -> NextStep:
|
|
100
|
+
location = f"{rule_id}.next_step"
|
|
101
|
+
step = _require_object(value, location)
|
|
102
|
+
kind = _require_nonempty_string(step.get("kind"), f"{location}.kind")
|
|
103
|
+
if kind not in NEXT_STEP_KINDS:
|
|
104
|
+
allowed = ", ".join(NEXT_STEP_KINDS)
|
|
105
|
+
raise RuleCatalogError(
|
|
106
|
+
f"{location}.kind must be one of: {allowed}."
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
required_fields = {"kind", "text"}
|
|
110
|
+
if kind == "command":
|
|
111
|
+
required_fields.add("command")
|
|
112
|
+
elif kind == "tool":
|
|
113
|
+
required_fields.add("tool")
|
|
114
|
+
_require_exact_fields(step, required=required_fields, location=location)
|
|
115
|
+
|
|
116
|
+
text = _require_nonempty_string(step["text"], f"{location}.text")
|
|
117
|
+
command = None
|
|
118
|
+
tool = None
|
|
119
|
+
if kind == "command":
|
|
120
|
+
command = _require_nonempty_string(
|
|
121
|
+
step["command"], f"{location}.command"
|
|
122
|
+
)
|
|
123
|
+
elif kind == "tool":
|
|
124
|
+
tool = _require_nonempty_string(step["tool"], f"{location}.tool")
|
|
125
|
+
|
|
126
|
+
return NextStep(kind=kind, text=text, command=command, tool=tool)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _parse_rule(rule_id: str, value: object) -> RuleDefinition:
|
|
130
|
+
if not isinstance(rule_id, str):
|
|
131
|
+
raise RuleCatalogError("Rule catalogue IDs must be strings.")
|
|
132
|
+
|
|
133
|
+
match = RULE_ID_PATTERN.fullmatch(rule_id)
|
|
134
|
+
if match is None:
|
|
135
|
+
raise RuleCatalogError(
|
|
136
|
+
f"Rule ID {rule_id!r} must match MIDS- followed by three digits."
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
location = f"rules.{rule_id}"
|
|
140
|
+
rule = _require_object(value, location)
|
|
141
|
+
_require_exact_fields(
|
|
142
|
+
rule,
|
|
143
|
+
required={
|
|
144
|
+
"layer",
|
|
145
|
+
"status",
|
|
146
|
+
"title",
|
|
147
|
+
"severity",
|
|
148
|
+
"description",
|
|
149
|
+
"next_step",
|
|
150
|
+
},
|
|
151
|
+
location=location,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
layer = rule["layer"]
|
|
155
|
+
if not isinstance(layer, int) or isinstance(layer, bool):
|
|
156
|
+
raise RuleCatalogError(f"{location}.layer must be an integer.")
|
|
157
|
+
expected_layer = int(match.group(1))
|
|
158
|
+
if layer != expected_layer:
|
|
159
|
+
raise RuleCatalogError(
|
|
160
|
+
f"{location}.layer must be {expected_layer} to match {rule_id}."
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
status = _require_nonempty_string(rule["status"], f"{location}.status")
|
|
164
|
+
if status not in RULE_STATUSES:
|
|
165
|
+
allowed = ", ".join(sorted(RULE_STATUSES))
|
|
166
|
+
raise RuleCatalogError(
|
|
167
|
+
f"{location}.status must be one of: {allowed}."
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
severity_value = _require_nonempty_string(
|
|
171
|
+
rule["severity"], f"{location}.severity"
|
|
172
|
+
)
|
|
173
|
+
try:
|
|
174
|
+
severity = Severity(severity_value)
|
|
175
|
+
except ValueError as error:
|
|
176
|
+
allowed = ", ".join(severity.value for severity in Severity)
|
|
177
|
+
raise RuleCatalogError(
|
|
178
|
+
f"{location}.severity must be one of: {allowed}."
|
|
179
|
+
) from error
|
|
180
|
+
|
|
181
|
+
return RuleDefinition(
|
|
182
|
+
rule_id=rule_id,
|
|
183
|
+
layer=layer,
|
|
184
|
+
status=status,
|
|
185
|
+
title=_require_nonempty_string(rule["title"], f"{location}.title"),
|
|
186
|
+
severity=severity,
|
|
187
|
+
description=_require_nonempty_string(
|
|
188
|
+
rule["description"], f"{location}.description"
|
|
189
|
+
),
|
|
190
|
+
next_step=_parse_next_step(rule["next_step"], rule_id),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def validate_rule_catalog(value: object) -> RuleCatalog:
|
|
195
|
+
"""Validate decoded catalogue data and return immutable definitions."""
|
|
196
|
+
|
|
197
|
+
catalogue = _require_object(value, "Rule catalogue")
|
|
198
|
+
_require_exact_fields(
|
|
199
|
+
catalogue,
|
|
200
|
+
required={"schema_version", "rules"},
|
|
201
|
+
location="Rule catalogue",
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
schema_version = _require_nonempty_string(
|
|
205
|
+
catalogue["schema_version"], "Rule catalogue.schema_version"
|
|
206
|
+
)
|
|
207
|
+
if schema_version != CATALOG_SCHEMA_VERSION:
|
|
208
|
+
raise RuleCatalogError(
|
|
209
|
+
"Unsupported rule catalogue schema version "
|
|
210
|
+
f"{schema_version!r}; expected {CATALOG_SCHEMA_VERSION!r}."
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
raw_rules = _require_object(catalogue["rules"], "Rule catalogue.rules")
|
|
214
|
+
if not raw_rules:
|
|
215
|
+
raise RuleCatalogError("Rule catalogue.rules must not be empty.")
|
|
216
|
+
|
|
217
|
+
definitions = {
|
|
218
|
+
rule_id: _parse_rule(rule_id, rule)
|
|
219
|
+
for rule_id, rule in raw_rules.items()
|
|
220
|
+
}
|
|
221
|
+
return RuleCatalog(
|
|
222
|
+
schema_version=schema_version,
|
|
223
|
+
rules=MappingProxyType(definitions),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _object_without_duplicate_keys(
|
|
228
|
+
pairs: list[tuple[str, object]],
|
|
229
|
+
) -> dict[str, object]:
|
|
230
|
+
result: dict[str, object] = {}
|
|
231
|
+
for key, value in pairs:
|
|
232
|
+
if key in result:
|
|
233
|
+
raise RuleCatalogError(f"Rule catalogue repeats JSON key {key!r}.")
|
|
234
|
+
result[key] = value
|
|
235
|
+
return result
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def parse_rule_catalog(text: str) -> RuleCatalog:
|
|
239
|
+
"""Decode and validate rule-catalogue JSON text."""
|
|
240
|
+
|
|
241
|
+
try:
|
|
242
|
+
value = json.loads(text, object_pairs_hook=_object_without_duplicate_keys)
|
|
243
|
+
except json.JSONDecodeError as error:
|
|
244
|
+
raise RuleCatalogError(
|
|
245
|
+
f"Rule catalogue is not valid JSON: {error.msg}."
|
|
246
|
+
) from error
|
|
247
|
+
return validate_rule_catalog(value)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@lru_cache(maxsize=1)
|
|
251
|
+
def load_rule_catalog() -> RuleCatalog:
|
|
252
|
+
"""Load and validate the packaged rule catalogue once."""
|
|
253
|
+
|
|
254
|
+
catalogue_path = files("omids_validator").joinpath("data", "rules.json")
|
|
255
|
+
try:
|
|
256
|
+
text = catalogue_path.read_text(encoding="utf-8")
|
|
257
|
+
except OSError as error:
|
|
258
|
+
raise RuleCatalogError(
|
|
259
|
+
f"Rule catalogue could not be read: {error}."
|
|
260
|
+
) from error
|
|
261
|
+
return parse_rule_catalog(text)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def finding_for_rule(
|
|
265
|
+
rule_id: str,
|
|
266
|
+
*,
|
|
267
|
+
message: str,
|
|
268
|
+
path: str | None = None,
|
|
269
|
+
) -> Finding:
|
|
270
|
+
"""Create a finding using the catalogue title and severity."""
|
|
271
|
+
|
|
272
|
+
rule = load_rule_catalog().get(rule_id)
|
|
273
|
+
return Finding(
|
|
274
|
+
rule_id=rule.rule_id,
|
|
275
|
+
severity=rule.severity,
|
|
276
|
+
title=rule.title,
|
|
277
|
+
message=message,
|
|
278
|
+
path=path,
|
|
279
|
+
)
|