Commit 3022dae26e
Unsigned
Layout: unified · split
CHANGELOG.md +4
| @@ -6,6 +6,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). | |||
| 6 | 6 | ||
| 7 | ## [Unreleased] | 7 | ## [Unreleased] |
| 8 | 8 | ||
| 9 | ### Added | ||
| 10 | |||
| 11 | - Ruleset `schema: 2`: rules may declare a `timestamp` column and `max_gap_days`; `audit_report.periods.check` reports rows outside a test period, undated rows, and gaps. Schema 1 rulesets are unchanged. | ||
| 12 | |||
| 9 | ### Fixed | 13 | ### Fixed |
| 10 | 14 | ||
| 11 | - CSV rows with fewer cells than the header no longer crash rule evaluation; missing cells load as empty strings. | 15 | - CSV rows with fewer cells than the header no longer crash rule evaluation; missing cells load as empty strings. |
README.md +8
| @@ -149,6 +149,14 @@ rules: | |||
| 149 | | `require_any_row` | Passes only if at least one row satisfies `when`. | | 149 | | `require_any_row` | Passes only if at least one row satisfies `when`. | |
| 150 | | `assert_row` | Checks each condition in `require` against the first row of a single-row config table. | | 150 | | `assert_row` | Checks each condition in `require` against the first row of a single-row config table. | |
| 151 | 151 | ||
| 152 | **Period checks (schema 2)** — a ruleset with `schema: 2` may give a rule a | ||
| 153 | `timestamp` column (ISO date or date-time) and an optional `max_gap_days`. | ||
| 154 | `audit_report.periods.check(rows, column, start, end, max_gap_days)` reports | ||
| 155 | rows dated outside a test period, rows with no readable date, and runs of more | ||
| 156 | than `max_gap_days` days with no rows. Schema 1 rulesets are unchanged and | ||
| 157 | reject these keys. Joins across tables are not part of the rule schema: an | ||
| 158 | analytic produces an ordinary table, and rules evaluate that. | ||
| 159 | |||
| 152 | **Condition language** — a condition is a leaf `{column, op, value}`, or one of | 160 | **Condition language** — a condition is a leaf `{column, op, value}`, or one of |
| 153 | `{all: [...]}`, `{any: [...]}`, `{not: ...}`. Operators: `equals`, `not_equals`, | 161 | `{all: [...]}`, `{any: [...]}`, `{not: ...}`. Operators: `equals`, `not_equals`, |
| 154 | `is_true`, `is_false`, `in`, `not_in`, `gt`, `gte`, `lt`, `lte`, `empty`, | 162 | `is_true`, `is_false`, `in`, `not_in`, `gt`, `gte`, `lt`, `lte`, `empty`, |
audit_report/periods.py added +69
| @@ -0,0 +1,69 @@ | |||
| 1 | """Row-level period checks for rules that declare a timestamp column (ruleset schema 2). | ||
| 2 | |||
| 3 | Evidence for a test period should be dated inside it and should not leave long | ||
| 4 | stretches with no rows (a log that stops for three weeks, a ticket export that | ||
| 5 | skips a month). :func:`check` reports, for one table and one period, which rows | ||
| 6 | fall outside it, which rows have no readable date, and the gaps longer than | ||
| 7 | ``max_gap_days`` between the period start, each dated row, and the period end. | ||
| 8 | |||
| 9 | Multi-table logic (joins across packages) is not part of the rule schema; it | ||
| 10 | is done by analytics whose outputs are ordinary tables that rules evaluate. | ||
| 11 | """ | ||
| 12 | |||
| 13 | from __future__ import annotations | ||
| 14 | |||
| 15 | from dataclasses import dataclass, field | ||
| 16 | from datetime import date, timedelta | ||
| 17 | |||
| 18 | |||
| 19 | @dataclass | ||
| 20 | class PeriodCheck: | ||
| 21 | column: str | ||
| 22 | start: str | ||
| 23 | end: str | ||
| 24 | rows_in_period: int = 0 | ||
| 25 | outside: list[dict] = field(default_factory=list) # {"row": index, "date": value} | ||
| 26 | undated: list[int] = field(default_factory=list) | ||
| 27 | gaps: list[dict] = field(default_factory=list) # {"from", "to", "days"} | ||
| 28 | first: str = "" | ||
| 29 | last: str = "" | ||
| 30 | |||
| 31 | @property | ||
| 32 | def ok(self) -> bool: | ||
| 33 | return not self.outside and not self.undated and not self.gaps | ||
| 34 | |||
| 35 | |||
| 36 | def _date(value: str) -> date | None: | ||
| 37 | text = str(value or "").strip()[:10] | ||
| 38 | try: | ||
| 39 | return date.fromisoformat(text) | ||
| 40 | except ValueError: | ||
| 41 | return None | ||
| 42 | |||
| 43 | |||
| 44 | def check(rows: list[dict], column: str, start: str, end: str, max_gap_days: int | None = None) -> PeriodCheck: | ||
| 45 | """Check that ``rows`` are dated by ``column`` within ``start``..``end`` (inclusive).""" | ||
| 46 | p_start, p_end = date.fromisoformat(start), date.fromisoformat(end) | ||
| 47 | result = PeriodCheck(column=column, start=start, end=end) | ||
| 48 | dated: list[date] = [] | ||
| 49 | for i, row in enumerate(rows): | ||
| 50 | d = _date(row.get(column, "")) | ||
| 51 | if d is None: | ||
| 52 | result.undated.append(i) | ||
| 53 | elif d < p_start or d > p_end: | ||
| 54 | result.outside.append({"row": i, "date": d.isoformat()}) | ||
| 55 | else: | ||
| 56 | dated.append(d) | ||
| 57 | result.rows_in_period = len(dated) | ||
| 58 | if dated: | ||
| 59 | result.first, result.last = min(dated).isoformat(), max(dated).isoformat() | ||
| 60 | if max_gap_days: | ||
| 61 | # Runs of consecutive days in the period with no rows; a sentinel past each edge. | ||
| 62 | prev = p_start - timedelta(days=1) | ||
| 63 | for d in [*sorted(set(dated)), p_end + timedelta(days=1)]: | ||
| 64 | empty = (d - prev).days - 1 | ||
| 65 | if empty > max_gap_days: | ||
| 66 | first_empty, last_empty = prev + timedelta(days=1), d - timedelta(days=1) | ||
| 67 | result.gaps.append({"from": first_empty.isoformat(), "to": last_empty.isoformat(), "days": empty}) | ||
| 68 | prev = d | ||
| 69 | return result | ||
audit_report/rules.py +15
| @@ -46,6 +46,8 @@ class Rule: | |||
| 46 | controls: list[str] = field(default_factory=list) | 46 | controls: list[str] = field(default_factory=list) |
| 47 | rationale: str = "" | 47 | rationale: str = "" |
| 48 | remediation: str = "" | 48 | remediation: str = "" |
| 49 | timestamp: str | None = None # schema 2: the column that dates each row | ||
| 50 | max_gap_days: int | None = None # schema 2: longest allowed run of days with no rows | ||
| 49 | 51 | ||
| 50 | 52 | ||
| 51 | @dataclass | 53 | @dataclass |
| @@ -62,6 +64,7 @@ class Ruleset: | |||
| 62 | name: str = "" | 64 | name: str = "" |
| 63 | version: str = "" | 65 | version: str = "" |
| 64 | sha256: str = "" | 66 | sha256: str = "" |
| 67 | schema: int = 1 | ||
| 65 | 68 | ||
| 66 | 69 | ||
| 67 | def _as_number(value: str) -> float | None: | 70 | def _as_number(value: str) -> float | None: |
| @@ -137,8 +140,17 @@ def load_ruleset(path: str | Path) -> Ruleset: | |||
| 137 | if not platform: | 140 | if not platform: |
| 138 | raise ValueError(f"{path}: ruleset is missing a 'platform'") | 141 | raise ValueError(f"{path}: ruleset is missing a 'platform'") |
| 139 | 142 | ||
| 143 | schema = int(data.get("schema", 1)) | ||
| 144 | if schema not in (1, 2): | ||
| 145 | raise ValueError(f"{path}: unsupported ruleset schema {schema}") | ||
| 146 | |||
| 140 | rules: list[Rule] = [] | 147 | rules: list[Rule] = [] |
| 141 | for entry in data.get("rules", []): | 148 | for entry in data.get("rules", []): |
| 149 | if schema == 1 and ("timestamp" in entry or "max_gap_days" in entry): | ||
| 150 | raise ValueError(f"{path}: rule {entry.get('id')}: 'timestamp' and 'max_gap_days' need 'schema: 2'") | ||
| 151 | gap = entry.get("max_gap_days") | ||
| 152 | if gap is not None and (not isinstance(gap, int) or gap < 1 or "timestamp" not in entry): | ||
| 153 | raise ValueError(f"{path}: rule {entry.get('id')}: max_gap_days must be a positive integer with a timestamp") | ||
| 142 | rule = Rule( | 154 | rule = Rule( |
| 143 | id=entry["id"], | 155 | id=entry["id"], |
| 144 | title=entry["title"], | 156 | title=entry["title"], |
| @@ -148,6 +160,8 @@ def load_ruleset(path: str | Path) -> Ruleset: | |||
| 148 | controls=entry.get("controls", []), | 160 | controls=entry.get("controls", []), |
| 149 | rationale=entry.get("rationale", ""), | 161 | rationale=entry.get("rationale", ""), |
| 150 | remediation=entry.get("remediation", ""), | 162 | remediation=entry.get("remediation", ""), |
| 163 | timestamp=entry.get("timestamp"), | ||
| 164 | max_gap_days=gap, | ||
| 151 | ) | 165 | ) |
| 152 | check_type = rule.check.get("type") | 166 | check_type = rule.check.get("type") |
| 153 | if check_type not in VALID_CHECK_TYPES: | 167 | if check_type not in VALID_CHECK_TYPES: |
| @@ -159,5 +173,6 @@ def load_ruleset(path: str | Path) -> Ruleset: | |||
| 159 | rules=rules, | 173 | rules=rules, |
| 160 | name=data.get("name", platform), | 174 | name=data.get("name", platform), |
| 161 | version=str(data.get("version", "")), | 175 | version=str(data.get("version", "")), |
| 176 | schema=schema, | ||
| 162 | sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(), | 177 | sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(), |
| 163 | ) | 178 | ) |
tests/test_periods.py added +62
| @@ -0,0 +1,62 @@ | |||
| 1 | """Row-level period checks (ruleset schema 2).""" | ||
| 2 | |||
| 3 | from pathlib import Path | ||
| 4 | |||
| 5 | import pytest | ||
| 6 | |||
| 7 | from audit_report import periods | ||
| 8 | from audit_report.rules import load_ruleset | ||
| 9 | |||
| 10 | ROWS = [{"at": "2026-07-01T10:00:00Z"}, {"at": "2026-07-03"}, {"at": "2026-07-20"}, {"at": "2026-06-30"}, {"at": "soon"}] | ||
| 11 | |||
| 12 | |||
| 13 | def test_outside_undated_and_gaps(): | ||
| 14 | res = periods.check(ROWS, "at", "2026-07-01", "2026-07-31", max_gap_days=7) | ||
| 15 | assert res.rows_in_period == 3 | ||
| 16 | assert res.outside == [{"row": 3, "date": "2026-06-30"}] | ||
| 17 | assert res.undated == [4] | ||
| 18 | assert res.first == "2026-07-01" and res.last == "2026-07-20" | ||
| 19 | assert res.gaps == [ | ||
| 20 | {"from": "2026-07-04", "to": "2026-07-19", "days": 16}, | ||
| 21 | {"from": "2026-07-21", "to": "2026-07-31", "days": 11}, | ||
| 22 | ] | ||
| 23 | assert not res.ok | ||
| 24 | |||
| 25 | |||
| 26 | def test_no_gap_limit_and_clean_period(): | ||
| 27 | rows = [{"at": f"2026-07-{d:02d}"} for d in range(1, 32, 3)] | ||
| 28 | assert periods.check(rows, "at", "2026-07-01", "2026-07-31", max_gap_days=2).ok | ||
| 29 | assert periods.check(rows, "at", "2026-07-01", "2026-07-31").gaps == [] | ||
| 30 | empty = periods.check([], "at", "2026-07-01", "2026-07-10", max_gap_days=3) | ||
| 31 | assert empty.gaps == [{"from": "2026-07-01", "to": "2026-07-10", "days": 10}] | ||
| 32 | |||
| 33 | |||
| 34 | def _ruleset(tmp_path: Path, body: str) -> Path: | ||
| 35 | path = tmp_path / "r.yaml" | ||
| 36 | path.write_text(body) | ||
| 37 | return path | ||
| 38 | |||
| 39 | |||
| 40 | RULE = """ | ||
| 41 | rules: | ||
| 42 | - id: x.logs | ||
| 43 | title: Logs present | ||
| 44 | table: events | ||
| 45 | check: {type: fail_if_any_rows, when: {column: level, op: equals, value: error}} | ||
| 46 | timestamp: at | ||
| 47 | max_gap_days: 3 | ||
| 48 | """ | ||
| 49 | |||
| 50 | |||
| 51 | def test_schema_2_fields(tmp_path): | ||
| 52 | rs = load_ruleset(_ruleset(tmp_path, "schema: 2\nplatform: x\n" + RULE)) | ||
| 53 | assert rs.schema == 2 and rs.rules[0].timestamp == "at" and rs.rules[0].max_gap_days == 3 | ||
| 54 | |||
| 55 | |||
| 56 | def test_schema_1_refuses_period_fields(tmp_path): | ||
| 57 | with pytest.raises(ValueError, match="need 'schema: 2'"): | ||
| 58 | load_ruleset(_ruleset(tmp_path, "platform: x\n" + RULE)) | ||
| 59 | with pytest.raises(ValueError, match="unsupported ruleset schema"): | ||
| 60 | load_ruleset(_ruleset(tmp_path, "schema: 3\nplatform: x\nrules: []\n")) | ||
| 61 | with pytest.raises(ValueError, match="positive integer with a timestamp"): | ||
| 62 | load_ruleset(_ruleset(tmp_path, "schema: 2\nplatform: x\n" + RULE.replace("max_gap_days: 3", "max_gap_days: 0"))) | ||