FLT-359 Fix Round 5 / 5b / 5c / 5d: Full Unix Ledger Path Guard + Display Sanitization¶
Decision by Andrew (2026-10-31): "Fix Unix properly" rather than restricting the executor ledger to Windows-only.
1. Linux/Unix POSIX (fcntl) Lock Preservation and Coordinated Per-Inode Pinning (src/Forge.Approvals.Cli/LedgerPathGuard.cs, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs)¶
- Problem (Cedric P1,
LedgerPathGuard.cs:97-101; Round 5b/5c Findings): On Linux/POSIX,fcntlrecord locks (F_SETLK/F_SETLKW) are associated with(process, inode). Closing any file descriptor referring to that inode in the process immediately releases all POSIX record locks held by the process on that file—including activeBEGIN IMMEDIATEtransaction locks held by SQLite on another descriptor. Conversely, pinning descriptors into a static table before.identityand schema validation succeed would retain file descriptors for failed/probed files, while allowing two concurrent cold opens to open separate provisional descriptors could close a duplicate descriptor mid-transaction or on GC finalization. - Fix:
LedgerPathGuardcoordinates both provisional and committed descriptors per(Device, Inode)underUnixPinLockviaUnixInodePin(Handle, Identity, ActiveGuards, Committed)inPinnedUnixFiles.- When
OpenUnixLeafruns on Linux, at most one file descriptor is opened per(Device, Inode)across the process. Concurrent guards opening the same(Device, Inode)before or afterCommitPin()incrementActiveGuardsand share the sameSafeFileHandlerather than opening a second descriptor that could later be closed or finalized. SqliteApprovalLedgercallsguard.CommitPin()(unixPin.Committed = true) only afterCheckIdentity(),VerifyConnectionHandle(),VerifyUnchanged(), andPRAGMA user_version == 1succeed. If validation fails beforeCommitPin(),LedgerPathGuard.Dispose()decrementsActiveGuardsand disposes/evicts the provisional descriptor whenActiveGuards == 0 && !Committed, so failed opens never leak file descriptors and never close a descriptor while another guard is active.SqliteApprovalLedgerserializes in-process ledger operations viaProcessGateand wraps everyBEGIN IMMEDIATEblock inTryObserveAsync,TryRecordAsync, andTryCommitEffectAsyncwithtry/finallythat explicitly executesROLLBACKwhenevercommittedis false before closing the connection.VerifyUnchanged()on Linux never opens or closes a file descriptor to the database inode: it re-stats held directory descriptors andunixPin.Handlewithfstat, re-walks ancestor directories from/viaopenat(O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), verifies the leaf directory entry viafstatat(leafDirFd, fileName, AT_SYMLINK_NOFOLLOW), and verifies/hardens any-journal,-wal, and-shmside files inleafDirFdviaVerifyUnixSideFiles.
2. Unix openat Walk, O_NONBLOCK + S_ISREG (nlink == 1) Verification, and Direct sqlite3_file_control Handle Verification (src/Forge.Approvals.Cli/LedgerPathGuard.cs, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs, src/Forge.Approvals.Cli/Stores.cs)¶
- Problem (Gronktayvius General & Red Team High, Jenny K1/K2, CedricFocus Round 5b/5c Findings):
open(path, O_NOFOLLOW)only checks the final component of each call and does not prevent ancestor directory rename swaps on Unix between the guard check andsqlite3_open_v2(path).- Passing
/proc/self/fd/<fileFd>directly tosqlite3_open_v2causes SQLite'sunixFullPathname(lstat+readlinkon the final path component) to either resolve the/proc/self/fd/<fileFd>symlink back to the mutable filesystem path or fail when attempting to create/proc/self/fd/<fileFd>-journalinsideprocfs. - Scanning
/proc/self/fdfor "any matching descriptor" does not prove which descriptor belongs to the specificsqlite3*connection when another descriptor to the ledger is open in the process. - Upstream SQLite creates
-journal,-wal, and-shmwith mode0644masked by processumask; enforcing mode0600(384u) in the custom VFSopensyscall wrapper and hardening any existing side files to0600viafchmodcloses any group/world-readable window without mutating process-globalumask. - Loading bare
libsqlite3.so.0on Linux allowsLD_LIBRARY_PATH/ app-directory search order hijacking, and following a soname symlink withfstatat(..., 0)without validating the resolved target's directory chain or pinning the opened.sodescriptor leaves a path-reopen window. - Fix:
- Anchored
openatdirectory walk with strict ancestor ownership/mode checks: Every directory component from/is walked step-by-step viaopenat(parentFd, segment, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)(and created duringPrepareDirectory/SavePrivateRecordviamkdirat(parentFd, segment, 0700)+openat+fchmod(fd, 0700)to clear any inheritedS_ISGIDbit). Every directory descriptor is verified viafstatto beS_ISDIR((mode & 0xF000) == 0x4000) withnlink >= 1, owned byrootor the effective UID (uid == 0 || uid == geteuid()), and free of group/other write bits (0x012) unless the sticky bit (0x200) is set; the leaf directory (for both the ledger andFileRequestStore) additionally requiresRequirePrivate(uid == geteuid()and mode0700on Unix; protected owner-only DACL on Windows). - Non-blocking single-link regular-file leaf open: The leaf database file is checked via
fstatat(leafDirFd, fileName, AT_SYMLINK_NOFOLLOW)and opened relative toleafDirFdwithopenat(leafDirFd, fileName, O_RDWR | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0600)(plusO_CREAT | O_EXCLandfchmod(fd, 0600)on creation). Bothfstatatandfstatenforce(mode & 0xF000) == 0x8000(S_ISREG),nlink == 1,uid == geteuid(), and mode0600, rejecting FIFOs, sockets, device nodes, symlinks, hard-linked files (nlink > 1), and directories. - SQLite opened via
/proc/self/fd/<leafDirFd>/<leafName>and verified directly before anyPRAGMAruns:LedgerPathGuard.ResolveOpenPathrequires a live file guard matchingPath.GetFullPath(filePath)and on Linux returns/proc/self/fd/<leafDirFd>/<leafName>.- Immediately across
sqlite3_open_v2—beforePRAGMA trusted_schema=OFF,PRAGMA foreign_keys=ON, orPRAGMA synchronous=FULLexecutes—SqliteApprovalLedger.Databaseretrieves SQLite's own connection handle/descriptor for"main": on Windows viaSQLITE_FCNTL_WIN32_GET_HANDLE(29), and on Linux x64 via a registeredsqlite3_vfs("forge_unix", cloned fromsqlite3_vfs_find(NULL)) whosexOpenwrapper intercepts thesqlite3_vfs"open"system call (xGetSystemCall/xSetSystemCallonsqlite3_vfsv3) underVfsSync+UnixPinLockusing a[ThreadStatic]recorder (activeSysOpenRecorder), enforces mode0600(384u) on any created file without mutating process-globalumask, preserves/restores nativeerrno(SetLastError = trueonUnixSysOpenDelegate+Marshal.GetLastPInvokeError()/Marshal.SetLastSystemError), and binds the exactfdreturned by SQLite'sopensyscall (openCallCount == 1, ordinalexpectedOpenPathmatch) directly to thatsqlite3_file*(pFile) viaLedgerPathGuard.CaptureVfsMainDbOpen(pFile, expectedOpenPath, ..., CleanupRejectedVfsOpen). IfbaseOpensucceeds (rc == 0) but the VFS binding is invalid (pathMismatch,openCallCount != 1, oropenedFd < 0),CleanupRejectedVfsOpeninvokespFile->pMethods->xClose(pFile), clearspFile->pMethods = IntPtr.Zero(NULL) per SQLite'sxOpenerror contract, and returns14(SQLITE_CANTOPEN).Databasethen queriesSQLITE_FCNTL_FILE_POINTER(7) and claims the descriptor viaguard.ClaimVfsConnectionDescriptor(sqliteFilePtr), andguard.VerifyConnectionHandle(borrowed, dbFilename)verifiessqliteDbFilename,RequirePrivate(borrowed, path, false), andReadIdentity(borrowed, false) == guard.FileIdentitydirectly on SQLite's descriptor. SqliteApprovalLedgerrejects embedded NUL (\0) characters in bound parameters (PersonId,ChallengeId, andDatabase.Executevalues) and passes explicit UTF-8 byte lengths (Encoding.UTF8.GetByteCount) tosqlite3_bind_text.VerifyUnixSideFileschecks-journal,-wal, and-shminleafDirFdviafstatat(..., AT_SYMLINK_NOFOLLOW)beforeBEGIN/COMMIT/ROLLBACKstatements step (and afterBEGINsteps, never afterCOMMIThas already stepped), requiringS_ISREG,nlink == 1, anduid == geteuid(), and tightening any SQLite-created side file whose mode is not yet0600viaopenat(O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)+fstatinode match +fchmod(0600).
- Root-owned system
libsqlite3.so.0resolution and fd pinning on Linux:LedgerPathGuard.ResolveTrustedUnixSqlite()resolves any soname symlink hop viareadlinkat(up to 4 hops), walks every ancestor directory of the resolved target from/withO_DIRECTORY | O_NOFOLLOW | O_CLOEXECrequiringuid == 0and(mode & 0x012) == 0, opens the final regular.sofile withO_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, verifiesfstat(S_ISREG,nlink == 1,uid == 0,(mode & 0x012) == 0), pins the handle inPinnedUnixSqliteLibrary, and returns/proc/self/fd/<libFd>toNativeLibrary.Load. - Ancestor- and path-bound
.identityrecord with atomicrenameat2(RENAME_NOREPLACE)publication:SqliteApprovalLedger.Initialize()callsfileGuard.SaveIdentity()inside the initialization transaction prior toCOMMIT(rolling back the transaction and cleaning up unconditionally via no-followRemoveIdentityIfPresent()if any step beforeCommitPin()fails), publishing.identityviarenameat2(..., RENAME_NOREPLACE)on Linux (File.Move(..., overwrite: false)on Windows), andCheckIdentityverifies canonicalPath,FileIdentity, and the fullAncestorschain. - Anchored
FileRequestStore.Save, fail-closedFileRequestStore.Load, and hardenedFileNotificationOutbox:LedgerPathGuard.SavePrivateRecordandOpenPrivateReadenforceValidateSingleFileName(fileName)(rejecting empty,.,.., path separators,:, trailing.or' ', NUL, and Windows reserved device namesCON,PRN,AUX,NUL,CONIN$,CONOUT$,COM1..COM9,LPT1..LPT9), enforceRequirePrivateon the leaf store directory (0700on Unix, protected owner-only DACL on Windows), and publish<jti>.jsonatomically without overwrite viarenameat2(..., RENAME_NOREPLACE)on Unix (File.Move(..., overwrite: false)on Windows).FileRequestStore.Loadopens request files viaLedgerPathGuard.OpenPrivateRead(directory, fileName), enforces a byte-length cap before JSON deserialization, rejects null/whitespaceChallengeId, and catches onlyFileNotFoundException/DirectoryNotFoundExceptionasnullwhile allowing tamper, permission, symlink, oversized-payload, and malformed-JSON exceptions to propagate.FileNotificationOutboxwalks and pins the outbox directory without following symlinks or reparse points (O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC+0700+uid == geteuid()on Unix; single-componentCreateDirectoryW+CreateFileW(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)withoutFILE_SHARE_DELETE+ handle-boundSetKernelObjectSecurity/GetKernelObjectSecurityowner-only DACL on Windows), writes a private0600temporary marker relative to the pinned directory that omitsJti(.pending-{guid}.tmp), publishes without overwrite (renameat2(..., RENAME_NOREPLACE)on Unix;File.Move(..., overwrite: false)on Windows), separates atomic publication (TryPublishMarkerNoReplace) from post-publish verification and durability (VerifyAndFlushPublishedMarker+FlushPinnedDirectoryHandle(outboxDirHandle)), verifies directory chain identity (VerifyOutboxChainUnchanged) across reservation and synchronization, and durably flushes the pinned directory handle before dispatch.
3. Complete Display Sanitization Across Push and Email Sinks (src/Forge.Approvals.Twilio/TwilioProvider.cs, src/Forge.Approvals.Notify/Notifications.cs)¶
- Problem (Jenny K3 High,
TwilioProvider.cs:45-50,TwilioProvider.cs:171-173): BuildDeviceMessagesanitizedEffectBindingandHumanSummarybut interpolatedtargetandrequest.Action.Ticketwithout callingSanitizeDisplayText.SanitizeDisplayTextiterated UTF-16charcode units, wherechar.GetUnicodeCategoryreturnsUnicodeCategory.Surrogatefor surrogate pairs, allowing supplementary-planeUnicodeCategory.Formatcharacters (such as Unicode Tag charactersU+E0001,U+E0020..U+E007Fand musical format controlsU+1D173..U+1D17A) and unpaired surrogates through.- Fix:
BuildDeviceMessageandEmailNotifiernow passkind,target,ticket,commandSha256,effect,summary, andserializedActionthroughSanitizeDisplayText.SanitizeDisplayTextin bothTwilioProviderandEmailNotifierenforcesArgumentNullException.ThrowIfNulland decodes Unicode scalar values withRune.TryGetRuneAt: unpaired surrogates (TryGetRuneAt == false), C0/C1 controls (Rune.IsControl),UnicodeCategory.Format(BMP and non-BMP),UnicodeCategory.LineSeparator(U+2028),UnicodeCategory.ParagraphSeparator(U+2029), and non-' 'UnicodeCategory.SpaceSeparatorscalar values are all replaced with' '.- CI TRX gate cleanup (
ci/Assert-TestResults.ps1,ci/Test-AssertTestResults.ps1): Assert-TestResults.ps1enforcesexecuted == discoveredandpassed == discoveredand includespending,inProgress, andwarningin the counter denylist.Test-AssertTestResults.ps1writes its synthetic TRX fixtures under a unique temp directory and removes it infinally.