Module: Hlsv::PathGuard

Defined in:
lib/hlsv/path_guard.rb

Overview

Path-traversal guards, meant to be included into Sinatra's helpers do ... end block so halt is available.

Instance Method Summary collapse

Instance Method Details

#resolve_within!(base_dir, relative) ⇒ Object

Stronger check: resolves the path and ensures it stays within base_dir. Use this for anything rooted under a known folder (e.g. hlsv_results/).



23
24
25
26
27
28
29
30
# File 'lib/hlsv/path_guard.rb', line 23

def resolve_within!(base_dir, relative)
  safe_relative_path!(relative)

  base = File.expand_path(base_dir)
  full = File.expand_path(File.join(base, relative))
  halt 403, "Access denied" unless full.start_with?("#{base}#{File::SEPARATOR}")
  full
end

#safe_relative_path!(relative, label: "file") ⇒ Object

Basic anti-traversal check for a user-supplied relative path. Use this when the target base directory varies (e.g. a user-configured data_directory) and can't be constrained to a single root.



15
16
17
18
19
# File 'lib/hlsv/path_guard.rb', line 15

def safe_relative_path!(relative, label: "file")
  halt 400, "Missing #{label} parameter" if relative.nil? || relative.to_s.empty?
  halt 403, "Access denied" if relative.include?('..') || relative.start_with?('/')
  relative
end