You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
File access 1/3: race-free file-reference resolver with a pluggable access policy (additive) - #137
This is part 1 of 3: the core. It is additive, and no existing caller's behavior changes. It adds DemaConsulting.CanvasNet.Files: a race-free file-reference resolver with a pluggable access policy.
FileAccessPolicy is an abstract class with AllowAll (the default for new callers), NoSymlinks, UnderRoots(roots), Combine(...) and FromDelegate(name, check).
Check(FileAccessRequest) receives the reference as written, the referrer, the base folder, the requested path, and the real final path of the opened handle.
It returns a FileAccessDecision (allow, or deny with a reason and a hint).
FileReferenceResolver opens first, then checks the real path of the open handle, so swapping a folder for a link between the check and the open can't escape a policy. The real path comes from the open handle on each OS:
Windows: GetFinalPathNameByHandleW;
Linux: /proc/self/fd/N;
macOS: proc_pidfdinfo, with an fstat fallback.
Restrictive policies fail closed when the real path is unavailable.
Hardening:
Unix files are opened non-blocking, and only regular files are accepted, so devices and FIFOs are refused.
UNC, network and device paths (including \\.\ and \\?\ forms and legacy device names) and alternate data streams are refused under every policy.
NoSymlinks is anchored at the trusted start of the chain.
macOS folders are compared after realpath.
SandboxedFileResolver keeps its behavior, but now verifies the open handle before reading, which closes the security review's check-then-open race.
Race tests without timing: an injected hook swaps a folder for a junction between the open and the check, and the decision follows the handle. Junctions need no privilege, so these run on Windows CI. File-symlink tests skip there with a stated reason.
The code-review gate found and fixed four bypasses during development:
NoSymlinks via relativeTo;
a link to a UNC share under AllowAll;
legacy device names;
a \\.\ device path under an extended-length base folder.
Additional Notes
70 files changed.
CI on this branch was green on Windows, Linux and macOS, including the first macOS run of the native code.
Parts 2 (the breaking switch) and 3 (CLI and docs) are stacked on top. All three should merge before the next release tag, so the library and CLI defaults never differ in a published package.
Type of Change
Bug fix (non-breaking change which fixes an issue)
New feature (non-breaking change which adds functionality)
Breaking change (fix or feature that would cause existing functionality to not work as expected)
Documentation update
Code quality improvement
Related Issues
This is the file-access policy redesign (agreed in review): the default is unrestricted, as in Pandoc; there is a race-free policy hook with built-in policies; and the CLI gets options. It is part 1 of 3 stacked PRs. There is no issue to close.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
Code builds successfully and all tests pass: pwsh ./build.ps1 passed (83,397 tests, 0 failed, 60 OS-specific and symlink-privilege skips)
Code produces zero warnings
Code Quality
New code has appropriate XML documentation comments
Static analyzer warnings have been addressed
Quality Checks
Please run the following checks before submitting:
All linters pass: pwsh ./lint.ps1 passed (exit 0)
Testing
Added unit tests for new functionality
Updated existing tests if behavior changed
All tests follow the AAA (Arrange, Act, Assert) pattern
Test coverage is maintained or improved
Documentation
Updated README.md (if applicable)
Updated docs/ documentation (if applicable)
Added code examples for new features (if applicable)
Updated requirements.yaml (if applicable): the per-unit reqstream files
…Path, NativeMethods)
Windows GetFinalPathNameByHandleW/GetFileType, Linux /proc/self/fd and fstat, macOS proc_pidfdinfo; O_NONBLOCK|O_CLOEXEC open on Unix; test seams around the open.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ilt-in policies
Open, inspect the handle, ask the policy about the real path, then read from the same handle. AllowAll (default), UnderRoots, NoSymlinks, Combine and FromDelegate. Network, device and ADS paths and non-regular files are always refused; restrictive policies fail closed without a real path.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The link walk is unchanged; the open now goes through the handle path and the no-symlinks rule anchored at the root is checked on the handle's real path, closing the walk/open race. Non-regular files are CannotRead; an unavailable real path is LinkCheckFailed.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…-free checks
Unit tests for FileReferenceResolver (search, text rules, limits, cache, callback, policy evaluation), real links and junctions, deterministic race tests through open seams (no timing), FileAccessPolicy built-ins, the per-OS RealPath unit (OS-specific scenarios skip elsewhere), the sandbox's post-open verification, Files subsystem tests with a source-tree guard for direct file opens, and two system tests.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…file-access policies
System, subsystem and unit requirements (OS-specific evidence with source filters), unit design and verification for FileReferenceResolver, FileAccessPolicy and RealPath, the sandbox's post-open verification, the platform-support note on native interop, SysML parts, review sets, spelling terms, the user-guide API section, a README feature bullet, and updated XML docs of the namespace and the sandbox failure kinds.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…info cannot describe a descriptor
Keeps devices and named pipes recognized as non-regular files even if the vnode query fails (Arm64 struct stat layout only).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
… network shares and legacy device names, canonicalize macOS folders with realpath
- FileReference carries the host-chosen origin of its chain; FileAccessRequest.BaseDirectory is that origin, never a referring document's folder, and Resolve rejects a relativeTo this resolver did not return
- Windows: a local path whose opened file lies on a network share is NetworkPath under every policy (mapped network drives exempt); a reference mapped to a device (NUL) is InvalidPath before the open
- macOS: TryGetCanonicalDirectory uses realpath(3), so an execute-only folder has a real location; the sandbox reports an unknown root location as LinkCheckFailed
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ets, legacy device names, execute-only roots, and the subsystem and system scenarios
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…in origin, network targets, device names and execute-only roots
- Subsystem requirements narrowed to sandboxed paths where they contradicted the policy model; same-level tests replace wrong-level links
- New unit requirements ChainOrigin, NetworkTarget and RealPath-NetworkLocation; system scenarios for combined and delegate policies and the sandbox link swap
- Vega-Lite and OpenSCAD docs no longer claim a link swapped in after the check goes unnoticed; case-insensitive comparison documented as a known limit
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ory; clarify docs and tests
An absolute reference such as C:/x/NUL resolved against an extended-length
directory (\\?\C:\docs) gave \\.\NUL and bypassed the device-name refusal.
FullCandidate now refuses every \\.\ path and allows a \\?\ path only under
the same root as the extended-length directory. Also reword the Scad and
Vega-Lite BaseDirectory docs (the decision uses the opened handle), clarify
the chain-origin verification text, and move an assert out of the Act step.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Approval is blocked by active critical and moderate issues that can allow unknown non-regular handles or misclassify valid Linux paths, violating fail-closed file safety and correct path resolution.
This additive PR introduces a policy-driven, race-resistant file-reference resolver for CanvasNet, adds cross-platform open-handle inspection, hardens the existing sandbox resolver, and updates related tests, traceability artifacts, and documentation.
… from the open handle
- FileReferenceResolver and SandboxedFileResolver read a file only when its handle is known to be a regular
file; an unknown type (the platform cannot tell) is refused under every policy, AllowAll included.
- Linux: deletion is decided from fstat's link count (zero) instead of the " (deleted)" suffix of the
/proc/self/fd link, which a live file may carry in its name; the link text is kept verbatim. The
struct stat layouts are x64 (st_nlink u64 @16, st_mode u32 @24) and Arm64 (st_mode u32 @16,
st_nlink u32 @20).
- New IsRegularFileOf test seam, regression tests, requirements and docs.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Three active findings remain, including a critical path-validation issue that can access DOS devices before classification and moderate issues that violate the safe-display contract.
The public constructor documents that Reference has control characters replaced, but it stores the caller's string unchanged. A caller can construct this exception directly with "a\0b", leaving the control character in both Reference and the user-facing Message, contrary to the safe-display contract. Normalize the reference before assigning it and cover direct construction with a control character.
Absolute references expose host paths in denial messages
For an absolute reference, Reference can itself be a host path, but this interpolation puts it verbatim into Message. That violates the documented/required guarantee that messages are safe to show to an untrusted author and never disclose host directories: a denied reference such as /srv/private/key would expose that directory. Sanitize the display value or omit path components for host paths, and add an absolute-reference message test.
…ception references printable
- FileReferenceResolver refuses, on Windows and before the open, a path with a reserved device name in
any component (CON, PRN, AUX, NUL, COM0-9, LPT0-9, the superscript-digit forms, CONIN$, CONOUT$, any
case, with an extension, trailing spaces or dots, or a stream suffix); the extended-length (\\?\)
base-directory exception is kept. SandboxedFileResolver refuses them before its link walk (CannotRead).
- FileReferenceException replaces control characters in Reference also when constructed directly.
- Docs state precisely what a message may contain: the reference as written, never the resolved or
real path or a configured directory; a test proves it for a denied absolute reference.
- Device-name tests assert through the BeforeOpen seam that nothing was opened.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Previously missed findings, both answered in 2ea4f3d:
Control characters through direct construction: fixed. The public FileReferenceException constructor now replaces control characters too. A test constructing it with "a\0b\n" gets "a?b?" in both Reference and Message.
Absolute references in messages: this is by design. The message repeats the reference exactly as the author wrote it, which reveals nothing they did not supply, and it never adds the resolved path, the real path or a configured base folder. The docs now state that precisely, and a test checks that a denied absolute reference's message contains the reference as written but neither the real path nor the base folder.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Critical active findings show that trusted-root paths are re-resolved after opening, allowing rename-and-replace races to bypass sandbox boundary checks and escape configured roots.
This resolves the anchor by name after the open. If a writer renames the trusted root after the lexical walk and replaces it with a link to an outside directory before the open, TryGetCanonicalDirectory(anchor) resolves that attacker-controlled replacement; the outside handle path then matches Expected(canonicalAnchor, ...) and this returns true. The sandbox post-open check and NoSymlinks share this helper, so the claimed race protection can be bypassed at the trusted root. Capture the canonical anchor before opening and carry that snapshot into the post-open check (or verify the anchor handle) instead of resolving the name again.
UnderRoots can accept an outside path after root replacement
ContainsWrittenPath short-circuits on the lexical root, so a normal pre-check does not populate Canonical. If the root is renamed and replaced by a link to an outside directory before the open, ContainsRealPath computes Canonical from that replacement and accepts the outside handle as inside the newly resolved root. This lets UnderRoots escape its originally configured boundary. Snapshot each root's real location before opening and use that same snapshot for the post-open real-path check, rather than lazily resolving the root name after the race window.
Closes the root rename-and-replace race: the post-open check compared the real path of the handle with a
root or anchor location it resolved by name after the open, so a root renamed and replaced by a link in
that window let the outside file pass.
- UnderRoots captures each root's real location when the policy is created and compares real paths only
with it; a root that does not exist then allows no file (fail closed, with its own reason and hint).
- NoSymlinks: the resolver captures the real location of the anchor (once per resolver, before the first
open below it) and the long 8.3 spelling of the written path before every open, and passes them in an
internal FileAccessRequest.Snapshot; the policy uses only that snapshot after the open.
- SandboxedFileResolver captures each root's real location before the link walk and the open.
- MatchesWithoutLinks resolves nothing by name; the post-open 8.3 expansion is replaced by the pre-open
long spelling (same sibling flaw).
- Deterministic race tests (root renamed and replaced by a junction or symbolic link inside the BeforeOpen
seam) for UnderRoots, NoSymlinks and the sandbox; a DirectoryLocationOf seam covers the unknown-location
path on every OS.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Fixed in 38d64f3: the root rename-and-replace race (both summary findings, plus the same flaw elsewhere).
Root cause. After the open, the check compared the handle's real path with the location of a trusted folder (a root or an anchor) that it looked up by name at that moment. If someone renamed that folder and put a link to an outside folder in its place during that window, the outside file passed the check.
Fix: no built-in check looks up a folder by name after a file is opened.
UnderRoots: each root's real location is captured when the policy is created, and real paths are compared only with that captured location. A root that doesn't exist (or can't be resolved) when the policy is created allows nothing, even after it is created. This fails closed, and the denial has its own reason and hint.
NoSymlinks: policies name the folders they trust. Before each open, FileReferenceResolver captures those folders' real locations and the expanded 8.3 spelling of the written path, and the policy uses only those after the open. A folder that wasn't captured is denied.
SandboxedFileResolver: each root's real location is captured before the link walk and the open.
Same flaw elsewhere: the 8.3 short-name expansion now uses the value captured before the open instead of looking the name up afterwards.
Tests (deterministic, using the existing hook): after the pre-check, the root is renamed and replaced by a junction (Windows) or a symbolic link (Linux, macOS) to an outside folder. The outside file is denied under UnderRoots and NoSymlinks, and the sandbox refuses it as ThroughLink. A new hook covers the "location unknown" path on every OS, and a root created after the policy allows nothing.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Critical active findings show that non-DOS device-namespace roots can bypass the documented device-path rejection and allow access to Windows device paths.
…vice-path rule
The extended-length exemption accepted any \\?\ root, so a base such as \\?\GLOBALROOT\Device\... let a
relative reference reach the Windows device namespace.
- One shared rule, RealPath.IsOrdinaryExtendedPath: only \\?\X:\ and \\?\Volume{GUID}\ map no device
names. RealPath.IsWindowsDeviceNamespace recognizes \\.\, \\?\ and \??\ in either slash.
- FileReferenceResolver: a full path in a device namespace is InvalidPath unless both it and its directory
are ordinary extended-length paths with the same root; references under \\?\GLOBALROOT\, \\?\UNC\,
\\?\pipe\ or \\.\ bases are refused before any open. A \??\ reference is a device path on Windows.
- SandboxedFileResolver: a path below a root in any other device namespace is CannotRead before the link
walk and the open; the reserved-name exemption uses the same rule.
- UnderRoots rejects a device-namespace root other than an ordinary extended-length one when created.
- Aligned: the final path of a handle is kept only as X:\... or \\server\... (anything else is unknown,
fail closed), and \\?\UNC\ and \\?\X:\ are classified as network or by their drive.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Fixed in a9bf089 (both threads): the extended-length exemption is now limited to drive and volume roots.
One shared rule (RealPath.IsOrdinaryExtendedPath): only \\?\X:\... and \\?\Volume{GUID}\... are exempt, because they are the only roots known to map no device names. \\?\GLOBALROOT\, \\?\UNC\, \\?\pipe\, \\.\ and \??\ get no exemption.
FileReferenceResolver: every reference under a non-ordinary device-namespace base is refused as InvalidPath before any open. A \??\ reference is a device path.
SandboxedFileResolver: a path under such a root is refused before the link walk and the open.
UnderRoots: a root in a non-ordinary device namespace is rejected with ArgumentException when the policy is created.
Aligned in the same commit: the final path read from a handle is kept only as X:\... or \\server\...; anything else counts as unknown, and restrictive policies refuse it. \\?\UNC\ is network, and \\?\Z:\ is classified by its drive.
Tests:
\\?\GLOBALROOT\Device\..., \\?\UNC\..., \\?\pipe\... and \\.\C:\... bases refuse relative and .. references with nothing opened, in both resolvers.
\\?\C:\... and \\?\Volume{GUID}\... bases still read their files.
A text-only theory covers the classification of every spelling on all OSes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull Request
Description
This is part 1 of 3: the core. It is additive, and no existing caller's behavior changes. It adds
DemaConsulting.CanvasNet.Files: a race-free file-reference resolver with a pluggable access policy.FileAccessPolicyis an abstract class withAllowAll(the default for new callers),NoSymlinks,UnderRoots(roots),Combine(...)andFromDelegate(name, check).Check(FileAccessRequest)receives the reference as written, the referrer, the base folder, the requested path, and the real final path of the opened handle.FileAccessDecision(allow, or deny with a reason and a hint).FileReferenceResolveropens first, then checks the real path of the open handle, so swapping a folder for a link between the check and the open can't escape a policy. The real path comes from the open handle on each OS:GetFinalPathNameByHandleW;/proc/self/fd/N;proc_pidfdinfo, with anfstatfallback.Restrictive policies fail closed when the real path is unavailable.
Hardening:
\\.\and\\?\forms and legacy device names) and alternate data streams are refused under every policy.NoSymlinksis anchored at the trusted start of the chain.realpath.SandboxedFileResolverkeeps its behavior, but now verifies the open handle before reading, which closes the security review's check-then-open race.Race tests without timing: an injected hook swaps a folder for a junction between the open and the check, and the decision follows the handle. Junctions need no privilege, so these run on Windows CI. File-symlink tests skip there with a stated reason.
The code-review gate found and fixed four bypasses during development:
NoSymlinksviarelativeTo;AllowAll;\\.\device path under an extended-length base folder.Additional Notes
Type of Change
Related Issues
This is the file-access policy redesign (agreed in review): the default is unrestricted, as in Pandoc; there is a race-free policy hook with built-in policies; and the CLI gets options. It is part 1 of 3 stacked PRs. There is no issue to close.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
pwsh ./build.ps1passed (83,397 tests, 0 failed, 60 OS-specific and symlink-privilege skips)Code Quality
Quality Checks
Please run the following checks before submitting:
pwsh ./lint.ps1passed (exit 0)Testing
Documentation