Jenny J1
Verdict: CHANGES REQUESTED (FLT-359)¶
The advisory CLI boundary (src/Forge.Approvals.Cli/Program.cs:17-27, src/Forge.Approvals.Cli/Program.cs:37-54), exception scrubbing (src/Forge.Approvals.Cli/Program.cs:86-91), non-creating runtime SQLite open (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:126-135, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:145), and post-lock BEGIN IMMEDIATE clock sampling (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:68-75) are well structured. However, there are two HIGH-severity defects (one breaking m-of-n quorums when m < n, and one privilege-boundary flaw in ledger directory provisioning) plus MEDIUM contract/resilience issues below.
Findings¶
1. [HIGH] Strict m-of-n (m < n) quorum approvals can never be committed¶
- Location:
src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:95-99,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:107-110(paired withsrc/Forge.Approvals.Cli/SqliteApprovalLedger.cs:57-58) - Problem:
RegisterPendingAsync(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:47-60) runs at challenge creation time—before humans respond—and persists allnissued challenge IDs (challenge_ids) and allnchallenged person IDs (approver_person_ids). When anm-of-nquorum withm < n(e.g., 2-of-3) is satisfied,approvedByhasmentries while the registered row hasnentries: - If the caller passes all
nregisteredevidenceitems andmapprovedByitems,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:95-99rejects becauseapprovedBy.Count != evidence.Count(m != n) andSequenceEqualfails. - If the caller filters
evidencedown to themapproved challenges,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:95-99passes, butsrc/Forge.Approvals.Cli/SqliteApprovalLedger.cs:107-110checksWHERE ... AND challenge_ids=?5 AND approver_person_ids=?6againstChallenges(evidence)(mitems) vs. the storedn-item JSON arrays, matching0rows (SELECT changes() != "1") and returningfalse. - As written,
TryCommitEffectAsynconly ever succeeds forn-of-nunanimity. - Fix: Inside
BEGIN IMMEDIATE, readchallenge_idsandapprover_person_idsfromapprovals WHERE jti=?1 AND action_hash=?2 AND approver_roles='[]' AND consumed_at IS NULL, reconstruct the registeredPersonId -> ChallengeIdmap, verify thatevidenceis a non-empty duplicate-free subset matching that registeredPersonId -> ChallengeIdmapping, and verify thatapprovedBy(Count > 0, distinctPersonIds,Enum.IsDefined(p.Role)) is a subset ofevidencePersonIds. Then executeUPDATE approvals SET consumed_at=?1, approver_roles=?2 WHERE jti=?3 AND action_hash=?4 AND approver_roles='[]' AND consumed_at IS NULL. This preserves exact challenge-ID pinning while supportingm < nregardless of whether the caller passes allnregistered challenges or themapproved challenges.
2. [HIGH] Initialize() trusts pre-existing/unowned/reparse directories and checks emptiness before locking down permissions¶
- Location:
src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:20-36 - Problem:
- NTFS Owner DACL-reset bypass:
Directory.CreateDirectory(directory)(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:22) succeeds silently whendirectoryalready exists. If an untrusted local user/agent pre-creates an empty directory (for example under a shared parent likeC:\ProgramData) and grants the executor access,SetAccessControl(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:28-33) modifies only the DACL and never verifies or sets the NTFS Owner (GetOwner(typeof(SecurityIdentifier))). Under Windows NTFS (SeAccessCheck), the object creator/Owner unconditionally retainsWRITE_DAC | READ_CONTROLeven when excluded bySetAccessRuleProtection(true, false), allowing the untrusted creator to rewrite the DACL afterInitialize()finishes and tamper withapprovals/effects. - Reparse points / junctions:
Initialize()does not rejectFileAttributes.ReparsePointondirectory(unprivileged users on Windows can create directory junctions). - TOCTOU window & Unix file mode:
Directory.EnumerateFileSystemEntries(directory).Any()(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:23) executes beforeSetAccessControl(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:33) andFile.SetUnixFileMode(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:35). Whiledirectorystill carries inherited ACLs / default umask permissions, a local process can plant<db>-journal/<db>-walfiles after line23and before line33/35, which line36(FileMode.CreateNewondatabasePathonly) will not catch. On Unix, line36also createsdatabasePathwith default umask (0644) instead of0600. - Fix: Reject
FileAttributes.ReparsePointondirectory(and verifyDirectoryInfo.LinkTarget is null), applySetAccessControl/SetUnixFileMode(0700) before enumerating directory contents, verify on Windows thatnew DirectoryInfo(directory).GetAccessControl().GetOwner(typeof(SecurityIdentifier)) == owner, then assert!Directory.EnumerateFileSystemEntries(directory).Any(), and createdatabasePathusingFileStreamOptionswithUnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite.
3. [MEDIUM] TryRecordAsync(DateTimeOffset now, ...) ignores now, breaking IApprovalClock monotonicity checks¶
- Location:
src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:82-83 - Problem:
TryRecordAsync(DateTimeOffset now, CancellationToken cancellationToken)discardsnowand delegates toTryObserveAsync(cancellationToken), which samplesthis.UtcNowinstead. Any caller or test invokingIApprovalClock.TryRecordAsync(now)with a stale/rolled-back timestamp (now < stored_ticks) fails open (returns true) wheneverthis.UtcNow >= stored_ticks, and passingnow > this.UtcNowfails to advanceclock.utc_tickstonow. - Fix: Either remove
TryRecordAsyncfromIApprovalClockif completely retired, or validate and persistnow.UtcTicksinsideBEGIN IMMEDIATE(returningfalsewhennow.UtcTicks < ticks, else updatingclock.utc_tickstonow.UtcTicks).
4. [MEDIUM] FileRequestStore.Load throws on missing JTI despite nullable contract, and Save writes non-atomically in place¶
- Location:
src/Forge.Approvals.Cli/Stores.cs:7-19(consumed atsrc/Forge.Approvals.Cli/Program.cs:72-73) - Problem:
Load(Guid jti)returnsStoredApproval?andProgram.cs:72-73checksif (stored is null), butFile.OpenRead(src/Forge.Approvals.Cli/Stores.cs:16) throwsFileNotFoundException/DirectoryNotFoundExceptionwhen the file or directory does not exist (masked inApprovalClionly by the blanketcatch (Exception)atsrc/Forge.Approvals.Cli/Program.cs:86, while breaking direct callers). Additionally,Save(src/Forge.Approvals.Cli/Stores.cs:10-12) serializes directly into${jti:D}.jsonwithFileMode.CreateNewandFileShare.None; an interrupted write leaves a corrupt file that permanently blocks thatJti, and concurrentLoadcalls fail with sharingIOExceptions. - Fix: Return
nullinLoadwhen the path does not exist (catchingFileNotFoundException/DirectoryNotFoundException), and inSavewrite +Flush(flushToDisk: true)to a temporary file indirectorybefore atomically moving viaFile.Move(tmp, target, overwrite: false).
5. [LOW] Outbox crash-recovery gap, synchronous 10s lock wait in async methods, and Linux library search path¶
- Location:
src/Forge.Approvals.Cli/Migrations/001-approval-ledger.sql:12-15,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:111-125,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:149,src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:175-176 - Problem:
- Outbox recovery: If the executor crashes immediately after
db.Execute("COMMIT")(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:114) and before dispatching the effect,approvals.consumed_atis set so retries ofTryCommitEffectAsyncreturnfalse, yeteffects(src/Forge.Approvals.Cli/Migrations/001-approval-ledger.sql:12-15) has nodispatched_at/claim state andSqliteApprovalLedgeronly exposes point-lookupReadQueuedEffect(Guid jti)(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:121-125) with no way for a recovery sweeper to enumerate undispatched effects. - Uncancelable sync wait & implicit rollback:
Native.BusyTimeout(handle, 10000)(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:149) blocks calling threads synchronously for up to 10s insideTask-returning methods (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:47,62,85) without observingcancellationToken, and early returns afterBEGIN IMMEDIATE(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:72,105,110) rely on implicitsqlite3_close_v2rollback instead of an explicitROLLBACK. - Linux P/Invoke search path: On Windows,
winsqlite3.dllis pinned toEnvironment.SystemDirectory, whereas on LinuxNativeLibrary.Load("libsqlite3.so.0", assembly, path)(src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:176) receivespath == null, which searchesAppContext.BaseDirectorybefore OS library directories. - Fix: Add dispatch-tracking state (or an enumeration/acknowledge method) on
effectsif the executor does not externally journaljtibefore callingTryCommitEffectAsync; issue explicitROLLBACKon early exit paths; and passpath ?? DllImportSearchPath.SafeDirectoriestoNativeLibrary.Loadon Linux.
Backend Concurrency & Missing Test Verification¶
No test files are included in this diff (6379edb vs master). Before landing, verify or add deterministic tests covering:
1. Strict m-of-n (m < n) quorum commit (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:47-60, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:85-119): Register 3 challenges (Alice, Bob, Charlie), approve only 2 (Alice, Charlie), and assert TryCommitEffectAsync returns true, queues effects, and records only those 2 in approver_roles—plus negative tests where an unchallenged 4th PersonId or mismatched ChallengeId is rejected.
2. Parallel double-spend & cross-connection race (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:100-115): Launch $N \ge 8$ concurrent Task.Run callers (across separate SqliteApprovalLedger instances pointing at the same SQLite file) racing TryCommitEffectAsync for the same Jti; assert exactly one returns true, all others return false, and effects contains one row.
3. Concurrent monotonic clock contention & rollback (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:62-83): Parallel TryObserveAsync writers under a stepped FakeTimeProvider asserting non-decreasing utc_ticks with zero spurious SQLITE_BUSY failures, plus explicit rollback tests on both TryObserveAsync and TryRecordAsync(rolledBackTimestamp).
4. Mid-transaction cancellation atomicity (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:74, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:113): Cancel CancellationToken before COMMIT and verify OperationCanceledException is thrown, approvals.consumed_at remains NULL, effects is empty, clock.utc_ticks is unchanged, and no writer lock leaks to subsequent connections.
5. Directory ownership & pre-seeded directory rejection (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:18-44): Assert Initialize() rejects reparse points, non-empty directories, and (on Windows) pre-existing directories not owned by the current WindowsIdentity SID.