audit-labs/audit-report

Turn audit-tools evidence packages into control-mapped, auditor-ready reports. audit compliance evidence reporting https://audit-labs.dev/audit-report/

audit_report/rules.py

5efcd1ab7ea396a5c196764c32dff4231d1d8bb2
audit-report/audit_report/rules.py history · blame · raw

207 lines · 7087 bytes

8 symbols in this file
  1"""Rule model and the small condition language rulesets are written in.
  2
  3A **ruleset** is a YAML file: a platform name plus a list of rules. Each rule
  4names a table, a check, the controls it maps to, and human text. Checks are
  5evaluated by :mod:`audit_report.engine`.
  6
  7The condition language is intentionally tiny. A *condition* is one of:
  8
  9* a leaf ``{column, op, value}`` — test one column of a row
 10* ``{all: [cond, ...]}`` — every sub-condition holds
 11* ``{any: [cond, ...]}`` — at least one holds
 12* ``{not: cond}`` — the sub-condition does not hold
 13
 14Operators (``op``): ``equals``, ``not_equals``, ``is_true``, ``is_false``,
 15``in``, ``not_in``, ``gt``, ``gte``, ``lt``, ``lte``, ``empty``, ``not_empty``.
 16"""
 17
 18from __future__ import annotations
 19
 20import hashlib
 21from dataclasses import dataclass, field
 22from pathlib import Path
 23
 24import yaml
 25
 26_TRUTHY = {"true", "yes", "1", "y", "t", "enabled", "on"}
 27_FALSY = {"false", "no", "0", "n", "f", "disabled", "off", ""}
 28
 29RELATIONSHIPS = {"full", "partial"}
 30
 31
 32def _controls(entry: dict, path) -> tuple[list[str], dict[str, dict]]:
 33    """A rule's `controls`: plain codes, or `{control, relationship, rationale, source}` mappings."""
 34    codes: list[str] = []
 35    mappings: dict[str, dict] = {}
 36    for item in entry.get("controls", []) or []:
 37        if isinstance(item, str):
 38            codes.append(item)
 39            continue
 40        if not isinstance(item, dict) or not item.get("control"):
 41            raise ValueError(f"{path}: rule {entry.get('id')}: a control mapping needs 'control'")
 42        relationship = str(item.get("relationship", "full"))
 43        if relationship not in RELATIONSHIPS:
 44            raise ValueError(f"{path}: rule {entry.get('id')}: relationship must be full or partial")
 45        code = str(item["control"])
 46        codes.append(code)
 47        mappings[code] = {
 48            "relationship": relationship,
 49            "rationale": str(item.get("rationale", "")),
 50            "source": str(item.get("source", "")),
 51        }
 52    return codes, mappings
 53
 54
 55VALID_CHECK_TYPES = {
 56    "fail_rows_where",
 57    "fail_if_any_rows",
 58    "assert_row",
 59    "require_any_row",
 60}
 61
 62
 63@dataclass
 64class Rule:
 65    """A single control check declared in a ruleset."""
 66
 67    id: str
 68    title: str
 69    table: str
 70    check: dict
 71    severity: str = "medium"
 72    controls: list[str] = field(default_factory=list)
 73    rationale: str = ""
 74    remediation: str = ""
 75    control_mappings: dict[str, dict] = field(default_factory=dict)  # code -> relationship, rationale, source
 76    timestamp: str | None = None  # schema 2: the column that dates each row
 77    max_gap_days: int | None = None  # schema 2: longest allowed run of days with no rows
 78
 79
 80@dataclass
 81class Ruleset:
 82    """A named collection of rules for one platform.
 83
 84    ``version`` and ``sha256`` identify *which* ruleset produced a report, so an
 85    auditor can re-perform against the exact mapping used. ``sha256`` is the
 86    digest of the ruleset file's bytes as loaded.
 87    """
 88
 89    platform: str
 90    rules: list[Rule]
 91    name: str = ""
 92    version: str = ""
 93    sha256: str = ""
 94    schema: int = 1
 95
 96
 97def _as_number(value: str) -> float | None:
 98    try:
 99        return float(value)
100    except (TypeError, ValueError):
101        return None
102
103
104def _compare_numeric(op: str, raw: str, value) -> bool:
105    left, right = _as_number(raw), _as_number(str(value))
106    if left is None or right is None:
107        return False
108    return {
109        "gt": left > right,
110        "gte": left >= right,
111        "lt": left < right,
112        "lte": left <= right,
113    }[op]
114
115
116def _match_leaf(condition: dict, row: dict[str, str]) -> bool:
117    column = condition.get("column")
118    op = condition.get("op")
119    if column is None or op is None:
120        raise ValueError(f"malformed condition: {condition!r}")
121
122    raw = row.get(column, "")
123    value = condition.get("value")
124    norm = raw.strip().lower()
125
126    if op == "equals":
127        return norm == str(value).strip().lower()
128    if op == "not_equals":
129        return norm != str(value).strip().lower()
130    if op == "is_true":
131        return norm in _TRUTHY
132    if op == "is_false":
133        return norm in _FALSY
134    if op == "empty":
135        return raw.strip() == ""
136    if op == "not_empty":
137        return raw.strip() != ""
138    if op in ("in", "not_in"):
139        choices = {str(v).strip().lower() for v in (value or [])}
140        return (norm in choices) if op == "in" else (norm not in choices)
141    if op in ("gt", "gte", "lt", "lte"):
142        return _compare_numeric(op, raw, value)
143
144    raise ValueError(f"unknown operator: {op!r}")
145
146
147def match(condition: dict, row: dict[str, str]) -> bool:
148    """Return True if *condition* holds for *row*.
149
150    Raises ``ValueError`` on a malformed condition so ruleset bugs surface
151    loudly rather than silently evaluating to False.
152    """
153    if "all" in condition:
154        return all(match(c, row) for c in condition["all"])
155    if "any" in condition:
156        return any(match(c, row) for c in condition["any"])
157    if "not" in condition:
158        return not match(condition["not"], row)
159    return _match_leaf(condition, row)
160
161
162def load_ruleset(path: str | Path) -> Ruleset:
163    """Parse a ruleset YAML file into a :class:`Ruleset`, validating each rule."""
164    text = Path(path).read_text(encoding="utf-8")
165    data = yaml.safe_load(text) or {}
166    platform = data.get("platform")
167    if not platform:
168        raise ValueError(f"{path}: ruleset is missing a 'platform'")
169
170    schema = int(data.get("schema", 1))
171    if schema not in (1, 2):
172        raise ValueError(f"{path}: unsupported ruleset schema {schema}")
173
174    rules: list[Rule] = []
175    for entry in data.get("rules", []):
176        if schema == 1 and ("timestamp" in entry or "max_gap_days" in entry):
177            raise ValueError(f"{path}: rule {entry.get('id')}: 'timestamp' and 'max_gap_days' need 'schema: 2'")
178        codes, mappings = _controls(entry, path)
179        gap = entry.get("max_gap_days")
180        if gap is not None and (not isinstance(gap, int) or gap < 1 or "timestamp" not in entry):
181            raise ValueError(f"{path}: rule {entry.get('id')}: max_gap_days must be a positive integer with a timestamp")
182        rule = Rule(
183            id=entry["id"],
184            title=entry["title"],
185            table=entry["table"],
186            check=entry["check"],
187            severity=entry.get("severity", "medium"),
188            controls=codes,
189            control_mappings=mappings,
190            rationale=entry.get("rationale", ""),
191            remediation=entry.get("remediation", ""),
192            timestamp=entry.get("timestamp"),
193            max_gap_days=gap,
194        )
195        check_type = rule.check.get("type")
196        if check_type not in VALID_CHECK_TYPES:
197            raise ValueError(f"{rule.id}: unknown check type {check_type!r}")
198        rules.append(rule)
199
200    return Ruleset(
201        platform=platform,
202        rules=rules,
203        name=data.get("name", platform),
204        version=str(data.get("version", "")),
205        schema=schema,
206        sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(),
207    )