Skip to content

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 with src/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 all n issued challenge IDs (challenge_ids) and all n challenged person IDs (approver_person_ids). When an m-of-n quorum with m < n (e.g., 2-of-3) is satisfied, approvedBy has m entries while the registered row has n entries:
  • If the caller passes all n registered evidence items and m approvedBy items, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:95-99 rejects because approvedBy.Count != evidence.Count (m != n) and SequenceEqual fails.
  • If the caller filters evidence down to the m approved challenges, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:95-99 passes, but src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:107-110 checks WHERE ... AND challenge_ids=?5 AND approver_person_ids=?6 against Challenges(evidence) (m items) vs. the stored n-item JSON arrays, matching 0 rows (SELECT changes() != "1") and returning false.
  • As written, TryCommitEffectAsync only ever succeeds for n-of-n unanimity.
  • Fix: Inside BEGIN IMMEDIATE, read challenge_ids and approver_person_ids from approvals WHERE jti=?1 AND action_hash=?2 AND approver_roles='[]' AND consumed_at IS NULL, reconstruct the registered PersonId -> ChallengeId map, verify that evidence is a non-empty duplicate-free subset matching that registered PersonId -> ChallengeId mapping, and verify that approvedBy (Count > 0, distinct PersonIds, Enum.IsDefined(p.Role)) is a subset of evidence PersonIds. Then execute UPDATE 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 supporting m < n regardless of whether the caller passes all n registered challenges or the m approved 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 when directory already exists. If an untrusted local user/agent pre-creates an empty directory (for example under a shared parent like C:\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 retains WRITE_DAC | READ_CONTROL even when excluded by SetAccessRuleProtection(true, false), allowing the untrusted creator to rewrite the DACL after Initialize() finishes and tamper with approvals/effects.
  • Reparse points / junctions: Initialize() does not reject FileAttributes.ReparsePoint on directory (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 before SetAccessControl (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:33) and File.SetUnixFileMode (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:35). While directory still carries inherited ACLs / default umask permissions, a local process can plant <db>-journal/<db>-wal files after line 23 and before line 33/35, which line 36 (FileMode.CreateNew on databasePath only) will not catch. On Unix, line 36 also creates databasePath with default umask (0644) instead of 0600.
  • Fix: Reject FileAttributes.ReparsePoint on directory (and verify DirectoryInfo.LinkTarget is null), apply SetAccessControl / SetUnixFileMode (0700) before enumerating directory contents, verify on Windows that new DirectoryInfo(directory).GetAccessControl().GetOwner(typeof(SecurityIdentifier)) == owner, then assert !Directory.EnumerateFileSystemEntries(directory).Any(), and create databasePath using FileStreamOptions with UnixCreateMode = 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) discards now and delegates to TryObserveAsync(cancellationToken), which samples this.UtcNow instead. Any caller or test invoking IApprovalClock.TryRecordAsync(now) with a stale/rolled-back timestamp (now < stored_ticks) fails open (returns true) whenever this.UtcNow >= stored_ticks, and passing now > this.UtcNow fails to advance clock.utc_ticks to now.
  • Fix: Either remove TryRecordAsync from IApprovalClock if completely retired, or validate and persist now.UtcTicks inside BEGIN IMMEDIATE (returning false when now.UtcTicks < ticks, else updating clock.utc_ticks to now.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 at src/Forge.Approvals.Cli/Program.cs:72-73)
  • Problem: Load(Guid jti) returns StoredApproval? and Program.cs:72-73 checks if (stored is null), but File.OpenRead (src/Forge.Approvals.Cli/Stores.cs:16) throws FileNotFoundException / DirectoryNotFoundException when the file or directory does not exist (masked in ApprovalCli only by the blanket catch (Exception) at src/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}.json with FileMode.CreateNew and FileShare.None; an interrupted write leaves a corrupt file that permanently blocks that Jti, and concurrent Load calls fail with sharing IOExceptions.
  • Fix: Return null in Load when the path does not exist (catching FileNotFoundException/DirectoryNotFoundException), and in Save write + Flush(flushToDisk: true) to a temporary file in directory before atomically moving via File.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_at is set so retries of TryCommitEffectAsync return false, yet effects (src/Forge.Approvals.Cli/Migrations/001-approval-ledger.sql:12-15) has no dispatched_at/claim state and SqliteApprovalLedger only exposes point-lookup ReadQueuedEffect(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 inside Task-returning methods (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:47, 62, 85) without observing cancellationToken, and early returns after BEGIN IMMEDIATE (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:72, 105, 110) rely on implicit sqlite3_close_v2 rollback instead of an explicit ROLLBACK.
  • Linux P/Invoke search path: On Windows, winsqlite3.dll is pinned to Environment.SystemDirectory, whereas on Linux NativeLibrary.Load("libsqlite3.so.0", assembly, path) (src/Forge.Approvals.Cli/SqliteApprovalLedger.cs:176) receives path == null, which searches AppContext.BaseDirectory before OS library directories.
  • Fix: Add dispatch-tracking state (or an enumeration/acknowledge method) on effects if the executor does not externally journal jti before calling TryCommitEffectAsync; issue explicit ROLLBACK on early exit paths; and pass path ?? DllImportSearchPath.SafeDirectories to NativeLibrary.Load on 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.

Jira FLT-359 · Vikunja · BOARD.md