Package com.tnsai.tools.file
Class FileGuard
java.lang.Object
com.tnsai.tools.file.FileGuard
Stateless gatekeeper used by every file-touching toolkit in
tnsai-tools.
Each method enforces the same three invariants encoded in
FileGuardConfig: sandbox containment, extension whitelist, and a byte
cap appropriate for the operation. The methods return the absolute, normalized
Path so callers do not re-resolve the input string.
Extension resolution is two-tier:
- If
FileGuardConfig.allowedExtensions()is non-empty, it is the authoritative whitelist (per-tenant or env-driven override). - Otherwise the
toolDefaultExtensionssupplied at the call site is used (the per-toolkit baseline — e.g.{pdf}forPdfTools).
An empty toolDefaultExtensions and empty config whitelist
disables extension filtering — the caller is opting in to "any extension".
-
Method Summary
Modifier and TypeMethodDescriptionstatic PathcheckRead(String path, FileGuardConfig config, Set<String> toolDefaultExtensions) Validates a read request and returns the resolved absolute path.static PathcheckWrite(String path, long bytesToWrite, FileGuardConfig config, Set<String> toolDefaultExtensions) Validates a write request and returns the resolved absolute path.
-
Method Details
-
checkRead
public static Path checkRead(String path, FileGuardConfig config, Set<String> toolDefaultExtensions) throws IOException Validates a read request and returns the resolved absolute path.Performs, in order: sandbox check → existence check → extension check → size check via
Files.size(Path).- Parameters:
path- user-supplied path (relative or absolute)config- governing guardrail configtoolDefaultExtensions- per-toolkit fallback whitelist- Returns:
- absolute, normalized path safe to read
- Throws:
SecurityException- if the path escapes the sandbox or has a disallowed extensionNoSuchFileException- if the file does not existIllegalArgumentException- if the file exceedsFileGuardConfig.maxReadBytes()IOException- if the size probe fails
-
checkWrite
public static Path checkWrite(String path, long bytesToWrite, FileGuardConfig config, Set<String> toolDefaultExtensions) Validates a write request and returns the resolved absolute path. Does not require the file to exist; the caller is expected to create it.Performs, in order: sandbox check → extension check → size check against
bytesToWrite.- Parameters:
path- user-supplied path (relative or absolute)bytesToWrite- payload size in bytesconfig- governing guardrail configtoolDefaultExtensions- per-toolkit fallback whitelist- Returns:
- absolute, normalized path safe to write
- Throws:
SecurityException- if the path escapes the sandbox or has a disallowed extensionIllegalArgumentException- if the payload exceedsFileGuardConfig.maxWriteBytes()
-