Class: Caruso::SafeFile

Inherits:
Object
  • Object
show all
Defined in:
lib/caruso/safe_file.rb

Defined Under Namespace

Classes: Error, NotFoundError, SecurityError

Class Method Summary collapse

Class Method Details

.read(path, base_dir: nil) ⇒ String

Safely reads a file from the filesystem

Parameters:

  • path (String) —

    The path to the file to read

  • base_dir (String) (defaults to: nil) —

    Optional base directory to restrict access to

Returns:

  • (String) —

    The file content

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/caruso/safe_file.rb', line 18

def self.read(path, base_dir: nil)
  # 1. Sanitize and validate path
  begin
    safe_path = PathSanitizer.sanitize_path(path, base_dir: base_dir)
  rescue PathSanitizer::PathTraversalError => e
    raise SecurityError, "Invalid file path: #{e.message}"
  end

  # 2. Check existence and type
  unless File.exist?(safe_path)
    raise NotFoundError, "File not found: #{path}"
  end

  unless File.file?(safe_path)
    raise NotFoundError, "Path is not a regular file: #{path}"
  end

  # 3. Read content
  File.read(safe_path)
end