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/

Commit b1b600f8f6

b1b600f8f6bcdc7681b771b10a40c5c2d11000b5

parent: 54df1e9127

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-29 20:50 UTC

Ruleset schema 2: timestamp columns and period checks

- Ruleset `schema: 2`: a rule may declare `timestamp` (the column that dates each row) and `max_gap_days`. Schema 1 rulesets are unchanged and reject these keys; other schema numbers are refused.
- `audit_report.periods.check(rows, column, start, end, max_gap_days)`: rows in the period, rows dated outside it, undated rows, first and last date, and runs of more than `max_gap_days` days with no rows (period edges included).
- Multi-table logic stays out of the rule schema: analytics produce ordinary tables that rules evaluate (audit-workbench roadmap 3.1).
- Needed by audit-workbench roadmap 2.6.
- Tests: 65 passed (4 new).

Layout: unified · split

CHANGELOG.md +4
@@ -6,6 +6,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66
77## [Unreleased]
88
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
913### Fixed
1014
1115- 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:
149149| `require_any_row` | Passes only if at least one row satisfies `when`. |
150150| `assert_row` | Checks each condition in `require` against the first row of a single-row config table. |
151151
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
155rows dated outside a test period, rows with no readable date, and runs of more
156than `max_gap_days` days with no rows. Schema 1 rulesets are unchanged and
157reject these keys. Joins across tables are not part of the rule schema: an
158analytic produces an ordinary table, and rules evaluate that.
159
152160**Condition language** — a condition is a leaf `{column, op, value}`, or one of
153161`{all: [...]}`, `{any: [...]}`, `{not: ...}`. Operators: `equals`, `not_equals`,
154162`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
3Evidence for a test period should be dated inside it and should not leave long
4stretches with no rows (a log that stops for three weeks, a ticket export that
5skips a month). :func:`check` reports, for one table and one period, which rows
6fall 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
9Multi-table logic (joins across packages) is not part of the rule schema; it
10is done by analytics whose outputs are ordinary tables that rules evaluate.
11"""
12
13from __future__ import annotations
14
15from dataclasses import dataclass, field
16from datetime import date, timedelta
17
18
19@dataclass
20class 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
36def _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
44def 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:
4646 controls: list[str] = field(default_factory=list)
4747 rationale: str = ""
4848 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
4951
5052
5153@dataclass
@@ -62,6 +64,7 @@ class Ruleset:
6264 name: str = ""
6365 version: str = ""
6466 sha256: str = ""
67 schema: int = 1
6568
6669
6770def _as_number(value: str) -> float | None:
@@ -137,8 +140,17 @@ def load_ruleset(path: str | Path) -> Ruleset:
137140 if not platform:
138141 raise ValueError(f"{path}: ruleset is missing a 'platform'")
139142
143 schema = int(data.get("schema", 1))
144 if schema not in (1, 2):
145 raise ValueError(f"{path}: unsupported ruleset schema {schema}")
146
140147 rules: list[Rule] = []
141148 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")
142154 rule = Rule(
143155 id=entry["id"],
144156 title=entry["title"],
@@ -148,6 +160,8 @@ def load_ruleset(path: str | Path) -> Ruleset:
148160 controls=entry.get("controls", []),
149161 rationale=entry.get("rationale", ""),
150162 remediation=entry.get("remediation", ""),
163 timestamp=entry.get("timestamp"),
164 max_gap_days=gap,
151165 )
152166 check_type = rule.check.get("type")
153167 if check_type not in VALID_CHECK_TYPES:
@@ -159,5 +173,6 @@ def load_ruleset(path: str | Path) -> Ruleset:
159173 rules=rules,
160174 name=data.get("name", platform),
161175 version=str(data.get("version", "")),
176 schema=schema,
162177 sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(),
163178 )
tests/test_periods.py added +62
@@ -0,0 +1,62 @@
1"""Row-level period checks (ruleset schema 2)."""
2
3from pathlib import Path
4
5import pytest
6
7from audit_report import periods
8from audit_report.rules import load_ruleset
9
10ROWS = [{"at": "2026-07-01T10:00:00Z"}, {"at": "2026-07-03"}, {"at": "2026-07-20"}, {"at": "2026-06-30"}, {"at": "soon"}]
11
12
13def 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
26def 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
34def _ruleset(tmp_path: Path, body: str) -> Path:
35 path = tmp_path / "r.yaml"
36 path.write_text(body)
37 return path
38
39
40RULE = """
41rules:
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
51def 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
56def 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")))