diff --git a/apps/web/e2e/monthly-reflection.spec.ts b/apps/web/e2e/monthly-reflection.spec.ts index 4a95cc5..bddb506 100644 --- a/apps/web/e2e/monthly-reflection.spec.ts +++ b/apps/web/e2e/monthly-reflection.spec.ts @@ -38,15 +38,25 @@ test('Monthly Reflection persists dimensions, events, goals, summary and confirm await expect(page.getByText('100%')).toBeVisible() await page.screenshot({ path: resolve(shots, 'monthly-reflection-filled.png'), fullPage: true }) + // 事件日期必须属于该复盘的月份:后端拒绝跨月事件(重要事件必须属于当前复盘月份)。 + // App 用 overview.currentMonth 创建/显示当前真实月份,所以这里也从界面读取当前月份, + // 而不是写死某个月份——否则测试在“当前月”变化后必然失败。 + const currentMonth = (await page.locator('.monthly-command').getByText(/^\d{4}-\d{2}$/).first().textContent())?.trim() ?? '' + expect(currentMonth).toMatch(/^\d{4}-\d{2}$/) await page.getByRole('button', { name: 'Events' }).click() await page.getByLabel('事件标题').fill('完成 Phase 6') - await page.getByLabel('事件日期').fill('2026-11-03') + await page.getByLabel('事件日期').fill(`${currentMonth}-03`) await page.getByLabel('事件所属维度').selectOption('vocation') await page.getByLabel('事件描述').fill('完成真实的本地月度复盘闭环。') await page.getByLabel('个人感受').fill('踏实') await page.getByLabel('关联项目').fill('Personal AI Profile') - await page.getByRole('button', { name: '添加事件' }).click() - await expect(page.getByText('完成 Phase 6')).toBeVisible() + // 等待添加事件的 POST 返回再断言:点击是异步的,立即断言会竞态(事件尚未进入列表、输入框已清空)。 + const [eventResponse] = await Promise.all([ + page.waitForResponse((response) => response.url().includes('/events') && response.request().method() === 'POST'), + page.getByRole('button', { name: '添加事件' }).click(), + ]) + expect(eventResponse.ok()).toBeTruthy() + await expect(page.getByText('完成 Phase 6')).toBeVisible({ timeout: 15_000 }) await page.getByRole('button', { name: 'Goals' }).click() await page.getByRole('button', { name: '添加目标' }).click() await page.locator('input[aria-label="目标 1"]').fill('完成下一阶段') diff --git a/core/security.py b/core/security.py index c17ddb0..3bae851 100644 --- a/core/security.py +++ b/core/security.py @@ -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) + 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,6 +417,73 @@ 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): + 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("审计结果无效。") @@ -293,26 +491,65 @@ def _append_event_unlocked(root: Path, *, client_id: str, event_type: str, resou 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("安全审计链完整性失败;已停止受保护操作。") + 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 "" + if live.is_file() and _live_first_prev(live) != expected_prev: 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)) diff --git a/tests/test_audit_rotation.py b/tests/test_audit_rotation.py new file mode 100644 index 0000000..5ea831d --- /dev/null +++ b/tests/test_audit_rotation.py @@ -0,0 +1,85 @@ +"""Tests for segmented audit-log rotation (core.security). + +Rotation must keep the ledger one continuous hash chain across sealed segments +and the live file, and must stay tamper-evident on both. The threshold is +lowered for the test so a handful of events trigger a seal; behaviour below the +threshold is unchanged (single live file, no manifest). +""" + +import json +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parents[1])) + +from core import profile, security + + +def _append_many(root: Path, count: int) -> None: + for index in range(count): + security.append_event( + root, client_id=f"c{index}", event_type="test.event", resource_type="test", + scope="profile:read", result="allowed", reason_code="TEST", + ) + + +def main() -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "vault" + profile.init(str(root)) + + # Below the threshold: the original single-file behaviour is unchanged. + _append_many(root, 3) + assert not (root / security.AUDIT_MANIFEST_FILE).exists() + assert not list((root / security.AUDIT_DIR).glob("security.*.jsonl")) + integrity = security.verify_audit(root) + assert integrity["status"] == "verified" and integrity["events"] == 3 + + # Lower the threshold so more events force at least one seal. + original = security.AUDIT_ROTATE_BYTES + security.AUDIT_ROTATE_BYTES = 300 + try: + _append_many(root, 20) + finally: + security.AUDIT_ROTATE_BYTES = original + + segments = sorted((root / security.AUDIT_DIR).glob(security.AUDIT_SEGMENT_FORMAT.format("*"))) + assert segments, "expected at least one sealed segment" + assert (root / security.AUDIT_MANIFEST_FILE).is_file() + manifest = json.loads((root / security.AUDIT_MANIFEST_FILE).read_text(encoding="utf-8")) + assert len(manifest["segments"]) == len(segments) + + # The whole ledger still verifies as one chain, with every event counted. + integrity = security.verify_audit(root) + assert integrity["status"] == "verified", integrity + assert integrity["events"] == 23, integrity + query = security.query_events(root, page_size=1000) + assert query["total"] == 23 and len(query["items"]) == 23 + + # The live file links to the last sealed root (chain continuity). + live_prev = security._live_first_prev(root / security.AUDIT_FILE) + assert live_prev == manifest["segments"][-1]["rootHash"] + + # Tampering with a sealed segment's last record changes its root hash: + # the append guard detects the root mismatch and fails closed, and the + # full verify flags the whole ledger invalid. + target = segments[-1] + lines = target.read_text(encoding="utf-8").splitlines() + record = json.loads(lines[-1]) + record["reasonCode"] = "TAMPERED" + lines[-1] = json.dumps(record, ensure_ascii=False) + target.write_text("\n".join(lines) + "\n", encoding="utf-8") + assert security.verify_audit(root)["status"] == "invalid" + assert security.query_events(root, page_size=10)["total"] == 0 + try: + security.append_event(root, client_id="x", event_type="test.event", resource_type="test", scope="profile:read", result="allowed", reason_code="TEST") + raise AssertionError("tampered audit must block protected writes") + except RuntimeError: + pass + + print("audit rotation tests passed") + + +if __name__ == "__main__": + main()