Commit af9e4d63ff

af9e4d63ffd6340ff366304e7a910fcc8b6a10de

parent: 4584ae1d4a

Unsigned

cmc <hello@cleberg.net> · 2026-10-29 21:13 UTC

Partially supported state, typed mappings, catalog provenance and importers (!1)

- Coverage state `partially_supported`: in scope, passing evidence and no failures, but every passing observation comes through a partial mapping (`partial`, `subset`, `intersects`). Counts as addressed, not as supported. Markdown, HTML, and SoA reporters show it.
- `Observation` gains `relationship` (default `full`) and `mapping` (which mapping linked it). Report JSON findings may carry `control_mappings` (`{code: {relationship, rationale}}`).
- Catalog provenance fields `license` and `imported_from`; `catalog.load_file(path)`.
- `control_coverage.importers`: OSCAL catalog (groups and nested enhancements), OSCAL profile applied to its catalog (`include-controls`/`with-ids`), and CISO Assistant framework libraries (assessable requirement nodes, parent as family), each with source, version, license, and origin; conversion is deterministic.
- Needed by audit-workbench roadmap 4.1 and 4.2. Workbench suite passes against this branch (192).
- Tests: 68 passed (6 new).

Layout: unified · split

CHANGELOG.md +9
@@ -4,6 +4,15 @@ All notable changes to this project are documented here. The format is based on
44[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres
55to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66
7## [Unreleased]
8
9### Added
10
11- Coverage state `partially_supported`: passing evidence exists but only through partial mappings (`partial`, `subset`, `intersects`).
12- `Observation.relationship` and `Observation.mapping`; report JSON findings may carry `control_mappings` (`{code: {relationship, rationale}}`), as audit-report writes for typed rule mappings.
13- Catalog provenance: `license` and `imported_from` fields; `catalog.load_file`.
14- `control_coverage.importers`: OSCAL catalogs (with enhancements), OSCAL profiles over a catalog, and CISO Assistant framework libraries to catalog YAML.
15
716## [1.0.0] - 2026-08-07
817
918First stable release. The bundled catalogs, the coverage / Statement of
control_coverage/catalog.py +10 −1
@@ -62,6 +62,8 @@ class Catalog:
6262 source: str
6363 controls: list[Control]
6464 sha256: str = "" # digest of the catalog file, so coverage ties to a mapping
65 license: str = "" # terms the catalog content is used under
66 imported_from: str = "" # original file or URL when converted by an importer
6567
6668 @property
6769 def complete(self) -> bool:
@@ -87,7 +89,12 @@ def _resolve(name: str) -> Path:
8789
8890def load(name: str) -> Catalog:
8991 """Load a bundled catalog by framework name, short code, or alias."""
90 path = _resolve(name)
92 return load_file(_resolve(name))
93
94
95def load_file(path: str | Path) -> Catalog:
96 """Load a catalog YAML file (bundled, imported, or hand-written)."""
97 path = Path(path)
9198 text = path.read_text(encoding="utf-8")
9299 raw = yaml.safe_load(text)
93100 framework = raw["framework"]
@@ -108,6 +115,8 @@ def load(name: str) -> Catalog:
108115 source=raw.get("source", ""),
109116 controls=controls,
110117 sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(),
118 license=str(raw.get("license", "")),
119 imported_from=str(raw.get("imported_from", "")),
111120 )
112121
113122
control_coverage/corpus.py +14
@@ -37,6 +37,16 @@ class Observation:
3737 title: str
3838 severity: str
3939 source: str # report file / package name the finding came from
40 relationship: str = "full" # how the evidence relates to the control; see RELATIONSHIPS
41 mapping: str = "" # which mapping linked them (rule, crosswalk pack, rationale)
42
43
44# Relationship of evidence (or a source control) to a target control. Following
45# NIST IR 8477 for crosswalks: `equal` and `superset` fully cover the target;
46# `subset` and `intersects` cover part of it. Rule mappings use `full` or `partial`.
47FULL_RELATIONSHIPS = {"full", "equal", "superset"}
48PARTIAL_RELATIONSHIPS = {"partial", "subset", "intersects"}
49RELATIONSHIPS = FULL_RELATIONSHIPS | PARTIAL_RELATIONSHIPS
4050
4151
4252def _iter_report(doc: dict, source: str):
@@ -45,7 +55,9 @@ def _iter_report(doc: dict, source: str):
4555 rule_id = f.get("id", "")
4656 title = f.get("title", "")
4757 severity = f.get("severity", "medium")
58 mappings = f.get("control_mappings") or {}
4859 for control in f.get("controls", []):
60 m = mappings.get(control) or {}
4961 yield Observation(
5062 control=control,
5163 status=status,
@@ -53,6 +65,8 @@ def _iter_report(doc: dict, source: str):
5365 title=title,
5466 severity=severity,
5567 source=source,
68 relationship=m.get("relationship", "full"),
69 mapping=m.get("rationale", ""),
5670 )
5771
5872
control_coverage/coverage.py +12 −5
@@ -2,7 +2,10 @@
22
33For every control in a catalog we assign one **assurance state**:
44
5* ``supported`` — in scope, at least one mapped finding passes and none fail.
5* ``supported`` — in scope, at least one fully mapped finding passes and none fail.
6* ``partially_supported`` — in scope, findings pass and none fail, but every
7 passing one is only a partial mapping (``partial``,
8 ``subset``, ``intersects``): part of the control is shown.
69* ``failing`` — in scope, at least one mapped finding fails.
710* ``asserted`` — in scope, findings map here but their data was absent
811 (``not_applicable``): evidence was attempted, not obtained.
@@ -20,19 +23,20 @@ from __future__ import annotations
2023from dataclasses import dataclass, field
2124
2225from .catalog import Catalog, Control
23from .corpus import FAIL, PASS, Observation
26from .corpus import FAIL, PARTIAL_RELATIONSHIPS, PASS, Observation
2427
2528SUPPORTED = "supported"
29PARTIALLY_SUPPORTED = "partially_supported"
2630FAILING = "failing"
2731ASSERTED = "asserted"
2832UNADDRESSED = "unaddressed"
2933OUT_OF_SCOPE = "out_of_scope"
3034
3135# Order states appear in reports and roll up in summaries (most urgent first).
32STATE_ORDER = [FAILING, UNADDRESSED, ASSERTED, SUPPORTED, OUT_OF_SCOPE]
36STATE_ORDER = [FAILING, UNADDRESSED, ASSERTED, PARTIALLY_SUPPORTED, SUPPORTED, OUT_OF_SCOPE]
3337
3438# States that count as the control being "addressed" by the corpus at all.
35_ADDRESSED = {SUPPORTED, FAILING, ASSERTED}
39_ADDRESSED = {SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED}
3640
3741
3842@dataclass
@@ -57,7 +61,10 @@ def _state_for(observations: list[Observation]) -> str:
5761 statuses = {o.status for o in observations}
5862 if FAIL in statuses:
5963 return FAILING
60 if PASS in statuses:
64 passing = [o for o in observations if o.status == PASS]
65 if passing:
66 if all(o.relationship in PARTIAL_RELATIONSHIPS for o in passing):
67 return PARTIALLY_SUPPORTED
6168 return SUPPORTED
6269 return ASSERTED # only not_applicable observations remain
6370
control_coverage/importers.py added +122
@@ -0,0 +1,122 @@
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
control_coverage/reporters/html.py +9 −2
@@ -14,6 +14,7 @@ from ..coverage import (
1414 ASSERTED,
1515 FAILING,
1616 OUT_OF_SCOPE,
17 PARTIALLY_SUPPORTED,
1718 SUPPORTED,
1819 UNADDRESSED,
1920)
@@ -23,6 +24,7 @@ if TYPE_CHECKING:
2324
2425_STATE_LABEL = {
2526 SUPPORTED: "supported",
27 PARTIALLY_SUPPORTED: "partially supported",
2628 FAILING: "failing",
2729 ASSERTED: "asserted",
2830 UNADDRESSED: "unaddressed",
@@ -30,6 +32,7 @@ _STATE_LABEL = {
3032}
3133_STATE_CLASS = {
3234 SUPPORTED: "supported",
35 PARTIALLY_SUPPORTED: "partial",
3336 FAILING: "failing",
3437 ASSERTED: "asserted",
3538 UNADDRESSED: "unaddressed",
@@ -56,6 +59,7 @@ td.num, th.num { text-align: right; }
5659.badge { display: inline-block; font-weight: 700; font-size: .72rem; letter-spacing: .02em;
5760 padding: .12rem .5rem; border-radius: 999px; white-space: nowrap; }
5861.badge.supported { background: #e5f6ea; color: #1a7f37; }
62.badge.partial { background: #eef7f0; color: #3d7a4d; }
5963.badge.failing { background: #fdeaea; color: #c1272d; }
6064.badge.asserted { background: #fff4e0; color: #a8620a; }
6165.badge.unaddressed { background: #eceaf6; color: #5b4bb0; }
@@ -64,6 +68,7 @@ td.num, th.num { text-align: right; }
6468 border: 1px solid #ddd; }
6569.bar > span { display: block; }
6670.bar .supported { background: #35b866; }
71.bar .partial { background: #8fcf9f; }
6772.bar .failing { background: #e2565b; }
6873.bar .asserted { background: #eaa53c; }
6974.bar .unaddressed { background: #8877d8; }
@@ -81,6 +86,7 @@ footer { margin-top: 3rem; font-size: .8rem; color: #888; border-top: 1px solid
8186 th, td { border-color: #333; } th { background: #202126; }
8287 .headline small, .legend { color: #999; }
8388 .badge.supported { background: #12321d; color: #4ac36a; }
89 .badge.partial { background: #1b2c20; color: #8fcf9f; }
8490 .badge.failing { background: #3a1416; color: #ff6b70; }
8591 .badge.asserted { background: #33260f; color: #e6a94e; }
8692 .badge.unaddressed { background: #211d3a; color: #9d8ef0; }
@@ -92,6 +98,7 @@ footer { margin-top: 3rem; font-size: .8rem; color: #888; border-top: 1px solid
9298
9399_LEGEND_COLORS = {
94100 SUPPORTED: "#35b866",
101 PARTIALLY_SUPPORTED: "#8fcf9f",
95102 FAILING: "#e2565b",
96103 ASSERTED: "#eaa53c",
97104 UNADDRESSED: "#8877d8",
@@ -107,7 +114,7 @@ def _bar(fc: FrameworkCoverage) -> str:
107114 counts = fc.counts
108115 total = sum(counts.values()) or 1
109116 segments = []
110 for state in [SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
117 for state in [SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
111118 n = counts[state]
112119 if not n:
113120 continue
@@ -121,7 +128,7 @@ def _bar(fc: FrameworkCoverage) -> str:
121128
122129def _legend() -> str:
123130 items = []
124 for state in [SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
131 for state in [SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
125132 items.append(
126133 f'<span><i style="background:{_LEGEND_COLORS[state]}"></i>{_STATE_LABEL[state]}</span>'
127134 )
control_coverage/reporters/markdown.py +3
@@ -9,6 +9,7 @@ from ..coverage import (
99 ASSERTED,
1010 FAILING,
1111 OUT_OF_SCOPE,
12 PARTIALLY_SUPPORTED,
1213 STATE_ORDER,
1314 SUPPORTED,
1415 UNADDRESSED,
@@ -19,6 +20,7 @@ if TYPE_CHECKING:
1920
2021_STATE_LABEL = {
2122 SUPPORTED: "supported",
23 PARTIALLY_SUPPORTED: "partially supported",
2224 FAILING: "failing",
2325 ASSERTED: "asserted",
2426 UNADDRESSED: "unaddressed",
@@ -26,6 +28,7 @@ _STATE_LABEL = {
2628}
2729_STATE_MARK = {
2830 SUPPORTED: "✓",
31 PARTIALLY_SUPPORTED: "◑",
2932 FAILING: "✗",
3033 ASSERTED: "◐",
3134 UNADDRESSED: "○",
control_coverage/reporters/soa.py +9 −1
@@ -11,7 +11,14 @@ from __future__ import annotations
1111
1212from typing import TYPE_CHECKING
1313
14from ..coverage import ASSERTED, FAILING, OUT_OF_SCOPE, SUPPORTED, UNADDRESSED
14from ..coverage import (
15 ASSERTED,
16 FAILING,
17 OUT_OF_SCOPE,
18 PARTIALLY_SUPPORTED,
19 SUPPORTED,
20 UNADDRESSED,
21)
1522
1623if TYPE_CHECKING:
1724 from ..coverage import CoverageReport
@@ -19,6 +26,7 @@ if TYPE_CHECKING:
1926# How each assurance state reads as an implementation status in an SoA.
2027_IMPL_STATUS = {
2128 SUPPORTED: "Implemented — supporting evidence collected",
29 PARTIALLY_SUPPORTED: "Partly evidenced — evidence covers part of the control",
2230 FAILING: "Deficient — evidence shows a non-supporting state",
2331 ASSERTED: "Claimed — mapped, but evidence not yet obtained",
2432 UNADDRESSED: "Not evidenced — no evidence collected yet",
tests/test_importers_and_mappings.py added +98
@@ -0,0 +1,98 @@
1"""Catalog importers (OSCAL catalog/profile, CISO Assistant), provenance, and typed mappings."""
2
3import json
4
5import pytest
6import yaml
7
8from control_coverage import catalog, coverage, importers
9from control_coverage.corpus import Observation, load_report
10
11OSCAL = {
12 "catalog": {
13 "uuid": "c-1",
14 "metadata": {"title": "Mini 800-53", "version": "5.1.1"},
15 "groups": [
16 {"id": "ac", "title": "Access Control", "controls": [
17 {"id": "ac-1", "title": "Policy and Procedures"},
18 {"id": "ac-2", "title": "Account Management", "controls": [{"id": "ac-2.1", "title": "Automated Account Management"}]},
19 ]},
20 {"id": "au", "title": "Audit and Accountability", "controls": [{"id": "au-2", "title": "Event Logging"}]},
21 ],
22 }
23}
24PROFILE = {"profile": {"uuid": "p-1", "metadata": {"title": "Mini Low Baseline", "version": "1"}, "imports": [{"href": "#c-1", "include-controls": [{"with-ids": ["ac-2", "au-2"]}]}]}}
25CISO = {
26 "urn": "urn:intuitem:risk:library:dora",
27 "ref_id": "DORA",
28 "name": "DORA",
29 "version": 2,
30 "provider": "EU",
31 "copyright": "EU public domain",
32 "objects": {"framework": {"ref_id": "DORA", "name": "Digital Operational Resilience Act", "requirement_nodes": [
33 {"urn": "u:ch2", "ref_id": "Chapter II", "name": "ICT risk management", "assessable": False},
34 {"urn": "u:a5", "parent_urn": "u:ch2", "ref_id": "Art.5", "name": "Governance and organisation", "assessable": True},
35 {"urn": "u:a9", "parent_urn": "u:ch2", "ref_id": "Art.9", "name": "Protection and prevention", "assessable": True},
36 ]}},
37}
38
39
40def _write(tmp_path, data):
41 path = tmp_path / f"{data['framework'].lower()}.yaml"
42 path.write_text(importers.to_yaml(data))
43 return path
44
45
46def test_oscal_catalog_with_enhancements_and_provenance(tmp_path):
47 data = importers.from_oscal_catalog(OSCAL, "nist", "Public domain (US government work)", "nist-mini.json")
48 assert [c["id"] for c in data["controls"]] == ["AC-1", "AC-2", "AC-2.1", "AU-2"]
49 cat = catalog.load_file(_write(tmp_path, data))
50 assert cat.framework == "NIST" and cat.version == "5.1.1" and cat.license.startswith("Public domain")
51 assert cat.imported_from == "nist-mini.json"
52 assert importers.to_yaml(importers.from_oscal_catalog(OSCAL, "nist", "Public domain (US government work)", "nist-mini.json")) == importers.to_yaml(data)
53
54
55def test_oscal_profile_selects_baseline():
56 data = importers.from_oscal_profile(PROFILE, OSCAL, "NISTLOW", "Public domain")
57 assert [c["id"] for c in data["controls"]] == ["AC-2", "AU-2"]
58 assert data["name"] == "Mini Low Baseline" and "profile p-1" in data["source"]
59
60
61def test_ciso_assistant_library():
62 data = importers.from_ciso_assistant(CISO, None)
63 assert data["framework"] == "DORA" and data["license"] == "EU public domain"
64 assert data["controls"] == [
65 {"id": "Art.5", "title": "Governance and organisation", "family": "ICT risk management"},
66 {"id": "Art.9", "title": "Protection and prevention", "family": "ICT risk management"},
67 ]
68 with pytest.raises(ValueError):
69 importers.from_ciso_assistant({"objects": {}}, "X")
70
71
72def _obs(status, relationship="full"):
73 return Observation("TEST:C1", status, "r", "t", "high", "s", relationship=relationship)
74
75
76def test_partial_mappings_give_partially_supported():
77 cat = catalog.Catalog("TEST", "Test", "1", "complete", "", [catalog.Control("TEST", "C1", "One")])
78 state = lambda obs: coverage.evaluate([cat], obs).frameworks[0].results[0].state
79 assert state([_obs("pass", "partial")]) == coverage.PARTIALLY_SUPPORTED
80 assert state([_obs("pass", "intersects"), _obs("pass", "subset")]) == coverage.PARTIALLY_SUPPORTED
81 assert state([_obs("pass", "partial"), _obs("pass", "full")]) == coverage.SUPPORTED
82 assert state([_obs("pass", "equal"), _obs("fail", "partial")]) == coverage.FAILING
83 report = coverage.evaluate([cat], [_obs("pass", "partial")])
84 assert report.frameworks[0].addressed == 1 and report.frameworks[0].supported == 0
85
86
87def test_report_json_carries_mappings(tmp_path):
88 path = tmp_path / "r.json"
89 path.write_text(json.dumps({"findings": [{"id": "x", "status": "pass", "controls": ["SOC2:CC6.1", "ISO:A.5.17"],
90 "control_mappings": {"ISO:A.5.17": {"relationship": "partial", "rationale": "covers MFA only"}}}]}))
91 obs = {o.control: o for o in load_report(path)}
92 assert obs["SOC2:CC6.1"].relationship == "full"
93 assert (obs["ISO:A.5.17"].relationship, obs["ISO:A.5.17"].mapping) == ("partial", "covers MFA only")
94
95
96def test_bundled_catalogs_still_load():
97 assert yaml.safe_load(importers.to_yaml({"a": 1})) == {"a": 1}
98 assert catalog.load("soc2").license == ""