control_coverage/importers.py

122 lines · 5235 bytes

7 symbols in this file
  1"""Convert published framework content into catalog YAML.
  2
  3Supported inputs:
  4
  5* an OSCAL catalog (JSON), with nested control enhancements;
  6* an OSCAL profile (JSON) applied to its OSCAL catalog, keeping only the
  7  controls the profile includes (for example a NIST 800-53 baseline);
  8* a CISO Assistant framework library (YAML): assessable requirement nodes
  9  become controls, their parent node becomes the family.
 10
 11Each result records where it came from (`source`, `imported_from`, `version`)
 12and the `license` the content is used under, so the provenance travels with
 13the catalog. Converting the same input twice yields the same YAML.
 14"""
 15
 16from __future__ import annotations
 17
 18import json
 19import re
 20
 21import yaml
 22
 23
 24def _code(raw: str) -> str:
 25    code = re.sub(r"[^A-Za-z0-9]+", "", str(raw or "")).upper()
 26    if not code:
 27        raise ValueError("framework code is required")
 28    return code
 29
 30
 31def _oscal_controls(controls: list[dict], family: str, out: list[dict], keep: set[str] | None) -> None:
 32    for c in controls or []:
 33        if keep is None or c.get("id") in keep:
 34            out.append({"id": str(c["id"]).upper(), "title": str(c.get("title", "")).strip(), "family": family})
 35        _oscal_controls(c.get("controls") or [], family, out, keep)
 36
 37
 38def from_oscal_catalog(doc: dict, framework: str, license_text: str, imported_from: str = "", keep: set[str] | None = None) -> dict:
 39    cat = doc.get("catalog") if isinstance(doc, dict) else None
 40    if not isinstance(cat, dict):
 41        raise ValueError("not an OSCAL catalog (no 'catalog' object)")  # noqa: TRY004
 42    meta = cat.get("metadata") or {}
 43    controls: list[dict] = []
 44    for group in cat.get("groups") or []:
 45        _oscal_controls(group.get("controls") or [], str(group.get("title") or group.get("id") or ""), controls, keep)
 46    _oscal_controls(cat.get("controls") or [], "", controls, keep)
 47    if not controls:
 48        raise ValueError("the OSCAL catalog has no controls")
 49    return {
 50        "framework": _code(framework),
 51        "name": str(meta.get("title") or framework),
 52        "version": str(meta.get("version") or ""),
 53        "coverage": "complete" if keep is None else "partial",
 54        "source": f"OSCAL catalog {cat.get('uuid', '')}".strip(),
 55        "license": license_text,
 56        "imported_from": imported_from,
 57        "controls": controls,
 58    }
 59
 60
 61def from_oscal_profile(profile_doc: dict, catalog_doc: dict, framework: str, license_text: str, imported_from: str = "") -> dict:
 62    prof = profile_doc.get("profile") if isinstance(profile_doc, dict) else None
 63    if not isinstance(prof, dict):
 64        raise ValueError("not an OSCAL profile (no 'profile' object)")  # noqa: TRY004
 65    keep: set[str] = set()
 66    for imp in prof.get("imports") or []:
 67        for inc in imp.get("include-controls") or []:
 68            keep.update(inc.get("with-ids") or [])
 69    if not keep:
 70        raise ValueError("the OSCAL profile selects no controls with 'include-controls'/'with-ids'")
 71    data = from_oscal_catalog(catalog_doc, framework, license_text, imported_from, keep)
 72    pmeta = prof.get("metadata") or {}
 73    data["name"] = str(pmeta.get("title") or data["name"])
 74    data["version"] = str(pmeta.get("version") or data["version"])
 75    data["source"] = f"OSCAL profile {prof.get('uuid', '')} over {data['source']}".strip()
 76    data["coverage"] = "complete"  # complete for the profile's baseline
 77    return data
 78
 79
 80def from_ciso_assistant(doc: dict, framework: str | None, license_text: str = "", imported_from: str = "") -> dict:
 81    if not isinstance(doc, dict):
 82        raise ValueError("not a CISO Assistant library")  # noqa: TRY004
 83    fw = ((doc.get("objects") or {}).get("framework")) or {}
 84    nodes = fw.get("requirement_nodes") or []
 85    if not nodes:
 86        raise ValueError("the library has no framework requirement_nodes")
 87    by_urn = {n.get("urn"): n for n in nodes}
 88    controls = []
 89    for n in nodes:
 90        if not n.get("assessable") or not n.get("ref_id"):
 91            continue
 92        parent = by_urn.get(n.get("parent_urn")) or {}
 93        controls.append(
 94            {
 95                "id": str(n["ref_id"]),
 96                "title": str(n.get("name") or n.get("description") or "").strip()[:200],
 97                "family": str(parent.get("name") or parent.get("ref_id") or ""),
 98            }
 99        )
100    if not controls:
101        raise ValueError("the library has no assessable requirements with a ref_id")
102    return {
103        "framework": _code(framework or fw.get("ref_id") or doc.get("ref_id") or ""),
104        "name": str(fw.get("name") or doc.get("name") or ""),
105        "version": str(doc.get("version") or ""),
106        "coverage": "complete",
107        "source": f"CISO Assistant library {doc.get('urn', '')} ({doc.get('provider') or doc.get('packager') or 'unknown provider'})",
108        "license": license_text or str(doc.get("copyright") or ""),
109        "imported_from": imported_from,
110        "controls": controls,
111    }
112
113
114def to_yaml(data: dict) -> str:
115    return yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
116
117
118def load_json(text: str) -> dict:
119    try:
120        return json.loads(text)
121    except json.JSONDecodeError as exc:
122        raise ValueError(f"not valid JSON: {exc}") from exc