Class FileGuard

java.lang.Object
com.tnsai.tools.file.FileGuard

public final class FileGuard extends Object
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:

  1. If FileGuardConfig.allowedExtensions() is non-empty, it is the authoritative whitelist (per-tenant or env-driven override).
  2. Otherwise the toolDefaultExtensions supplied at the call site is used (the per-toolkit baseline — e.g. {pdf} for PdfTools).

An empty toolDefaultExtensions and empty config whitelist disables extension filtering — the caller is opting in to "any extension".

  • 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 config
      toolDefaultExtensions - per-toolkit fallback whitelist
      Returns:
      absolute, normalized path safe to read
      Throws:
      SecurityException - if the path escapes the sandbox or has a disallowed extension
      NoSuchFileException - if the file does not exist
      IllegalArgumentException - if the file exceeds FileGuardConfig.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 bytes
      config - governing guardrail config
      toolDefaultExtensions - per-toolkit fallback whitelist
      Returns:
      absolute, normalized path safe to write
      Throws:
      SecurityException - if the path escapes the sandbox or has a disallowed extension
      IllegalArgumentException - if the payload exceeds FileGuardConfig.maxWriteBytes()