Repository navigation
feat(security): rotate the audit log and verify it incrementally #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,15 @@ | |
| SECURITY_ROOT = Path("90 System") / "Security" | ||
| CLIENTS_FILE = SECURITY_ROOT / "clients.json" | ||
| AUDIT_FILE = Path("90 System") / "Audit" / "security.jsonl" | ||
| # Segmented audit log: when the live file exceeds AUDIT_ROTATE_BYTES it is sealed | ||
| # as a read-only segment and a fresh live file continues the hash chain from the | ||
| # sealed root. Sealed segments are retained (compliance history); the append | ||
| # path verifies only the live tail so it stays O(1) instead of re-reading the | ||
| # whole ledger on every event. | ||
| AUDIT_DIR = AUDIT_FILE.parent | ||
| AUDIT_ROTATE_BYTES = 1_048_576 # 1 MiB | ||
| AUDIT_SEGMENT_FORMAT = "security.{}.jsonl" | ||
| AUDIT_MANIFEST_FILE = AUDIT_DIR / "security-manifest.json" | ||
|
|
||
|
|
||
| def _now() -> str: | ||
|
|
@@ -87,11 +96,18 @@ def _registry_audit_transaction(root: Path): | |
| """Keep a registry mutation and its audit event rollback-consistent.""" | ||
| registry_path, audit_path = root / CLIENTS_FILE, root / AUDIT_FILE | ||
| audit_path.parent.mkdir(parents=True, exist_ok=True) | ||
| with _registry_lock(root), FileLock(root / AUDIT_FILE.parent / "security-audit.lock", timeout=10): | ||
| with _registry_lock(root), FileLock(root / AUDIT_DIR / "security-audit.lock", timeout=10): | ||
| rollback = { | ||
| registry_path: registry_path.read_text(encoding="utf-8") if registry_path.exists() else None, | ||
| audit_path: audit_path.read_text(encoding="utf-8") if audit_path.exists() else None, | ||
| # Seal the manifest and any existing segments too, so a rotation that | ||
| # happens mid-transaction is rolled back to a consistent prior state | ||
| # (the fresh live file is restored and the new segment removed). | ||
| root / AUDIT_MANIFEST_FILE: (root / AUDIT_MANIFEST_FILE).read_text(encoding="utf-8") if (root / AUDIT_MANIFEST_FILE).exists() else None, | ||
| } | ||
| for index in _sealed_segments(root): | ||
| segment = _segment_path(root, index) | ||
| rollback[segment] = segment.read_text(encoding="utf-8") | ||
| journal, transaction = profile.begin_transaction(root, rollback) | ||
| try: | ||
| yield _registry(root), lambda **values: _append_event_unlocked(root, **values) | ||
|
|
@@ -267,14 +283,129 @@ def _canonical_hash(record: dict[str, Any]) -> str: | |
| return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() | ||
|
|
||
|
|
||
| def verify_audit(root: Path) -> dict[str, Any]: | ||
| def _segment_path(root: Path, index: int) -> Path: | ||
| return root / AUDIT_DIR / AUDIT_SEGMENT_FORMAT.format(index) | ||
|
|
||
|
|
||
| def _read_manifest(root: Path) -> dict[str, Any]: | ||
| """Parse the sealed-segment manifest, or a tidy empty shape when absent.""" | ||
| path = root / AUDIT_MANIFEST_FILE | ||
| if not path.is_file(): | ||
| return {"version": 1, "segments": []} | ||
| path = profile.safe_vault_file(root, path) | ||
| try: | ||
| value = json.loads(path.read_text(encoding="utf-8")) | ||
| except json.JSONDecodeError as exc: | ||
| raise RuntimeError("安全审计轮转清单损坏;已停止受保护操作。") from exc | ||
| if not isinstance(value, dict) or not isinstance(value.get("segments"), list): | ||
| raise RuntimeError("安全审计轮转清单格式无效;已停止受保护操作。") | ||
| return value | ||
|
|
||
|
|
||
| def _write_manifest(root: Path, value: dict[str, Any]) -> None: | ||
| profile.atomic_write(root / AUDIT_MANIFEST_FILE, json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n") | ||
|
|
||
|
|
||
| def _sealed_segments(root: Path) -> list[int]: | ||
| """Segment indexes present on disk, ascending (oldest first).""" | ||
| folder = root / AUDIT_DIR | ||
| found: list[int] = [] | ||
| if folder.is_dir(): | ||
| for item in folder.glob(AUDIT_SEGMENT_FORMAT.format("*")): | ||
| try: | ||
| found.append(int(item.stem.split(".")[-1])) | ||
| except (ValueError, IndexError): | ||
| continue | ||
| return sorted(found) | ||
|
|
||
|
|
||
| def _rotate_audit(root: Path) -> dict[str, Any]: | ||
| """Seal the live file as the next segment and start a fresh live file. | ||
|
|
||
| Called with the audit lock held. The manifest records each segment's root | ||
| hash and event count; the live file's first ``prevHash`` links to the last | ||
| sealed root, so the whole ledger stays one continuous hash chain. | ||
| """ | ||
| manifest = _read_manifest(root) | ||
| segments = manifest["segments"] | ||
| live = root / AUDIT_FILE | ||
| count = 0 | ||
| if live.is_file(): | ||
| for line in profile.safe_vault_file(root, live).read_text(encoding="utf-8").splitlines(): | ||
| if line.strip(): | ||
| count += 1 | ||
| index = (segments[-1]["index"] + 1) if segments else 1 | ||
| target = _segment_path(root, index) | ||
| os.replace(live, target) | ||
| segments.append({"index": index, "events": count, "prevHash": segments[-1]["rootHash"] if segments else "", "rootHash": _segment_root(target)}) | ||
| _write_manifest(root, manifest) | ||
|
Comment on lines
+339
to
+341
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make rotation recoverable after the live-file rename. If manifest persistence fails on the first rotation, On retry, the absent manifest and live file look like an empty ledger. Append creates a new chain, and verification reports that chain as verified while ignoring the old segment. Journal the rotation before renaming. Recovery must restore the prior ledger or complete the manifest and live continuation before accepting another event.
|
||
| return manifest | ||
|
|
||
|
|
||
| def _segment_root(path: Path) -> str: | ||
| """Root hash of a segment: the hash of its last record ('' when empty).""" | ||
| last = _tail_hash(path) | ||
| return last or "" | ||
|
|
||
|
|
||
| def _tail_record(path: Path) -> dict[str, Any] | None: | ||
| """Last non-empty record in ``path`` without reading the file whole. | ||
|
|
||
| Reads a bounded window from the end and scans backwards for the final line, | ||
| so the append path stays O(1) regardless of ledger size. | ||
| """ | ||
| if not path.is_file(): | ||
| return None | ||
| with path.open("rb") as handle: | ||
| handle.seek(0, os.SEEK_END) | ||
| size = handle.tell() | ||
| window = min(size, 65_536) | ||
| handle.seek(size - window) | ||
| chunk = handle.read(window) | ||
| lines = [line for line in chunk.decode("utf-8", "replace").splitlines() if line.strip()] | ||
| if not lines: | ||
| return None | ||
| try: | ||
| record = json.loads(lines[-1]) | ||
| except json.JSONDecodeError: | ||
| return None | ||
| return record if isinstance(record, dict) else None | ||
|
|
||
|
|
||
| def _tail_hash(path: Path) -> str: | ||
| """Verified root hash of a segment's last record, or "" when absent/invalid. | ||
|
|
||
| The stored ``hash`` is recomputed from the record's content and checked | ||
| against both the stored value and the chained ``prevHash`` neighbour is left | ||
| to the full verifier; here the point is that a tampered or truncated tail is | ||
| caught cheaply. | ||
| """ | ||
| record = _tail_record(path) | ||
| if record is None: | ||
| return "" | ||
| if not hmac.compare_digest(str(record.get("hash", "")), _canonical_hash(record)): | ||
| return "\0invalid" | ||
| return str(record.get("hash", "")) | ||
|
|
||
|
|
||
| def _verify_live(root: Path, expected_prev: str) -> dict[str, Any]: | ||
| """Verify the live audit file's chain against ``expected_prev``. | ||
|
|
||
| Returns the same shape as ``verify_audit`` for the live file alone | ||
| (``events`` counts live records, ``lastHash`` is the live root). | ||
| """ | ||
| path = root / AUDIT_FILE | ||
| if not path.is_file(): | ||
| return {"status": "missing", "events": 0, "lastHash": ""} | ||
| # A missing live file is "missing" only when nothing was ever sealed; | ||
| # with sealed segments present, its absence is truncation. | ||
| status = "missing" if expected_prev == "" else "invalid" | ||
| return {"status": status, "events": 0, "lastHash": expected_prev if status == "invalid" else ""} | ||
| path = profile.safe_vault_file(root, path) | ||
| previous = "" | ||
| previous = expected_prev | ||
| count = 0 | ||
| for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): | ||
| if not line.strip(): | ||
| continue | ||
| try: | ||
| record = json.loads(line) | ||
| except json.JSONDecodeError: | ||
|
|
@@ -286,33 +417,139 @@ def verify_audit(root: Path) -> dict[str, Any]: | |
| return {"status": "verified", "events": count, "lastHash": previous} | ||
|
|
||
|
|
||
| def verify_audit(root: Path) -> dict[str, Any]: | ||
| """Verify the full audit ledger: every sealed segment, then the live file. | ||
|
|
||
| Segments are immutable and ordered; each one's first ``prevHash`` links to | ||
| the previous root and its final ``hash`` must equal the manifest's recorded | ||
| root. The live file then continues from the last sealed root. The return | ||
| shape is unchanged (``events`` is the total across segments and live). | ||
| """ | ||
| manifest = _read_manifest(root) | ||
| expected_prev = "" | ||
| total = 0 | ||
| # Manifest-declared segments, in order, each verified internally. | ||
| for entry in manifest["segments"]: | ||
| index = entry.get("index") | ||
| if not isinstance(index, int): | ||
| return {"status": "invalid", "events": total, "line": 0, "lastHash": expected_prev} | ||
| path = _segment_path(root, index) | ||
| if not path.is_file(): | ||
| return {"status": "invalid", "events": total, "line": 0, "lastHash": expected_prev} | ||
| previous = entry.get("prevHash", "") | ||
| if previous != expected_prev: | ||
| return {"status": "invalid", "events": total, "line": 0, "lastHash": expected_prev} | ||
| count = 0 | ||
| for number, line in enumerate(profile.safe_vault_file(root, path).read_text(encoding="utf-8").splitlines(), start=1): | ||
| if not line.strip(): | ||
| continue | ||
| try: | ||
| record = json.loads(line) | ||
| except json.JSONDecodeError: | ||
| return {"status": "invalid", "events": total + count, "line": number, "lastHash": previous} | ||
| if record.get("prevHash", "") != previous or not hmac.compare_digest(str(record.get("hash", "")), _canonical_hash(record)): | ||
| return {"status": "invalid", "events": total + count, "line": number, "lastHash": previous} | ||
| previous = record["hash"] | ||
| count += 1 | ||
| if count != entry.get("events") or previous != entry.get("rootHash"): | ||
| return {"status": "invalid", "events": total + count, "line": 0, "lastHash": expected_prev} | ||
| expected_prev = previous | ||
| total += count | ||
| # The live file continues the chain. | ||
| live = _verify_live(root, expected_prev) | ||
| if live["status"] == "invalid": | ||
| live["events"] += total | ||
| return live | ||
| if live["status"] == "missing": | ||
| if expected_prev == "": | ||
| return {"status": "missing", "events": 0, "lastHash": ""} | ||
| return {"status": "invalid", "events": total, "line": 0, "lastHash": expected_prev} | ||
| total += live["events"] | ||
| return {"status": "verified", "events": total, "lastHash": live["lastHash"]} | ||
|
|
||
|
|
||
| def _all_audit_records(root: Path) -> list[dict[str, Any]]: | ||
| """Every audit record, oldest first: sealed segments then the live file.""" | ||
| records: list[dict[str, Any]] = [] | ||
| for index in _sealed_segments(root): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Read the same segments that verification checks.
Read records from the verified manifest sequence. Handle unlisted segments through explicit recovery or integrity checks instead of including them as verified history.
|
||
| path = _segment_path(root, index) | ||
| for line in profile.safe_vault_file(root, path).read_text(encoding="utf-8").splitlines(): | ||
| if line.strip(): | ||
| records.append(json.loads(line)) | ||
| live = root / AUDIT_FILE | ||
| if live.is_file(): | ||
| for line in profile.safe_vault_file(root, live).read_text(encoding="utf-8").splitlines(): | ||
| if line.strip(): | ||
| records.append(json.loads(line)) | ||
| return records | ||
|
|
||
|
|
||
| def _append_event_unlocked(root: Path, *, client_id: str, event_type: str, resource_type: str, scope: str, result: str, reason_code: str, correlation_id: str | None = None, details: dict[str, Any] | None = None) -> dict[str, Any]: | ||
| if result not in {"allowed", "denied"}: | ||
| raise RuntimeError("审计结果无效。") | ||
| safe_details = details or {} | ||
| forbidden = {"token", "password", "secret", "apiKey", "content", "body", "vaultPath"} | ||
| if forbidden.intersection(safe_details): | ||
| raise RuntimeError("审计详情包含禁止字段。") | ||
| folder = root / AUDIT_FILE.parent | ||
| folder = root / AUDIT_DIR | ||
| folder.mkdir(parents=True, exist_ok=True) | ||
| integrity = verify_audit(root) | ||
| if integrity["status"] == "invalid": | ||
| manifest = _read_manifest(root) | ||
| # Cheap sealed-segment guard: each segment's tail hash must still equal the | ||
| # root recorded in the manifest. O(number of segments), never a full re-read, | ||
| # so appends stay fast while a tampered or truncated sealed segment fails closed. | ||
| for entry in manifest["segments"]: | ||
| index = entry.get("index") | ||
| if not isinstance(index, int): | ||
| raise RuntimeError("安全审计轮转清单损坏;已停止受保护操作。") | ||
| segment = _segment_path(root, index) | ||
| if not segment.is_file() or _tail_hash(segment) != entry.get("rootHash"): | ||
| raise RuntimeError("安全审计链完整性失败;已停止受保护操作。") | ||
|
Comment on lines
+505
to
+506
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. An unchanged tail does not establish segment integrity. If an interior record changes but the final record stays unchanged, this guard accepts the segment. Append then succeeds although Preserve the fail-closed requirement for interior changes as well as tail changes. Tail validation alone cannot provide that guarantee. Based on learnings, audit integrity failures must block protected operations.
|
||
| expected_prev = manifest["segments"][-1]["rootHash"] if manifest["segments"] else "" | ||
| live = root / AUDIT_FILE | ||
| # O(1) integrity guard on the live tail (bounded backwards read, not a full re-read). | ||
| tail = _tail_hash(live) if live.is_file() else "" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject an invalid live tail before appending. If the last live record changes without a matching hash update, Reject the invalid-tail result before rotation or append. Keep valid tails eligible for append. Based on learnings, audit integrity failures must block protected operations.
|
||
| if live.is_file() and _live_first_prev(live) != expected_prev: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject a missing live file when sealed history exists. If Reject this state before writing, or recover it through a validated rotation journal. Preserve initial creation when no sealed history exists.
|
||
| raise RuntimeError("安全审计链完整性失败;已停止受保护操作。") | ||
| # Rotate before appending when the live file has grown past the threshold. | ||
| rotated = False | ||
| if live.is_file() and live.stat().st_size >= AUDIT_ROTATE_BYTES: | ||
| manifest = _rotate_audit(root) | ||
| expected_prev = manifest["segments"][-1]["rootHash"] | ||
| tail = "" | ||
| rotated = True | ||
| # After a rotation the live file no longer exists, so the new first record | ||
| # links to the freshly sealed root; otherwise it links to the live tail. | ||
| previous = expected_prev if rotated else tail | ||
| record = { | ||
| "eventId": f"evt-{uuid.uuid4().hex}", "timestamp": _now(), "clientId": profile.clean_meta(client_id, 64) or "unknown", | ||
| "eventType": profile.clean_meta(event_type, 80), "resourceType": profile.clean_meta(resource_type, 80), | ||
| "scope": profile.clean_meta(scope, 80), "result": result, "reasonCode": profile.clean_meta(reason_code, 80), | ||
| "correlationId": correlation_id or f"corr-{uuid.uuid4().hex}", "details": safe_details, | ||
| "prevHash": integrity.get("lastHash", ""), | ||
| "prevHash": previous, | ||
| } | ||
| record["hash"] = _canonical_hash(record) | ||
| with (root / AUDIT_FILE).open("ab") as handle: | ||
| with live.open("ab") as handle: | ||
| handle.write((json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")) | ||
| handle.flush() | ||
| os.fsync(handle.fileno()) | ||
| return record | ||
|
|
||
|
|
||
| def _live_first_prev(path: Path) -> str: | ||
| """``prevHash`` of the first record in the live file ('' when empty).""" | ||
| if not path.is_file(): | ||
| return "" | ||
| with path.open("rb") as handle: | ||
| chunk = handle.read(65_536).decode("utf-8", "replace") | ||
| for line in chunk.splitlines(): | ||
| if line.strip(): | ||
| try: | ||
| return str(json.loads(line).get("prevHash", "")) | ||
| except json.JSONDecodeError: | ||
| return "" | ||
| return "" | ||
|
|
||
|
|
||
| def append_event(root: Path, **values: Any) -> dict[str, Any]: | ||
| folder = root / AUDIT_FILE.parent | ||
| folder.mkdir(parents=True, exist_ok=True) | ||
|
|
@@ -364,24 +601,21 @@ def query_events(root: Path, *, client_id: str = "", event_type: str = "", resou | |
| integrity = verify_audit(root) | ||
| if integrity["status"] == "invalid": | ||
| return {"items": [], "page": page, "pageSize": page_size, "total": 0, "integrity": integrity} | ||
| path = root / AUDIT_FILE | ||
| records = [] | ||
| if path.is_file(): | ||
| for line in profile.safe_vault_file(root, path).read_text(encoding="utf-8").splitlines(): | ||
| record = json.loads(line) | ||
| if client_id and record["clientId"] != client_id: | ||
| continue | ||
| if event_type and record["eventType"] != event_type: | ||
| continue | ||
| if resource_type and record["resourceType"] != resource_type: | ||
| continue | ||
| if result and record["result"] != result: | ||
| continue | ||
| if since and record["timestamp"] < since: | ||
| continue | ||
| if until and record["timestamp"] > until: | ||
| continue | ||
| records.append({key: value for key, value in record.items() if key not in {"hash", "prevHash"}}) | ||
| for record in _all_audit_records(root): | ||
| if client_id and record["clientId"] != client_id: | ||
| continue | ||
| if event_type and record["eventType"] != event_type: | ||
| continue | ||
| if resource_type and record["resourceType"] != resource_type: | ||
| continue | ||
| if result and record["result"] != result: | ||
| continue | ||
| if since and record["timestamp"] < since: | ||
| continue | ||
| if until and record["timestamp"] > until: | ||
| continue | ||
| records.append({key: value for key, value in record.items() if key not in {"hash", "prevHash"}}) | ||
| records.reverse() | ||
| page = max(1, page) | ||
| page_size = max(1, min(page_size, 100)) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rolled-back registry transactions can leave duplicate audit events.
If a registry transaction rotates the live audit file and then fails, recovery restores the pre-rotation live file and manifest. It does not remove the segment created by the rotation.
query_eventsanddiagnosticsread everysecurity.N.jsonlfile on disk, so the orphan segment returns the same events a second time until the next rotation overwrites it. Add the segment path that rotation would create to the snapshot asNone. Recovery then deletes it on rollback.Suggested fix
Committable suggestion