Module: OKF::Path

Defined in:
lib/okf/path.rb

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Class Method Details

.join_under!(root, path) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/okf/path.rb', line 23

def self.join_under!(root, path)
  relative = normalize_relative!(path)
  expanded_root = File.expand_path(root.to_s)
  expanded_path = File.expand_path(File.join(expanded_root, relative))
  unless expanded_path == expanded_root || expanded_path.start_with?("#{expanded_root}#{File::SEPARATOR}")
    raise Error, "path escapes bundle root"
  end

  expanded_path
end

.normalize_relative!(path) ⇒ Object

Raises:



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/okf/path.rb', line 8

def self.normalize_relative!(path)
  value = path.to_s
  raise Error, "path is blank" if value.empty?
  raise Error, "path contains null byte" if value.include?("\0")
  raise Error, "path must be relative" if value.start_with?("/")
  raise Error, "path must use forward slashes" if value.include?("\\")

  parts = value.split("/")
  if parts.any? { |part| part.empty? || part == "." || part == ".." }
    raise Error, "path contains unsafe segment"
  end

  parts.join("/")
end