Skip to content

reports

RenderedReport dataclass

Bases: BaseModel

Convenience wrapper for render results.

Source code in wintermute/reports.py
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass
class RenderedReport(BaseModel):
    """Convenience wrapper for render results."""

    spec: ReportSpec
    result: Any

    __schema__ = {"spec": ReportSpec}
    __enums__ = {}

Report dataclass

Bases: BaseModel

Facade class—call Report.render/save regardless of backend.

Example

from wintermute.reports import Report, ReportSpec from wintermute.backends.docx_reports import DocxTplPerVulnBackend from wintermute.basemodels import CloudAccount, Peripheral from wintermute.findings import Vulnerability, ReproductionStep, Risk Report.register_backend( ... "word_tpl_per_vuln", ... DocxTplPerVulnBackend( ... template_dir="templates", ... main_template="report_main.docx", ... vuln_template="report_vuln.docx", ... ), ... make_default=True, ... ) acct = CloudAccount( name="aws-prod", ... vulnerabilities=[ ... Vulnerability( ... title="S3 bucket public", ... description="Bucket allows public read", ... risk=Risk(likelihood="High", impact="Medium", severity="High"), ... reproduction_steps=[ ... ReproductionStep(title="List objects", tool="aws", action="s3 ls", arguments=["s3://bucket"]) ... ], ... verified=True, ... ) ... ], ... ) periph = Peripheral( ... name="UART0", ... pType="UART", ... vulnerabilities=[ ... Vulnerability( ... title="No console auth", ... description="UART console lacks auth", ... cvss=6, ... verified=False, ... ) ... ], ... ) spec = ReportSpec( ... title="Security Assessment – Q4", ... author="Enrique", ... summary="Overall posture is improving. Top issues: public S3 access, UART console auth.", ... ) Report.save(spec, [acct, periph], "out.docx")

Source code in wintermute/reports.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
@dataclass
class Report(BaseModel, metaclass=ReportMeta):
    """Facade class—call Report.render/save regardless of backend.

    Example:
        >>> from wintermute.reports import Report, ReportSpec
        >>> from wintermute.backends.docx_reports import DocxTplPerVulnBackend
        >>> from wintermute.basemodels import CloudAccount, Peripheral
        >>> from wintermute.findings import Vulnerability, ReproductionStep, Risk
        >>> Report.register_backend(
        ...     "word_tpl_per_vuln",
        ...     DocxTplPerVulnBackend(
        ...         template_dir="templates",
        ...         main_template="report_main.docx",
        ...         vuln_template="report_vuln.docx",
        ...     ),
        ...     make_default=True,
        ... )
        >>> acct = CloudAccount(
        >>>     name="aws-prod",
        ...     vulnerabilities=[
        ...         Vulnerability(
        ...             title="S3 bucket public",
        ...             description="Bucket allows public read",
        ...             risk=Risk(likelihood="High", impact="Medium", severity="High"),
        ...             reproduction_steps=[
        ...                 ReproductionStep(title="List objects", tool="aws", action="s3 ls", arguments=["s3://bucket"])
        ...             ],
        ...             verified=True,
        ...         )
        ...     ],
        ... )
        >>> periph = Peripheral(
        ...     name="UART0",
        ...     pType="UART",
        ...     vulnerabilities=[
        ...         Vulnerability(
        ...             title="No console auth",
        ...             description="UART console lacks auth",
        ...             cvss=6,
        ...             verified=False,
        ...         )
        ...     ],
        ... )
        >>> spec = ReportSpec(
        ...     title="Security Assessment – Q4",
        ...     author="Enrique",
        ...     summary="Overall posture is improving. Top issues: public S3 access, UART console auth.",
        ... )
        >>> Report.save(spec, [acct, periph], "out.docx")
    """

    # You typically won't instantiate Report; the class methods are the API.
    spec: ReportSpec

    _backend: ClassVar[Optional[ReportBackend]] = None
    _backends: ClassVar[Dict[str, ReportBackend]] = {}

    @classmethod
    def set_backend(cls, backend: ReportBackend) -> None:
        raise NotImplementedError

    @classmethod
    def register_backend(
        cls, name: str, backend: ReportBackend, *, make_default: bool = False
    ) -> None:
        raise NotImplementedError

    @classmethod
    def use_backend(cls, name: str) -> None:
        raise NotImplementedError

    @classmethod
    def render(
        cls, spec: ReportSpec, objects: Iterable[Any], *, include_summary: bool = True
    ) -> RenderedReport:
        raise NotImplementedError

    @classmethod
    def save(
        cls,
        spec: ReportSpec,
        objects: Iterable[Any],
        path: str,
        *,
        include_summary: bool = True,
    ) -> None:
        raise NotImplementedError

    __schema__ = {"spec": ReportSpec}
    __enums__ = {}

collect_test_runs(objects)

Yields (TestCaseRun, TestCase, context_path). We look for an Operation/Pentest to resolve the TestCase definition.

Source code in wintermute/reports.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def collect_test_runs(
    objects: Iterable[Any],
) -> Iterable[Tuple[TestCaseRun, Optional[TestCase], str]]:
    """
    Yields (TestCaseRun, TestCase, context_path).
    We look for an Operation/Pentest to resolve the TestCase definition.
    """
    seen: Set[int] = set()

    # Pre-calculate a lookup map if the object is an Operation
    tc_lookup: Dict[str, TestCase] = {}
    for obj in objects:
        if hasattr(obj, "iterTestCases"):
            tc_lookup.update({tc.code: tc for tc in obj.iterTestCases()})

    def _walk(
        node: Any, path: str
    ) -> Iterator[Tuple[TestCaseRun, Optional[TestCase], str]]:
        oid = id(node)
        if oid in seen:
            return
        seen.add(oid)

        if isinstance(node, TestCaseRun):
            parent_tc = tc_lookup.get(node.test_case_code)
            yield (node, parent_tc, path)
            return
        if isinstance(node, (list, tuple)):
            for i, item in enumerate(node):
                yield from _walk(item, f"{path}[{i}]")
        elif hasattr(node, "__dict__"):
            # Check for attributes that hold test execution data
            for attr in ["test_runs", "test_plans"]:
                if hasattr(node, attr):
                    yield from _walk(getattr(node, attr), f"{path}.{attr}")

    for obj in objects:
        yield from _walk(obj, obj.__class__.__name__)
    log.info(f"Collected test runs from objects: {len(seen)} nodes visited.")

collect_vulnerabilities(objects)

Walk arbitrary objects/lists/dicts/BaseModel graphs and yield (Vulnerability, context_path) pairs. The traversal skips BaseModel class metadata (JSON_ADAPTERS, PARSERS, schema, enums) and only treats a dict as a Vulnerability if it "looks like" one (has core fields).

Source code in wintermute/reports.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def collect_vulnerabilities(
    objects: Iterable[Any],
) -> Iterable[Tuple[Vulnerability, str]]:
    """
    Walk arbitrary objects/lists/dicts/BaseModel graphs and yield
    (Vulnerability, context_path) pairs. The traversal skips BaseModel class
    metadata (JSON_ADAPTERS, PARSERS, __schema__, __enums__) and only treats a
    dict as a Vulnerability if it "looks like" one (has core fields).
    """
    seen: Set[int] = set()
    SKIP_ATTRS = {
        "JSON_ADAPTERS",
        "PARSERS",
        "__schema__",
        "__enums__",
        "vulnerabilities",
    }

    def _looks_like_vuln_dict(d: Any) -> bool:
        if not isinstance(d, dict):
            return False
        # require at least a title or a description to avoid class-level dicts
        if "title" in d:
            return True
        # alternatively, a minimal risk block + description is also fine
        if "description" in d and isinstance(
            d.get("risk"), (dict, BaseModel, type(None))
        ):
            return True
        return False

    def coerce_v(node: Any) -> Optional[Vulnerability]:
        if isinstance(node, Vulnerability):
            return node
        if isinstance(node, dict) and _looks_like_vuln_dict(node):
            return Vulnerability.from_dict(node)
        return None

    def _walk(node: Any, path: str) -> Iterator[Tuple[Vulnerability, str]]:
        oid = id(node)
        if oid in seen:
            return
        seen.add(oid)

        # Direct vulnerability / vuln-like dict
        v = coerce_v(node)
        if v is not None:
            yield (v, path)
            return

        # List/Tuple
        if isinstance(node, (list, tuple)):
            for i, item in enumerate(node):
                yield from _walk(item, f"{path}[{i}]")
            return

        # Dict
        if isinstance(node, dict):
            for k, val in node.items():
                # keys in dicts can be non-strings; the path is just for humans
                key_str = str(k)
                yield from _walk(val, f"{path}.{key_str}")
            return

        # BaseModel or general object
        # 1) common convention: attribute named "vulnerabilities"
        if hasattr(node, "vulnerabilities"):
            maybe = getattr(node, "vulnerabilities")
            if isinstance(maybe, (list, tuple)):
                for i, item in enumerate(maybe):
                    vv = coerce_v(item)
                    if vv is not None:
                        yield (vv, f"{path}.vulnerabilities[{i}]")

        # 2) Shallow attribute walk for nested containers/models
        for attr in dir(node):
            if attr.startswith("_") or attr in SKIP_ATTRS:
                continue
            # Avoid binding descriptors/specials; best-effort try/except
            try:
                val = getattr(node, attr)
            except Exception:
                continue
            # Only follow containers and BaseModel instances; skip class-level dicts etc.
            if isinstance(val, (list, tuple, dict, BaseModel)):
                yield from _walk(val, f"{path}.{attr}")

    # Roots
    for obj in objects:
        cls_name = getattr(obj, "__class__", type(obj)).__name__
        name = getattr(obj, "name", None)
        label = f"{cls_name}[name={name}]" if isinstance(name, str) else cls_name
        yield from _walk(obj, label)
    log.info(f"Collected vulnerabilities from objects: {len(seen)} nodes visited.")