Repository navigation
feat(security): add tamper-evident audit chain logger - #892
gemini2026 wants to merge 7 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a tamper‑evident append‑only JSONL audit chain: new AuditLogger that resumes state, SHA‑256 chained entries, verification and query helpers (verifyChain, exportEntries, tailEntries), plus tests and reference documentation. Changes
sequenceDiagram
autonumber
participant Client as Client
participant Logger as AuditLogger
participant FS as FileSystem
participant Verifier as verifyChain
Client->>Logger: log(type, data)
Logger->>FS: append JSONL entry (seq, chain_id, prev_hash, entry_hash, ...)
FS-->>Logger: write ack
Client->>Verifier: verifyChain(path)
Verifier->>FS: read JSONL lines
FS-->>Verifier: return lines
Verifier->>Verifier: parse lines, validate seq, chain_id, prev_hash, recompute entry_hash
Verifier-->>Client: VerifyResult (valid / error, entries)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
docs/reference/audit-chain.md (3)
39-40: One sentence per line.Lines 39–40 contain two sentences on the same line.
Split them for cleaner diffs.The `chain_id` is a random 24-character hex string generated when the logger creates a new file. It remains constant across all entries in a single chain and persists when the logger resumes from an existing file.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/audit-chain.md` around lines 39 - 40, The line describing `chain_id` currently contains two sentences on the same line—split it into two separate lines so each sentence is its own line: one line stating "The `chain_id` is a random 24-character hex string generated when the logger creates a new file." and the next line stating "It remains constant across all entries in a single chain and persists when the logger resumes from an existing file." so diffs are clean.
85-86: One sentence per line.Multiple sentences appear on a single line here.
Split each sentence onto its own line for readable diffs.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/audit-chain.md` around lines 85 - 86, The documentation line describing the constructor currently contains multiple sentences on one line; split each sentence into its own line so diffs are readable—e.g., separate "The constructor creates parent directories if they do not exist." and "If the file already contains entries, the logger resumes the chain from the last entry." into two lines under the constructor documentation.
113-114: One sentence per line.Lines 113–114 and 119–120 each have two sentences on the same line.
Split them for cleaner diffs.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/audit-chain.md` around lines 113 - 114, Split the two combined-sentence lines so each sentence is on its own line: change the line that currently contains "When `limit` is omitted or zero, all matching entries are returned. Malformed lines are silently skipped." into two lines ("When `limit` is omitted or zero, all matching entries are returned." and "Malformed lines are silently skipped.") and do the same for the other occurrence around lines 119–120; ensure each sentence is a separate line to keep diffs clean.nemoclaw/src/security/audit-chain.test.ts (1)
558-578: Test name "concurrent writes" is misleading.This test performs rapid sequential writes from a single thread, not concurrent writes from multiple threads.
SinceappendFileSyncis synchronous, the writes are serialized.
Consider renaming to"rapid sequential writes"or similar to accurately reflect what's being tested.True concurrency testing would require multiple worker threads writing simultaneously.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw/src/security/audit-chain.test.ts` around lines 558 - 578, The test title "concurrent writes" is misleading because it performs serialized writes using AuditLogger (which uses appendFileSync); rename the describe or it block to accurately reflect the behavior (e.g., change describe("concurrent writes") or it("handles rapid sequential writes without data loss") to "rapid sequential writes" or similar) so the test name matches the implementation, referencing the AuditLogger, appendFileSync, readEntries, and verifyChain symbols to locate the test to update.nemoclaw/src/security/audit-chain.ts (2)
346-350: Consider a structured logging approach instead ofconsole.error.Using
console.errorduringreadTailStatecan produce unexpected output in production or library consumers.
Options:
- Return a diagnostic in the
TailStateresult for the caller to handle.- Accept an optional logger callback.
- Silently skip (current behavior minus the log).
Given this is a security module where malformed lines could indicate tampering, silent skipping may be appropriate since
verifyChainhandles detection separately.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw/src/security/audit-chain.ts` around lines 346 - 350, The console.error in readTailState should be removed and replaced with a structured diagnostic approach: update the readTailState signature to either accept an optional logger callback (e.g., logger?: (level: string, msg: string, meta?: any) => void) or add a diagnostic field on the returned TailState (e.g., diagnostics: Array<{line: string, error: string}>), then use that mechanism instead of console.error when skipping a malformed line; ensure callers (or verifyChain) can inspect diagnostics if needed and that default behavior remains silent if no logger is provided.
110-113: No file locking for multi-process writes.
appendFileSyncprovides atomicity at the OS level for small writes, but concurrent appends from multiple processes can interleave or corrupt entries on some platforms.If multi-process logging is a future requirement, consider:
- Advisory file locking (
flockequivalent)- A separate log aggregator process
- A database-backed alternative
For single-process use as currently tested, this is fine.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw/src/security/audit-chain.ts` around lines 110 - 113, The current append in AuditChain.write (appendFileSync(this.path, ...)) can interleave or corrupt when multiple processes write; replace the direct append with a multi-process-safe approach such as acquiring an advisory lock before writing (e.g., flock via a native binding or fs-ext's flockSync), or implement a dedicated log-writer/aggregator process or DB-backed store; ensure the code acquires the lock on this.path (or on a separate .lock file), performs the append of JSON.stringify(entry)+"\n", updates this.seq and this.prevHash only after a successful write, and always releases the lock even on error.docs/reference/injection-scanner.md (1)
23-25: One sentence per line.Lines 23-24 contain multiple sentences on single lines. Per coding guidelines, each sentence should be on its own line to make diffs readable.
The injection scanner detects prompt injection patterns in agent tool inputs and outputs. -It applies text normalization and pattern matching to identify attempts to override system prompts, inject instructions, manipulate tools, or exfiltrate data. +It applies text normalization and pattern matching to identify attempts to override system prompts, inject instructions, manipulate tools, or exfiltrate data.(The second sentence is already on its own line, but verify the source has one sentence per line throughout.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/reference/injection-scanner.md` around lines 23 - 25, The two sentences in the README paragraph should be split so each sentence is on its own line: replace the single line containing "The injection scanner detects prompt injection patterns in agent tool inputs and outputs. It applies text normalization and pattern matching to identify attempts to override system prompts, inject instructions, manipulate tools, or exfiltrate data." with two lines — one containing "The injection scanner detects prompt injection patterns in agent tool inputs and outputs." and a second containing "It applies text normalization and pattern matching to identify attempts to override system prompts, inject instructions, manipulate tools, or exfiltrate data."; also scan the rest of the document to ensure every sentence follows the one-sentence-per-line guideline.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/reference/injection-scanner.md`:
- Around line 113-115: The documentation for maxSeverity incorrectly states its
return type as `Severity | ""`; update the doc to match the implementation and
tests by changing the return type to `Severity | null` and the description to
say it returns null for an empty findings array; reference the maxSeverity
function and the existing test that asserts null to ensure consistency.
---
Nitpick comments:
In `@docs/reference/audit-chain.md`:
- Around line 39-40: The line describing `chain_id` currently contains two
sentences on the same line—split it into two separate lines so each sentence is
its own line: one line stating "The `chain_id` is a random 24-character hex
string generated when the logger creates a new file." and the next line stating
"It remains constant across all entries in a single chain and persists when the
logger resumes from an existing file." so diffs are clean.
- Around line 85-86: The documentation line describing the constructor currently
contains multiple sentences on one line; split each sentence into its own line
so diffs are readable—e.g., separate "The constructor creates parent directories
if they do not exist." and "If the file already contains entries, the logger
resumes the chain from the last entry." into two lines under the constructor
documentation.
- Around line 113-114: Split the two combined-sentence lines so each sentence is
on its own line: change the line that currently contains "When `limit` is
omitted or zero, all matching entries are returned. Malformed lines are silently
skipped." into two lines ("When `limit` is omitted or zero, all matching entries
are returned." and "Malformed lines are silently skipped.") and do the same for
the other occurrence around lines 119–120; ensure each sentence is a separate
line to keep diffs clean.
In `@docs/reference/injection-scanner.md`:
- Around line 23-25: The two sentences in the README paragraph should be split
so each sentence is on its own line: replace the single line containing "The
injection scanner detects prompt injection patterns in agent tool inputs and
outputs. It applies text normalization and pattern matching to identify attempts
to override system prompts, inject instructions, manipulate tools, or exfiltrate
data." with two lines — one containing "The injection scanner detects prompt
injection patterns in agent tool inputs and outputs." and a second containing
"It applies text normalization and pattern matching to identify attempts to
override system prompts, inject instructions, manipulate tools, or exfiltrate
data."; also scan the rest of the document to ensure every sentence follows the
one-sentence-per-line guideline.
In `@nemoclaw/src/security/audit-chain.test.ts`:
- Around line 558-578: The test title "concurrent writes" is misleading because
it performs serialized writes using AuditLogger (which uses appendFileSync);
rename the describe or it block to accurately reflect the behavior (e.g., change
describe("concurrent writes") or it("handles rapid sequential writes without
data loss") to "rapid sequential writes" or similar) so the test name matches
the implementation, referencing the AuditLogger, appendFileSync, readEntries,
and verifyChain symbols to locate the test to update.
In `@nemoclaw/src/security/audit-chain.ts`:
- Around line 346-350: The console.error in readTailState should be removed and
replaced with a structured diagnostic approach: update the readTailState
signature to either accept an optional logger callback (e.g., logger?: (level:
string, msg: string, meta?: any) => void) or add a diagnostic field on the
returned TailState (e.g., diagnostics: Array<{line: string, error: string}>),
then use that mechanism instead of console.error when skipping a malformed line;
ensure callers (or verifyChain) can inspect diagnostics if needed and that
default behavior remains silent if no logger is provided.
- Around line 110-113: The current append in AuditChain.write
(appendFileSync(this.path, ...)) can interleave or corrupt when multiple
processes write; replace the direct append with a multi-process-safe approach
such as acquiring an advisory lock before writing (e.g., flock via a native
binding or fs-ext's flockSync), or implement a dedicated log-writer/aggregator
process or DB-backed store; ensure the code acquires the lock on this.path (or
on a separate .lock file), performs the append of JSON.stringify(entry)+"\n",
updates this.seq and this.prevHash only after a successful write, and always
releases the lock even on error.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a1657469-f7fc-48b6-b329-fb8a4cbfad82
⛔ Files ignored due to path filters (2)
nemoclaw/package-lock.jsonis excluded by!**/package-lock.jsonpackage-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (10)
.github/PULL_REQUEST_TEMPLATE.md.github/workflows/pr.yamlDockerfiledocs/reference/audit-chain.mddocs/reference/injection-scanner.mdinstall.shnemoclaw/src/security/audit-chain.test.tsnemoclaw/src/security/audit-chain.tsnemoclaw/src/security/injection-scanner.test.tsnemoclaw/src/security/injection-scanner.ts
💤 Files with no reviewable changes (1)
- .github/workflows/pr.yaml
| ### `maxSeverity(findings: Finding[]): Severity | ""` | ||
|
|
||
| The highest severity level present in the findings array, or an empty string if the array is empty. |
There was a problem hiding this comment.
Documentation-code mismatch: maxSeverity returns null, not "".
The documented return type Severity | "" does not match the implementation, which returns Severity | null. The test at injection-scanner.test.ts:623-625 confirms maxSeverity([]) returns null via .toBeNull(). Callers following this documentation would incorrectly check for an empty string instead of null.
📝 Proposed fix
-### `maxSeverity(findings: Finding[]): Severity | ""`
+### `maxSeverity(findings: Finding[]): Severity | null`
-The highest severity level present in the findings array, or an empty string if the array is empty.
+The highest severity level present in the findings array, or `null` if the array is empty.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ### `maxSeverity(findings: Finding[]): Severity | ""` | |
| The highest severity level present in the findings array, or an empty string if the array is empty. | |
| ### `maxSeverity(findings: Finding[]): Severity | null` | |
| The highest severity level present in the findings array, or `null` if the array is empty. |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/reference/injection-scanner.md` around lines 113 - 115, The
documentation for maxSeverity incorrectly states its return type as `Severity |
""`; update the doc to match the implementation and tests by changing the return
type to `Severity | null` and the description to say it returns null for an
empty findings array; reference the maxSeverity function and the existing test
that asserts null to ensure consistency.
66b520e to
f68e97c
Compare
|
✨ Thanks for submitting this PR with a detailed summary, it proposes a new security feature to improve audit logging and prevent tampering. |
- Remove dead code: `classifyRisk()` count > 2 branch can never be reached because trifecta is checked first and there are exactly three capability classes — simplify to a ternary - Add `onTrifecta` callback to `SessionStore` constructor so callers can log a warning, emit a metric, or terminate the session when risk escalates; callback fires once per session on first trifecta - Add `clear()` method to release all tracked state; prevents unbounded memory growth in long-running processes - Consolidate duplicate event-cap / boundary-condition test suites into a single test covering all boundary behaviors - Add tests for `onTrifecta` (fires once, per session, not partial) and `clear()` (resets state, allows new sessions) - Fix passive voice in docs: "are dropped" → "The tracker drops", "are silently ignored" → "The method silently ignores", "are not deduplicated" → "The tracker does not deduplicate" - Replace colon with em dash in exfiltration chain sentence - Add justification for 100-event cap (~10 KB per session) - Document in-memory-only limitation explicitly - Annotate Next Steps cross-refs with pending PR numbers (NVIDIA#870/NVIDIA#892) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Wrap onTrifecta callback in try/catch so a broken handler never
disrupts recording — the store state is already mutated by the time
the callback fires, so propagating would leave callers in an
inconsistent state
- Replace {doc} cross-references with plain-text file paths to avoid
Sphinx build errors while injection-scanner (NVIDIA#870) and audit-chain
(NVIDIA#892) pages are still pending
- Add "NemoClaw" prefix to title.page and H1 to match the naming
convention used by other reference pages (NemoClaw Architecture,
NemoClaw Network Policies, etc.)
- Add test: getExposure returns null after clear() — catches partial-
reset bugs that wipe capabilities but not the event log
- Add test: onTrifecta fires again after clear + re-record — verifies
the callback is not permanently suppressed for a session ID
- Add test: throwing onTrifecta callback is swallowed without error
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Docs reviewThe doc content is accurate — every API surface, interface, default, and behavioral claim matches the implementation in A few style guide items to fix before merge: 1. Frontmatter
|
|
All four fixed in 0db9334:
Let me know if anything else needs a pass. |
|
All currently raised feedback on this branch should be addressed now. Latest maintainer review is approved and checks are green on the current head. @brandonpelfrey when you have a moment, could you please take a final pass? |
e0a237e to
5cd3b6d
Compare
67fc371 to
1b90a2c
Compare
SHA-256 hash-chained JSONL audit logger with verify, export, and tail utilities. Each entry includes the hash of the previous entry, making any tampering detectable via the verifyChain function. Includes sequence continuity and chain_id consistency checks to detect block-deletion and splice attacks. Graceful handling of malformed JSONL lines in all read paths.
Update the audit chain reference page so the H1 heading matches the title.page frontmatter value, following the convention used by other NemoClaw reference pages. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Silent skip is more appropriate for a library module — callers use verifyChain() for tamper detection instead. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sphinx requires every document to be in a toctree — the CI doc build fails with -W (warnings as errors) without this entry. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The referenced doc does not exist yet, causing Sphinx -W to fail. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Frontmatter description: flat string → main/agent structure
- Em dash → colon in title.page and H1
- Passive voice → active ("Skips malformed lines")
- {doc} cross-ref → relative link in docs, skill pointer in generated file
- Regenerated skill files via docs-to-skills.py
|
❌ Brev E2E (full): FAILED on branch |
1b90a2c to
34137bc
Compare
|
Rebased on current main (211d19f). All 7 commits cherry-picked cleanly — no conflicts in our files. Plugin tests pass (357/357 including our 38 audit-chain tests). Types clean. Re #916 — had a look at Benedikt's approach. His PR is Python-side and focuses on OS-layer tamper prevention (append-only CI runs are pending workflow approval. |
|
Thank you @gemini2026 for your help here. This is the right kind of fix, but this is already addressed along with a couple of other things in #916 . We're going to be proceeding with 916 instead of this PR. |
|
Makes sense — #916 covers audit logging end-to-end with the OS-layer hardening too. Good to consolidate. If Benedikt's implementation could benefit from the #870 (injection scanner) is rebased and ready for review separately whenever you have bandwidth. |
Closes #891
What this does
Adds a tamper-evident audit logger under
nemoclaw/src/security/. It writes JSONL entries where each entry includes a SHA-256 hash of the previous one — modifying or deleting any entry breaks the chain downstream.Comes with
verifyChain()to validate an entire log file, plusexportEntries()andtailEntries()for querying.Three new files, no changes to existing NemoClaw code.
How the chain works
Each entry has:
seq(monotonic),chain_id(random hex per instance),prev_hash,entry_hash,type,time,data. The logger resumes from an existing file by reading the last entry for continuation state.verifyChaincatches: modified data, broken hash links, sequence gaps (block deletion), and chain_id mismatches (splice attacks).Test plan
npx vitest run src/security/audit-chain.test.ts)tsc --noEmitcleanSigned-off-by: Charan Jagwani [email protected]