- Overview
- Quick Navigation
- Reading Paths
- At A Glance
- Conceptual Model
- Installation
- The Ephemeral File System
- The Jailed File System
- Usage Examples
- Behavioral Reference
- Ephemeral: path routing
- Ephemeral: file-system close semantics
- Ephemeral: watch-service cadence and closure
- Ephemeral: copy vs. move semantics
- Ephemeral: capacity accounting
- Ephemeral: links
- Jailed: path identity and
ProviderMismatchException - Jailed: name validation
- Jailed: watch registration
- Jailed: attribute and file-store forwarding
- Error Model
- Defaults Reference
- Troubleshooting
- Limitations and Known Issues
- Summary
The smallmind-file module is a container for alternative java.nio.file
FileSystem implementations — file systems that plug into the standard JDK
NIO SPI (java.nio.file.spi.FileSystemProvider) but store, route, or gate
their data in ways the built-in file: provider cannot.
It is organized as two independently publishable artifacts:
-
file-ephemeral— an in-memory, heap-backedFileSystemwith a transparent fall-through to a native provider for paths outside its configured roots. Can be installed as the JVM default through-Djava.nio.file.spi.DefaultFileSystemProvider=…. -
file-jailed— a chroot-styleFileSystemthat confines all path resolution to a subtree of an underlying native file system. The jail boundary can be fixed at construction time or resolved per-call from a thread-bound context.
Neither artifact has a runtime dependency on the other. Both depend only on
smallmind-nutsnbolts; the jailed artifact additionally has an optional
compile-time dependency on jakarta.xml.bind-api for the JAXB annotations
on RootedFileSystemContext.
The JDK ships exactly one production-grade FileSystemProvider, the
platform file: provider. Everything else — in-memory sandboxes, chroot
confinements, overlay trees for tests, watched virtual directories —
either has to be implemented by hand or pulled in from a heavyweight
dependency such as Jimfs, Memoryfs, or a full VFS library.
The two modules in smallmind-file are the minimum useful answer to two
recurring needs that do not justify either of those choices:
-
Ephemeral, default-installable in-memory storage with native pass-through. Tests want a
Files.createDirectories/Files.write/Files.readStringloop that leaves no disk artefacts, runs at memory speed, and still reads real classpath resources through the ordinaryfile:provider. A production service that wants an overlay — for example, a scratch area under/opt/epicenter/twimblethat must behave like a real directory to legacy code but never touch disk — wants the same thing, but installed JVM-wide. -
A hard boundary around a subtree of the real file system. Code that accepts user-controlled path inputs — uploaded file managers, sandboxed plugin hosts, multi-tenant storage services — needs a
FileSystemwhose absolute/is someone else’s/var/lib/service/tenant-42, with every path translation gated so../../etc/passwdcannot escape. The JDK provides no such type; this module provides two concrete strategies for it.
Both modules exist as ordinary FileSystemProvider implementations so
that they integrate through java.nio.file.Files, java.nio.file.Path,
and java.nio.file.Paths without any code on the caller’s side knowing
that a non-standard provider is in play.
-
Not a full VFS (no zip, no SFTP, no S3). The two provided file systems are the two the repository needs; adding more is possible but is not the purpose of the module.
-
Not a security boundary on its own. The jailed provider enforces path containment at the path translation layer; it does not sign, encrypt, or audit I/O, and it does not defend against kernel-level escapes such as symlink traversal on the underlying native file system. A caller that wants those properties must compose them over the jailed provider.
-
Not a persistence layer. The ephemeral provider is, by construction, lost on JVM exit.
| If you are … | Read, in this order |
|---|---|
… a test author who wants a throwaway in-memory file system for the duration of a single test |
|
… a service author installing ephemeral storage as the JVM default provider |
Installing as the JVM default provider → Configuration → Native delegation in detail. |
… a library author building a user-facing upload surface that must not escape a tenant directory |
Jailed quick start → Translator strategies → Jail policy → Deriving the jail boundary per request. |
… someone deciding how hard the jail boundary needs to be, and what a symbolic link inside it can do |
|
… someone trying to understand why a call is throwing
|
| Artifact | Ships | Reach for it when | Module name |
|---|---|---|---|
|
|
You need a |
|
|
|
You need a |
|
A few terms recur throughout this module.
- Provider-managed singleton
-
Both
EphemeralFileSystemProviderandJailedFileSystemProvidermaintain exactly oneFileSysteminstance per provider. Calls tonewFileSystem(URI, Map)always throwFileSystemAlreadyExistsException;getFileSystem(URI)returns the single pre-constructed instance after validating the URI. This is a deliberate choice: it keeps the mapping between scheme and provider unambiguous when the provider is registered through the SPI. - Scheme mirroring
-
The ephemeral provider has a no-arg constructor using the scheme
"ephemeral"and aEphemeralFileSystemProvider(FileSystemProvider)constructor that mirrors the scheme of another provider (typically the platformfile:provider) and captures a reference to that provider’s root file system. When the provider is installed as the JVM default and mirrors thefile:scheme, ephemeral paths and native paths can coexist under the samePaths.get(…)call, with theEphemeralFileSystemConfigurationdeciding which ones are "ours". - Native delegation
-
In the ephemeral provider, any path the configuration does not claim is wrapped in a
NativePathadapter and all operations on it are forwarded, unchanged, to the native provider. This is what makes the ephemeral provider safe to install as the JVM default: real files underC:\Users\…or/usr/…are not intercepted; only paths that match the configured overlay roots are served from the heap.Three rules decide the question, in order. A path rooted at
/is claimed when it lies at or beneath a configured root, matched on whole segments. A path that is absolute in the native namespace is never claimed, whatever the roots say — on Windows a drive-qualified or UNC path does not begin with/, so without this rule it would look relative and be swallowed by the heap. Anything genuinely relative belongs to whichever file system owns the working directory. - Path translation
-
In the jailed provider, every operation goes through a
JailedPathTranslator.unwrapPath(Path, LinkOption…)call that converts the jailed absolute path into a native path rooted at the jail’s configured root directory. Translation normalizes the jailed path with..clamped at the jail root, validates every name element as a single legal name on the native file system, and verifies that the assembled native path lies beneath the root. Listing operations wrap native paths back intoJailedPathinstances viawrapPath(…). Any failure to confine a path raisesSecurityException. - Jail policy
-
Structural confinement alone can be defeated by a symbolic link that lives inside the jail and points out of it, because the native file system will follow it.
JailPolicy.STRICT, the default, closes that by additionally resolving the real location of the translated path and comparing it against the real path of the jail root, so an escaping link is refused rather than followed.JailPolicy.LENIENTperforms no I/O and accepts the risk. See Jail policy: structural versus real-path confinement. - Heap tree
-
Internal name for the in-memory data structure that backs the ephemeral file store: a tree of
DirectoryNode,FileNode, andLinkNodeobjects, each descending from a single anonymous root. File content lives in aHeapFileContent, a list of fixed-size segments addressed by absolute position, and is exposed to clients throughEphemeralSeekableByteChannelandEphemeralFileChannel.The content object holds no cursor of its own. That is the point: a channel owns only its own position, so two channels on one file advance independently, a single channel can be opened for reading and writing, and concurrent appends resolve the end of the file and write in one atomic step instead of overwriting one another.
- Space accounting
-
Every growth of file content is reserved against a running total through the
HeapSpaceGovernorthe store implements, and a write that would exceed the configured capacity fails rather than succeeding and driving the reported free space negative. Because the reservation happens while a content lock is held, the counter is lock-free and never reaches back for the tree lock. - Heap event / watch translation
-
Mutations to the heap tree raise
HeapEventobjects whose path is the changed entry. The store fires each event on the directory that contains the changed entry, and on that directory only — a NIO watch registration covers the entries of one directory and says nothing about its descendants, so events deliberately do not climb the tree. AnEphemeralHeapEventListeneris installed per watched directory and forwards to theEphemeralWatchService, which computes theWatchEventcontext()aswatchedPath.relativize(changedPath)so that the standard NIOWatchServicecontract is honoured end-to-end, entirely in heap.
Both artifacts are published under org.smallmind:
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>file-ephemeral</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>file-jailed</artifactId>
<version>${project.version}</version>
</dependency>Use whichever one you need; depending on both is allowed but unusual.
file-ephemeral-
Requires
smallmind-nutsnbolts(forSingleItemIterable,SnowflakeId, andUnknownSwitchCaseException). Everything else is JDK-only. File content is held inHeapFileContentrather than in nutsnbolts'ByteArrayIOBuffer, whose single shared stream position is the wrong shape for a file that several channels may hold open at once. file-jailed-
Requires
smallmind-nutsnbolts(forContextFactory/Context). Thejakarta.xml.bind-apidependency is marked<optional>true</optional>— it is needed only if you intend to unmarshalRootedFileSystemContextfrom XML. If you construct contexts programmatically, JAXB need not be on the classpath.
The jailed artifact ships a META-INF service entry:
META-INF/services/java.nio.file.spi.FileSystemProvider
org.smallmind.file.jailed.JailedFileSystemProviderso simply placing file-jailed on the classpath registers the jailed:
scheme with FileSystems.newFileSystem(URI, Map).
The ephemeral artifact ships one too:
META-INF/services/java.nio.file.spi.FileSystemProvider
org.smallmind.file.ephemeral.EphemeralFileSystemProviderso placing file-ephemeral on the classpath makes
FileSystems.getFileSystem(URI.create("ephemeral:///")) resolve without
the application constructing a provider itself. The service loader uses
the no-arg constructor, so the registered instance carries the
ephemeral: scheme and performs no native delegation.
Replacing the platform file: provider is a separate and deliberate
act, requested through
-Djava.nio.file.spi.DefaultFileSystemProvider=… (see
Installing as the JVM default provider) — a decision an application must
make on purpose, and one that constrains the configuration.
Both jars ship explicit module descriptors. On the classpath the descriptors are ignored. The repository-wide rules are in Module Path And Classpath; this section lists what is specific to these two modules.
-
Each descriptor declares its provider with
provides java.nio.file.spi.FileSystemProvider with …, alongside theMETA-INF/servicesentry shown above. On a module path only theprovidesclause counts, and the JDK’s own use of the service brings a provider module on the module path into the module graph without your module requiring it. -
org.smallmind.file.ephemeralrequiresorg.smallmind.nutsnboltsand exportsorg.smallmind.file.ephemeral,.heap, and.watch. -
org.smallmind.file.jailedexportsorg.smallmind.file.jailedand re-exportsorg.smallmind.nutsnbolts(requires transitive), whoseContextFactorytypes appear in its public signatures. JAXB isrequires static jakarta.xml.bind: if you unmarshalRootedFileSystemContextfrom XML on a module path, requirejakarta.xml.bindyourself or add it with--add-modules. The package is opened tojakarta.xml.bindfor that unmarshalling.
The ephemeral provider is a complete NIO file system backed entirely by heap memory, with built-in pass-through to a native provider for paths the configuration does not claim.
-
Serves a single
EphemeralFileSysteminstance per provider, with oneEphemeralFileStoreof configurable total capacity and block size. -
Recognises a configurable set of path prefixes (roots) and routes any path that matches one of them through the in-memory heap tree.
-
Wraps every other path in a
NativePathadapter that delegates to the native provider captured at construction. From the caller’s perspective,Paths.get(…)returns a seamlessPathregardless of whether it resolves to heap or disk. -
Implements the full
SeekableByteChannel,DirectoryStream, andSecureDirectoryStreamcontracts against the heap, soFiles.newByteChannel,Files.newDirectoryStream, andFiles.walkFileTreeall work. -
Implements
FileChannelfor ephemeral paths, soFileChannel.openworks as well asFiles.newByteChannel, including the positionalread/writeoverloads andtransferTo/transferFrom. -
Supports symbolic links and hard links:
createSymbolicLink,readSymbolicLink, andcreateLink, withNOFOLLOW_LINKShonoured throughout and link cycles reported rather than recursed. A hard link is a secondFileNodeover oneHeapFileContent, so both names report the samefileKey,Files.isSameFileagrees, and the content outlives the deletion of either name. -
Enforces the configured capacity. A write past it fails with an
IOException, andgetUsableSpace()/getUnallocatedSpace()report what is genuinely left. -
Resolves relative paths against a configurable working directory, so a relative path is served from the heap rather than silently reaching the real disk.
-
Implements
WatchServiceagainst heap events (HeapEvent→WatchEvent.Kindtranslation), soFiles.newWatchService()produces a working in-memory watcher with the same per-directory, non-recursive scope a platform watcher has. -
Closes what it opened.
EphemeralFileSystem.close()closes every channel, directory stream, and watch service obtained through the file system, asFileSystem.close()requires, so a caller still holding one is told it is gone rather than operating on an abandoned heap. -
Exposes a
clear()method on bothEphemeralFileSystemandEphemeralFileStorethat drops every node, useful for test teardown.
-
No POSIX permission model. The only
FileAttributeaccepted bycreateDirectoryandnewByteChannelis"posix:permissions", and even that is validated only by name — the value is not stored or enforced. Only thebasicattribute view is advertised. -
No
AsynchronousFileChannelsupport for ephemeral paths; that method exists only to delegate to the native provider when given aNativePath. -
No memory mapping.
EphemeralFileChannel.map(…)throwsUnsupportedOperationException, because content is held as a list of segments and noMappedByteBuffercan be produced over it. -
No file locking across processes.
EphemeralFileChannel.lock(…)returns a validFileLock, but the heap is private to one JVM so there is nothing to arbitrate with. -
No
UserPrincipalLookupServicebacking store. Lookups return freshEphemeralUserPrincipal/EphemeralGroupPrincipalinstances on every call. -
Not a security boundary. The ephemeral provider offers no access control of its own; use the jailed provider on top if path-space containment is required.
| Class / interface | Role |
|---|---|
|
Entry point. Manages a single |
|
The |
|
Immutable configuration carrier: capacity, block size, roots, and
working directory. The no-arg constructor reads system properties; an
explicit constructor accepts the values directly and
|
|
The heap file store. Implements every mutating and attribute-reading
operation exposed by the provider ( |
|
The heap-resident |
|
Adapter |
|
|
|
Typed attribute view for the file store. Attribute values are read by
reflection against declared fields (see
|
|
|
|
Channel over the |
|
|
|
Trivial |
|
Glob-to-regex translator and the compiled-regex-backed |
|
URI validation ( |
The heap subpackage, org.smallmind.file.ephemeral.heap, owns the
internal data structures:
| Class | Role |
|---|---|
|
Abstract base for tree nodes. Holds the parent reference, the node
name, the |
|
Map of child names to child nodes. |
|
Leaf node referring to a |
|
Leaf node holding the raw, unresolved target of a symbolic link. The target may be relative, and may not exist — a dangling link is legal, so resolution happens at lookup time. |
|
Segmented byte storage addressed by absolute position, with no cursor of its own. Grows on demand, zero-fills a gap left by a write past the end, zeroes a truncated tail so later growth cannot expose stale bytes, and counts the names referring to it so a hard-linked file survives the deletion of one of them. |
|
The accounting contract |
|
Enum with three constants, |
|
|
|
Callback interface invoked during |
|
Enum whose three constants ( |
The watch subpackage, org.smallmind.file.ephemeral.watch, ties the
heap events back to NIO’s WatchService:
| Class | Role |
|---|---|
|
|
|
|
|
|
|
Bridge from |
EphemeralFileSystemConfiguration is immutable, and has two
constructors plus one derivation:
// reads system properties; falls back to defaults
public EphemeralFileSystemConfiguration ();
// explicit; the working directory becomes the first root
public EphemeralFileSystemConfiguration (long capacity,
int blockSize,
String... roots);
// a copy with a different working directory
public EphemeralFileSystemConfiguration withWorkingDirectory (String workingDirectory);|
Note
|
The working directory is set through |
The four knobs are:
| Knob | Default | Notes |
|---|---|---|
|
|
An enforced ceiling on the bytes of file content the store will
hold. |
|
|
The size of each segment |
|
|
The set of subtrees served from the heap. A root must start with
|
|
the first root |
The absolute directory relative paths resolve against, the ephemeral
counterpart of |
The no-arg constructor reads:
org.smallmind.file.ephemeral.configuration.capacity = <long>
org.smallmind.file.ephemeral.configuration.blockSize = <int>
org.smallmind.file.ephemeral.configuration.roots = <comma-separated
list, optionally
bracketed>
org.smallmind.file.ephemeral.configuration.workingDirectory = <absolute path>For roots, both "/opt/tmp,/var/scratch" and "[/opt/tmp, /var/scratch]"
are accepted; entries that do not start with "/" are prefixed with one
automatically.
To replace the platform file: provider:
-Djava.nio.file.spi.DefaultFileSystemProvider=org.smallmind.file.ephemeral.EphemeralFileSystemProvider
-Dorg.smallmind.file.ephemeral.configuration.roots=/opt/overlay,/var/scratch
# plus any of:
-Dorg.smallmind.file.ephemeral.configuration.capacity=1073741824
-Dorg.smallmind.file.ephemeral.configuration.blockSize=4096
-Dorg.smallmind.file.ephemeral.configuration.workingDirectory=/opt/overlay|
Important
|
An explicit The reason is that the platform reads its own configuration through
The check runs only when this class is actually named in
|
When the JVM bootstraps the default file system through this property,
it calls the EphemeralFileSystemProvider(FileSystemProvider)
constructor, passing the platform file: provider. The resulting
provider:
-
reports
getScheme() == "file", -
answers
isDefault() == true, -
captures the platform provider’s root file system in its
nativeFileSystemfield, and -
routes every non-matching path through that captured file system.
From the application’s perspective, Paths.get("/opt/overlay/foo") is
an EphemeralPath while Paths.get("/etc/hosts") is a NativePath
wrapping the platform provider’s path — both returned by the same
FileSystems.getDefault().getPath(…) call.
The same holds on Windows, where a native absolute path carries a drive
or UNC prefix instead of a leading separator:
Paths.get("C:\\Program Files\\…") is a NativePath, while
Paths.get("/opt/overlay/foo") is an EphemeralPath. The heap
namespace is rooted at / on both platforms, which means test code
addresses it identically everywhere; the corollary is that an ephemeral
path is not a valid native path string on Windows, so
new java.io.File(ephemeralPath.toString()) will not find it —
java.io.File bypasses NIO altogether.
|
Note
|
|
The test in the source tree shows the smallest realistic loop:
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.smallmind.file.ephemeral.EphemeralFileSystem;
import org.smallmind.file.ephemeral.EphemeralFileSystemProvider;
public class Demo {
public static void main (String[] args)
throws Exception {
EphemeralFileSystemProvider.waitForInitialization(30, TimeUnit.SECONDS); (1)
Path real = Paths.get("C:\\Users\\david\\Documents\\response.txt"); (2)
System.out.println(Files.isRegularFile(real));
System.out.println(Files.readString(real, StandardCharsets.UTF_8));
Path eph = Paths.get("/opt/epicenter/twimble/farkle"); (3)
Files.createDirectories(eph);
try (SeekableByteChannel bc = Files.newByteChannel(
eph.resolve("sparkle.txt"),
Set.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE))) {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.put("Hello out there!".getBytes(StandardCharsets.UTF_8));
bb.flip();
bc.write(bb);
}
System.out.println(new String(Files.readAllBytes(eph.resolve("sparkle.txt"))));
((EphemeralFileSystem)FileSystems.getDefault()).clear(); (4)
}
}-
Blocks until the default-provider constructor has built the heap file system. Safe to call even when you are not using the default-provider install; it simply returns immediately.
-
A path that does not match any configured root. Wrapped in a
NativePathand forwarded to the real platform provider. -
A path under a configured root (or under
"/"by default). Served entirely from heap. Notice that from `Files’ point of view the two paths are indistinguishable. -
Drops every node. Useful at the end of a test, or between test methods, to reset the store to an empty state.
The ephemeral provider is perfectly usable as a secondary file system.
Construct one directly and obtain paths through its getPath(…):
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.smallmind.file.ephemeral.EphemeralFileSystemProvider;
EphemeralFileSystemProvider provider = new EphemeralFileSystemProvider("overlay");
FileSystem fs = provider.getFileSystem(URI.create("overlay:///"));
Path p = fs.getPath("/scratch/demo.txt");
Files.createDirectories(p.getParent());
Files.writeString(p, "hello");The scheme ("overlay" here) is decoupled from "file", so nothing
touches the default provider and the two can coexist in the same JVM.
Note that when constructed via the no-arg or String-scheme constructor
the provider has no native file system captured, so any path that does
not match a configured root will cause a NullPointerException the
moment the provider tries to delegate. Mix-mode usage requires the
EphemeralFileSystemProvider(FileSystemProvider) form.
The watch service is a full NIO WatchService:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
public void watch (Path root)
throws Exception {
Files.createDirectories(root);
try (WatchService watcher = root.getFileSystem().newWatchService()) {
root.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); (1)
// ... in another thread ...
Files.writeString(root.resolve("new.txt"), "hello"); (2)
WatchKey key = watcher.take(); (3)
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.kind() + " " + event.count());
}
key.reset(); (4)
}
}-
Registration creates a fresh
EphemeralHeapEventListenerbound to the watched path and attaches it to the directory’sDirectoryNode. The first registration per path attaches the listener; the last cancel detaches it. -
Any mutation to an entry of the watched directory fires the listener, which forwards the event to the service together with the changed path. A change deeper in the tree does not, exactly as with a platform watch service. The service translates the event type to a
WatchEvent.Kind(ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY) and dispatches to the registered keys withwatchedPath.relativize(changedPath)as the context. -
take()blocks on the service’s ready queue. A mid-waitclose()enqueues a sentinel, so the waiting thread raisesClosedWatchServiceExceptionat once rather than hanging. -
Forget to call
reset()and the key will never be signalled again. If events arrived while the key was being processed,reset()requeues it immediately so it is returned by the nexttake().
Whenever a Path reaches any provider method, the provider performs
three checks in this order:
-
The path’s file system must be an
EphemeralFileSystem. If not, aProviderMismatchExceptionis thrown with an explanatory message. This is the common failure mode when a caller mixes paths obtained from different providers. -
If the path is a
NativePath, the operation is forwarded verbatim to the native provider’s implementation of the same operation, using the wrapped native path. Return values (including directory stream iterators and attribute views) come back from the native provider unchanged; they are not re-wrapped as ephemeral types. -
Otherwise the path is treated as an
EphemeralPath, normalised, and passed to theEphemeralFileStorefor the actual operation.
For two-argument operations (copy, move, isSameFile) both paths
must be associated with an EphemeralFileSystem; otherwise
ProviderMismatchException is raised. Cross-provider copies (ephemeral
→ native and vice versa) must be performed through
Files.copy(InputStream, Path) / Files.copy(Path, OutputStream)
rather than Files.copy(Path, Path).
The NativePath adapter is the seam that makes default-provider
installation feel transparent. NativePath.getFileSystem() reports the
ephemeral file system so that NIO type checks pass, but every structural
operation (getRoot, resolve, normalize, toUri, compareTo,
startsWith, endsWith, etc.) delegates to the wrapped native path.
The jailed provider takes an existing native file system and serves it
to callers as if its root were some other configured directory on that
file system. Absolute paths under the jail look like "/foo/bar"; the
provider translates them to
<configured-root>/foo/bar on the native side before delegating.
-
Serves a single
JailedFileSysteminstance per provider under thejailed:URI scheme by default (or any scheme supplied explicitly). -
Translates every path supplied to any provider method into a native path via a
JailedPathTranslator, and forwards the operation to the native provider. -
For listing operations, wraps returned native paths back into
JailedPathinstances viatranslator.wrapPath(…), which throwsSecurityExceptionif the native path escapes the jail. -
Exposes two translator strategies out of the box:
RootedPathTranslator(fixed native root) andContextSensitiveRootedPathTranslator(native root read from a thread-boundRootedFileSystemContext). -
Clamps
..at the jail root during normalization, so no amount of parent traversal walks out of the jail, and resolves a relative jailed path against the jail root. -
Validates every name element as a single legal name on the native file system. A NUL character is always refused; when the native file system is backslash-separated, so are embedded separators, drive qualifiers, trailing dots or spaces, and the reserved device names (
CON,PRN,AUX,NUL,CONIN$,CONOUT$, andCOM0–COM9/LPT0–LPT9). -
Refuses to follow a symbolic link out of the jail under
JailPolicy.STRICT, the default. See Jail policy: structural versus real-path confinement. -
Confines watch registrations.
JailedFileSystem.newWatchService()returns aJailedWatchServicewhose keys and events are expressed in jail space, andJailedPath.register(…)works. -
Matches globs in jail space.
getPathMatcher("glob:…")and("regex:…")return aJailedPathMatcherthat treats/as the separator regardless of the native platform. -
Creates a symbolic link with its target expressed relative to the link’s own directory, which keeps the jail’s real location out of the link and makes the link resolve to the confined target.
-
No defence against a link substituted between the check and the operation it guards.
JailPolicy.STRICTverifies before it forwards, so a link swapped in during that window would not be caught — a race inherent to confining by path rather than by file descriptor, and one only the operating system can close. What the policy does guarantee is that a link already in place is not followed out of the jail. -
No in-jail file store abstraction.
FileStorequeries delegate to the native provider. -
No jail-level quota, audit, or interception hooks. The translator answers a single question — "is this path inside the jail?" — and everything else is native behaviour.
| Class / interface | Role |
|---|---|
|
Entry point. Manages a single |
|
|
|
Custom |
|
Strategy interface: |
|
Enum choosing how rigorously the boundary is enforced: |
|
Base class providing reusable |
|
Glob-to-regex translator and the compiled-regex-backed |
|
Watch-service adapters over the native watch service. A registration
translates and confines its path exactly as any other operation does,
and the key, its |
|
Fixed-root translator. The native root is passed at construction and never changes. |
|
Per-call-root translator. Reads a |
|
JAXB-annotated |
|
Static URI validation and conversion helpers, mirroring
|
The translator interface is the policy boundary for the jail. The module ships two implementations:
Both implementations take an optional JailPolicy; omitting it selects
JailPolicy.STRICT.
A single native root decided at construction time. Appropriate when the
jail boundary is known when the translator is created and never needs
to change. The root must be non-null, absolute, and owned by the
native file system, and is normalized on the way in:
import java.nio.file.FileSystems;
import java.nio.file.Path;
import org.smallmind.file.jailed.JailedFileSystemProvider;
import org.smallmind.file.jailed.RootedPathTranslator;
Path nativeRoot = FileSystems.getDefault().getPath("/var/lib/tenant-42");
JailedFileSystemProvider provider =
new JailedFileSystemProvider("jailed", new RootedPathTranslator(nativeRoot));A JailedPath.resolve("/etc/passwd") through this provider will
translate to /var/lib/tenant-42/etc/passwd on the native side — which
either resolves to a file that tenant has deliberately placed there or
to NoSuchFileException. What it never resolves to is the real
/etc/passwd, because RootedPathTranslator.unwrapPath(jailedPath)
appends segments to nativeRoot rather than treating them as absolute.
To trade the link check for speed, name the policy explicitly:
new RootedPathTranslator(nativeRoot, JailPolicy.LENIENT)Both policies apply the same structural confinement — .. clamped at
the root, each name element validated, and the assembled native path
verified to lie beneath the root. They differ in whether the real
location of that path is checked as well.
| Policy | Behaviour |
|---|---|
|
The default. The deepest existing ancestor of the translated path is
resolved with |
|
Structural confinement only, and no I/O at all. Cheaper, but a link (or a Windows junction or other reparse point) that lives inside the jail and points outside of it will be followed out by the native file system. Choose it only when the contents of the jail are trusted, or when the native file system has no notion of links. |
Under STRICT, passing LinkOption.NOFOLLOW_LINKS excludes the final
name element from the check, so an escaping link may still be deleted or
have its own attributes read — only reading through it is refused.
The native root is read on every call from a thread-bound
RootedFileSystemContext. Appropriate when the same provider must serve
different tenants, sessions, or request scopes in the same JVM:
import java.nio.file.FileSystems;
import org.smallmind.file.jailed.ContextSensitiveRootedPathTranslator;
import org.smallmind.file.jailed.JailedFileSystemProvider;
import org.smallmind.file.jailed.RootedFileSystemContext;
import org.smallmind.nutsnbolts.context.ContextFactory;
JailedFileSystemProvider provider =
new JailedFileSystemProvider(
"jailed",
new ContextSensitiveRootedPathTranslator(FileSystems.getDefault()));
// later, at request time:
RootedFileSystemContext ctx = new RootedFileSystemContext();
ctx.setRoot("/var/lib/tenant-42");
ContextFactory.pushContext(ctx); (1)
try {
// all jailed-path operations on this thread now translate against
// /var/lib/tenant-42
} finally {
ContextFactory.popContext(RootedFileSystemContext.class); (2)
}-
The push/pop API here is the
smallmind-nutsnboltsContextFactorycontract; consult that module for the exact method names and thread-binding semantics. -
If the context is missing or its
getRoot()isnullwhen a jailed-file-system operation runs,ContextSensitiveRootedPathTranslatorthrowsSecurityExceptionwith the message"No authorization for path". The jail fails closed.
The context-sensitive translator is the recommended pattern for services
that handle multiple tenants, users, or request scopes through one
JailedFileSystemProvider. The typical shape is:
-
A request-scoped interceptor (servlet filter, Jersey filter, RPC request handler, …) resolves the authorised native root for the current caller.
-
The interceptor pushes a
RootedFileSystemContextwith that root onto theContextFactorystack. -
Business logic performs
Files.*operations onJailedPathinstances. Each call hitsunwrapPath(…), which consults the context, and produces an absolute native path anchored at the request’s root. -
The interceptor pops the context on request completion. Any subsequent operation without a context fails closed with
SecurityException.
Because the context is consulted per call, the caller never has to manage a file-system instance per tenant; the single provider serves all of them.
The no-arg JailedFileSystemProvider() is what the SPI instantiates
when the artifact is on the classpath. It calls:
this("jailed", new ContextSensitiveRootedPathTranslator(FileSystems.getDefault()));That means just dropping file-jailed on the classpath registers a
jailed: provider whose root must be supplied at call time via a
RootedFileSystemContext. Without a context in scope, every call fails
with SecurityException.
A service that wants different defaults — a fixed root, a different
scheme, a non-default native file system — must construct and register
its own JailedFileSystemProvider explicitly. The SPI-installed
default is intentionally useless without a context: fail-closed is the
safer initial state.
Using RootedPathTranslator with a fixed root:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.smallmind.file.jailed.JailedFileSystemProvider;
import org.smallmind.file.jailed.RootedPathTranslator;
public class JailedDemo {
public static void main (String[] args)
throws Exception {
Path root = FileSystems.getDefault().getPath("/var/lib/tenant-42"); (1)
Files.createDirectories(root);
JailedFileSystemProvider provider =
new JailedFileSystemProvider("jailed", new RootedPathTranslator(root)); (2)
FileSystem fs = provider.getFileSystem(URI.create("jailed:///")); (3)
Path inside = fs.getPath("/reports/2026/q2.csv"); (4)
Files.createDirectories(inside.getParent());
Files.writeString(inside, "col1,col2\n1,2\n");
Path escapeAttempt = fs.getPath("/../../etc/passwd"); (5)
try {
Files.readAllBytes(escapeAttempt);
} catch (SecurityException ignored) {
// expected: translator rejects the attempt on wrap/unwrap
}
}
}-
The native root. Whatever this directory contains is what the jail exposes under
/. -
Construct the provider with a fixed-root translator.
-
The
URIhere must be"jailed:///"— scheme matches, authority is absent, path is exactly"/", no query, no fragment (seeJailedURIUtility.checkUri). -
Creating a directory and writing a file inside the jail — the
Files.*calls see a straightforward absolute path; the translator converts it to/var/lib/tenant-42/reports/2026/q2.csvon the way into the native provider. -
Attempting to escape.
..segments are not expanded by the translator itself; normalisation happens on the native side, and if the native path falls outside the root,wrapPath’s `startsWithcheck rejects it when the result of a listing iterator needs to be re-wrapped. In practice the escape surface is the set of places wherewrapPathruns — primarily directory listings and any caller that passes a native path back through.
|
Note
|
The translator’s |
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import org.smallmind.file.ephemeral.EphemeralFileSystem;
import org.smallmind.file.ephemeral.EphemeralFileSystemProvider;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
public class FooTest {
private EphemeralFileSystemProvider provider;
private FileSystem fs;
@BeforeClass
public void setup () {
provider = new EphemeralFileSystemProvider("test");
fs = provider.getFileSystem(URI.create("test:///"));
}
@AfterMethod
public void resetHeap () {
((EphemeralFileSystem)fs).clear();
}
// tests use fs.getPath(...) freely; each test starts with an empty heap.
}Mount an in-memory scratch area at /opt/scratch while leaving
everything else on real disk. Start the JVM with:
-Djava.nio.file.spi.DefaultFileSystemProvider=org.smallmind.file.ephemeral.EphemeralFileSystemProvider
-Dorg.smallmind.file.ephemeral.configuration.roots=/opt/scratch
-Dorg.smallmind.file.ephemeral.configuration.capacity=2147483648Paths.get("/opt/scratch/session-123/state.bin") is now an ephemeral
path, served from heap, with all NIO operations including watch
available. Paths.get("/etc/hosts") still reads the real file.
Request handler pseudocode, using the context-sensitive translator installed by the SPI default:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.smallmind.file.jailed.RootedFileSystemContext;
import org.smallmind.nutsnbolts.context.ContextFactory;
public void handleUpload (String tenantId, String relativePath, byte[] bytes)
throws IOException {
RootedFileSystemContext ctx = new RootedFileSystemContext();
ctx.setRoot("/var/lib/tenants/" + tenantId);
ContextFactory.pushContext(ctx);
try {
FileSystem fs = FileSystems.getFileSystem(URI.create("jailed:///"));
Path target = fs.getPath("/").resolve(relativePath).normalize(); (1)
Files.createDirectories(target.getParent());
Files.write(target, bytes);
} finally {
ContextFactory.popContext(RootedFileSystemContext.class);
}
}-
Normalise inside the jail so that
..sequences collapse within theJailedPathbefore the translator sees them. Combined with a symlink-free tenant root, this is the minimum precaution against path-traversal escapes.
EphemeralFileSystem.getPath(first, more) decides between
EphemeralPath and NativePath in three steps:
-
A
/-rooted path is claimed when it equals a configured root or lies beneath one on a segment boundary, so/overlayclaims/overlayand/overlay/abut not/overlayed. -
A path that is absolute in the native namespace is never claimed, whatever the roots say.
-
Anything genuinely relative is claimed when the working directory is claimed.
|
Warning
|
Rule 2 is not a nicety. A Windows path such as |
The rule is applied in two places, deliberately.
EphemeralFileSystem.getPath(…) puts the question of what makes a
path absolute to the native file system itself, so no platform’s
spelling of a root has to be recognized in this code.
EphemeralFileSystemConfiguration.isOurs(…) also applies a syntactic
test for a drive qualifier or a UNC prefix, performing no I/O, so that a
caller asking the configuration directly gets the same answer — and so
that the test is safe to run while FileSystems is still resolving its
default provider.
EphemeralOverlayRoutingTest pins this matrix using literal
Linux-shaped and Windows-shaped path strings, so the whole decision is
exercised on either platform.
EphemeralFileSystem.close() is a no-op when the file system is
installed as the default provider (isDefault() == true) — the default
file system cannot be closed. Otherwise it closes every channel,
directory stream, and watch service opened through the file system, and
then marks the file system closed.
Each resource is tracked from the moment it is handed out until it
closes itself, so a caller who uses try-with-resources costs nothing
here. The ordering matters, and it favours the stronger guarantee: the
closed flag is set before any resource is swept, so a thread racing to
open another one is refused rather than slipping a channel past the
sweep. The cost is that a resource needing the heap on its way out — a
channel opened with DELETE_ON_CLOSE has a deletion to perform — finds
it already gone. That is moot, since the heap is being discarded whole,
and those resources tolerate it rather than failing.
Every resource is closed even if an earlier one fails, so one bad channel cannot strand the rest.
After the call:
-
a channel reports
isOpen() == falseand raisesClosedChannelException; -
a directory stream raises
ClosedDirectoryStreamException; -
a watch service raises
ClosedWatchServiceException; -
anything reaching the file store raises
ClosedFileSystemException.
close() is idempotent, and declares IOException: if a resource fails
to close, the first failure is thrown with any others attached as
suppressed exceptions, after every resource has been given its turn.
The registry holds its entries weakly. A caller who abandons a channel
without closing it has leaked it already, and a long-lived default file
system should not compound that by holding the remains for the life of
the JVM. The corollary is that an abandoned channel may be collected
before close() ever sees it, so a DELETE_ON_CLOSE deletion is only
guaranteed for a channel that is actually closed — by its caller or by
the file system.
-
Registration installs a heap listener on the watched directory. Registering the same directory again returns the same key with its event kinds replaced, as
Watchable.registerspecifies, rather than handing out a second key for one directory. -
Watching is per directory and not recursive. Heap mutations performed through the file store and the channels (
createDirectory,delete,copy,move,newByteChannelwithCREATE/CREATE_NEW/TRUNCATE_EXISTING, channelwrite/truncate) fire on the directory that contains the changed entry and on no other, so a key registered on/asays nothing about/a/b/c.txt. TheWatchEvent.context()is the path relative to the watched directory. -
Deleting a watched directory invalidates its key.
-
Polling delegates straight to the underlying queue.
close()enqueues a sentinel, so a thread already blocked intake()orpoll(timeout, unit)raisesClosedWatchServiceExceptionat once. -
A key’s pending-event queue is bounded at 512. Once it is full a single
OVERFLOWevent replaces what could not be kept, so a consumer that has fallen behind is told so. -
A
WatchKeythat is fired while already signalled does not re-queue; subsequent fires are still added to the key’s event queue. Consumers who neglect to callreset()afterpollEvents()silently stop receiving signals for that key.
EphemeralFileStore.copy(source, target, options) and
move(source, target, options) both follow java.nio.file.Files
semantics: the target is the destination itself, never a container to
place the source inside. Both:
-
treat a target that already exists as an error unless
REPLACE_EXISTINGwas given, and refuse to replace a directory that is not empty (DirectoryNotEmptyException); -
require the target’s parent to exist (
NoSuchFileException); -
treat
sourceandtargetnaming the same file as a no-op; -
name the result from the target’s final name.
They differ in what they do with the source:
copy-
Duplicates a file’s content into a fresh
HeapFileContent, charged against the capacity as a new allocation. A directory is copied as an empty directory —Files.copycopies one entry, and walking a tree is the caller’s job.COPY_ATTRIBUTEScarries the timestamps over. UnderNOFOLLOW_LINKSa symbolic link is copied as a link.ATOMIC_MOVEis rejected withUnsupportedOperationException. move-
Re-parents the existing node through
HeapNode.relink(…), so a directory arrives with its whole subtree intact and the cost does not depend on how much lives beneath it. A symbolic link is moved as a link, not as its target. Moving a directory beneath itself, or moving the root, is refused.ATOMIC_MOVEis accepted: a re-parent under the store’s write lock already is atomic.
getTotalSpace() reports the configured capacity; getUsableSpace()
and getUnallocatedSpace() report it less the bytes currently held by
file content. Only file content is charged — directories and links are
not — and the count is maintained as content grows and shrinks rather
than by walking the tree, so a stat call is not O(tree).
A write that would exceed the capacity fails with an IOException and
changes nothing. Space is returned when a file is truncated or deleted;
for a hard-linked file, only when the last name for it goes.
-
findNodefollows symbolic links, and a link in any position but the last is always followed, because the elements after it have to be resolved somewhere.LinkOption.NOFOLLOW_LINKSapplies to the final element only. -
Resolution is bounded at 40 links. Beyond that a
FileSystemExceptionreports"Too many levels of symbolic links"rather than exhausting the stack. -
A relative link target is interpreted against the directory holding the link, not against the working directory.
-
A dangling link is legal:
createSymbolicLinkdoes not require the target to exist. -
deleteremoves a link rather than following it. -
Hard links share one
HeapFileContent, so both names report the samefileKeyandFiles.isSameFilereturnstruefor them. Deleting one name leaves the content reachable through the other.
Every cross-path operation on a JailedPath (startsWith, endsWith,
resolve, relativize, compareTo) requires the other argument to
be a JailedPath. A foreign Path raises ProviderMismatchException
with no message. This is a stricter contract than the JDK’s default
Path types; be careful when mixing JailedPath with paths returned
from other file systems.
AbstractJailedPathTranslator.asNativeName(String) vets every name
element before it is appended to the native root, so a name can never
contribute structure of its own. A NUL character is refused on every
platform. When the native file system is backslash-separated, so are
embedded separators, drive qualifiers, trailing dots or spaces, and the
reserved device names (CON, PRN, AUX, NUL, CONIN$, CONOUT$,
and COM0–COM9 / LPT0–LPT9). Each rejection is a
SecurityException naming the offending element.
The practical consequence is that a jailed path which is perfectly legal on Linux may be refused on Windows. Names that are portable in the first place are accepted everywhere.
JailedFileSystem.newWatchService() returns a JailedWatchService
wrapping the native watch service. Registering a JailedPath translates
and confines it exactly as any other operation would, so a registration
cannot be used to observe a directory outside the jail. The key handed
back is a JailedWatchKey whose watchable() is the jailed path, and
every event context is expressed in jail space, so a caller never sees a
native path. JailedPath.register(…) requires a JailedWatchService
and raises ProviderMismatchException for any other watcher.
JailedFileSystemProvider.getFileStore(Path),
readAttributes(…), getFileAttributeView(…), and
setAttribute(…) all translate the path and forward to the native
provider. The returned FileStore / FileAttributeView /
BasicFileAttributes instances are the native types, not
jail-specific wrappers. Callers who need jail-scoped attributes (for
example, a file size that is relative to an accounting quota, not the
native store’s total capacity) must wrap the returned values
themselves.
ProviderMismatchException-
Thrown whenever an operation receives a
Pathwhose file system is not anEphemeralFileSystem. The message identifies the offending path and the expected class. Two-argument operations (copy,move,isSameFile) also raise this exception when the two paths belong to differentEphemeralFileSysteminstances, with the message"The source and target are associated with different file systems". ClosedFileSystemException-
Thrown by
EphemeralFileStore,EphemeralFileSystem, andEphemeralWatchServicewhenever a post-close method is called. FileSystemAlreadyExistsException-
Always thrown by
EphemeralFileSystemProvider.newFileSystem(URI, Map). The provider pre-constructs the singleton in its constructor; callers must usegetFileSystem(URI)instead.
NoSuchFileException / FileAlreadyExistsException /
DirectoryNotEmptyException::
Standard NIO semantics, produced by EphemeralFileStore for the
matching conditions (missing parent, existing non-REPLACE_EXISTING
target, non-empty directory on delete or directory-target copy).
UnsupportedOperationException-
Raised when a caller passes an open option that is neither a
StandardOpenOptionnor aLinkOptiontonewByteChannel/newFileChannel, an unrecognisedCopyOptiontocopy/move(includingATOMIC_MOVEtocopy), or aFileAttributewhose name is not"posix:permissions"to a creation method. Also raised bynewAsynchronousFileChannelfor an ephemeral path, byEphemeralFileChannel.map(…), by an unsupported attribute-view name, and bygetNativeFileSystem()on a provider constructed without a native provider. IllegalArgumentException-
Raised for an illegal combination of open options (
APPENDwithREAD, orAPPENDwithTRUNCATE_EXISTING), for a negative channel position or size, for an unrecognised attribute name inreadAttributes/setAttribute, and byEphemeralFileSystemConfiguration.checkFitToBeDefaultFileSystem()when the configuration could not serve as the JVM default. IOException-
Raised when a write would exceed the store’s capacity, with a message naming the store and the space remaining.
FileSystemException-
Raised with
"Too many levels of symbolic links"when link resolution exceeds 40 hops, and when a hard link is requested for something other than a regular file. AccessDeniedException-
Raised by
checkAccesswhenAccessMode.EXECUTEis requested for anything but a directory. The heap carries no permission bits, so read and write access is always granted.
SecurityException-
The single failure mode of confinement, raised with a message that identifies which rule was broken:
Message Cause No authorization for pathNo
RootedFileSystemContextis present, or its root isnull.No authorization for path(=X)The path does not lie beneath the jail root — structurally, or, under
JailPolicy.STRICT, once its real location is resolved.Illegal path element(=X)/Illegal character in path elementA name element is not a single legal name on the native file system.
Reserved path element(=X)A name element is a reserved device name on a backslash-separated native file system.
ProviderMismatchException-
Raised by any
JailedPathcross-path operation that receives a non-JailedPathargument. FileSystemAlreadyExistsException-
Always thrown by
JailedFileSystemProvider.newFileSystem(URI, Map). IllegalArgumentException-
Raised by
JailedURIUtilityfor URIs that are not well-formed for the provider (wrong scheme, non-empty authority, path other than"/", any query or fragment), and byJailedPath.relativizewhen the two paths differ in absoluteness. Also raised when a translator is given a root that isnull, not absolute, or not owned by the native file system.
| Setting | Default | Where set |
|---|---|---|
Ephemeral capacity |
|
|
Ephemeral block size |
|
|
Ephemeral roots |
|
|
Ephemeral working directory |
the first root |
|
Ephemeral provider scheme (no-arg) |
|
|
Ephemeral symbolic link resolution limit |
|
|
Ephemeral pending watch events per key |
|
|
Ephemeral open-resource registry |
weak references |
|
Jailed provider scheme (no-arg) |
|
|
Jailed default translator (no-arg) |
|
|
Jailed default policy |
|
|
Jailed failure mode with no context |
|
|
Jailed path separator |
|
|
ProviderMismatchException: The path(X) is not associated with the EphemeralFileSystem-
A
Paththat did not come from anEphemeralFileSystemwas handed to the ephemeral provider. Common cause: mixingjava.nio.file.Paths.get(…)output when the ephemeral provider is not installed as the default with a non-default ephemeral provider instance. Resolve by obtaining paths from the specific file system you intend to use (ephemeralFs.getPath(…)). UnsupportedOperationException: This provider(…) was constructed without a native provider-
A provider constructed with the no-arg or
String-scheme form has no native file system to delegate to, and a path outside the configured roots needs one. Use theEphemeralFileSystemProvider(FileSystemProvider)constructor, or ensure every path matches a configured root. IllegalArgumentException: A root of / claims every path…at JVM start-up-
The provider was named in
java.nio.file.spi.DefaultFileSystemProviderwithout an explicitrootssetting. Add-Dorg.smallmind.file.ephemeral.configuration.roots=/overlay(or whichever subtree you mean to overlay). The same refusal applies to any root that would claimjava.home. See Installing as the JVM default provider. InternalError: Error loading java.security fileat JVM start-up-
The overlay claimed the platform’s own files, so
SecureRandomcould not readjava.security. If you see this, the configuration got past the check above — most likely because the roots are ephemeral-shaped but still cover the JDK (sayroots=/usron Linux). Narrow the roots. ProviderMismatchExceptionfrom an operation on a path derived from a native one-
Only possible when mixing path kinds by hand. Paths derived from a
NativePathstay native —resolve,resolveSibling, andrelativizeare all overridden to keep them so — but a path built independently throughfileSystem.getPath(…)may be anEphemeralPath. Derive from the path you already hold rather than re-parsing its text. EphemeralFileSystemoperations hang at startup under the default-provider install-
Some thread is calling
FileSystems.getDefault()(orPaths.get(…)) before the provider constructor has completed. CallEphemeralFileSystemProvider.waitForInitialization(timeout, unit)from your startup path, or sequence your initialization so the provider constructs before concurrent callers run. SecurityException("No authorization for path")in an apparently simple jailed call-
The current thread has no
RootedFileSystemContextin the context stack, or the context’s root isnull. Push a context before the operation, and guarantee the push happens even when an exception is thrown by the path-setup code — the whole point ofSecurityExceptionhere is that the jail fails closed. SecurityException("Illegal path element(=X)")for a name that works on Linux-
The native file system is backslash-separated and the name is not a legal Windows name — it embeds a separator or a drive qualifier, ends in a dot or a space, or is a reserved device name such as
CON. Use portable names, which are accepted on every platform. SecurityException("No authorization for path(=X)")on a path that looks inside the jail-
Under
JailPolicy.STRICTa symbolic link within the jail that resolves outside of it is refused rather than followed. That is the policy working. If the link is legitimate, either bring its target inside the jail or, having weighed the consequence, construct the translator withJailPolicy.LENIENT. JailedPathoperations reach a file outside the jail-
The translator was constructed with
JailPolicy.LENIENT, which applies structural confinement only and will follow a link out of the jail. Use the defaultJailPolicy.STRICT, and note that evenSTRICTcannot close the window between its check and the operation it guards — see Jail policy: structural versus real-path confinement. IllegalArgumentException("Path component should be '/'")when obtaining aJailedFileSystem-
getFileSystem(URI)was called with a URI other than"jailed:///". The path component of the URI must be exactly"/". Paths within the jail are built withfs.getPath(…), not URIs.
- No
AsynchronousFileChannel, and no memory mapping, for ephemeral paths -
newAsynchronousFileChannelthrowsUnsupportedOperationExceptionunless the path is aNativePath, andEphemeralFileChannel.map(…)always does: content is a list of segments, and noMappedByteBuffercan be produced over it. Code that needs mapped access must read the content into heap itself.FileChannel.openitself is supported. - Ephemeral attribute model is deliberately shallow
-
Only the
basicview is supported.posix,dos,owner, andaclviews are not implemented.setAttributerecognises onlycreationTime,lastModifiedTime, andlastAccessTime; any other name raisesIllegalArgumentExceptionrather than being ignored. - Ephemeral paths are POSIX-shaped on every platform
-
The heap namespace is rooted at
/on Windows as well as Linux, which is what lets the same test address it identically on both. The corollary is that an ephemeral path is not a valid native path string on Windows, so handingpath.toString()tojava.io.File, to a native process, or to any API that bypasses NIO will not find the file. - Jailed confinement is by path, not by descriptor
-
JailPolicy.STRICTverifies a path before forwarding the operation it guards, so a link substituted in between would not be caught. Closing that window requires descriptor-relative system calls the JDK does not expose. A link already in place is reliably refused. - Jailed name validation is platform-dependent
-
A name element legal on Linux may be refused on a backslash-separated native file system. This is deliberate — the alternative is letting a name contribute path structure of its own — but it does mean a jail is not equally permissive everywhere.
- Single-instance per provider
-
Both providers hold exactly one
FileSysteminstance. Multiple jails or multiple ephemeral overlays in the same JVM require multiple provider instances, each constructed by the application (not through the default SPI registration).
smallmind-file supplies two small, complete java.nio.file file
system implementations that fill two concrete gaps in the JDK:
-
file-ephemeralgives you an in-memoryFileSystemwith native pass-through, links, seekable and file channels, enforced capacity, and watch support, installable as the JVM default for transparent overlay behaviour or usable side-by-side with the platform provider for tests and scratch areas. -
file-jailedgives you a chroot-styleFileSystemon top of an existing native one, with a pluggable translator strategy that supports both fixed-root and per-request root selection, and aJailPolicythat decides whether a symbolic link may be followed out of the jail.
Both modules integrate through the standard Paths, Files, and
FileSystems APIs and depend on nothing outside smallmind-nutsnbolts.
Pick whichever one matches the need: heap-speed storage that behaves
like a real file system, or a hard boundary around a subtree of a real
file system.