Class: Wsv::PathResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/wsv/path_resolver.rb

Defined Under Namespace

Classes: Result

Constant Summary collapse

INVALID_PATH_CHARS =

RFC 3986 disallows control characters in URL paths. Reject them after percent-decoding so callers cannot smuggle CR/LF, NUL, etc. through.

/[\u0000-\u001f\u007f]/

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ PathResolver

Returns a new instance of PathResolver.



45
46
47
# File 'lib/wsv/path_resolver.rb', line 45

def initialize(root)
  @root = root
end

Instance Method Details

#resolve(raw_path) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/wsv/path_resolver.rb', line 49

def resolve(raw_path)
  decoded = decode(raw_path)
  return Result.error(400) unless decoded

  relative = decoded.sub(%r{\A/+}, "")
  return Result.error(403) if hidden_segment?(relative)

  candidate = File.expand_path(relative, @root)
  return Result.error(403) unless within?(candidate)
  return Result.error(404) unless File.exist?(candidate)

  real = File.realpath(candidate)
  return Result.error(403) unless within?(real)
  return Result.error(403) if hidden_under_root?(real)

  if File.directory?(real)
    return Result.redirect unless decoded.end_with?("/")

    index = File.join(real, "index.html")
    return Result.error(404) unless File.file?(index)

    return Result.file(index)
  end

  return Result.error(404) unless File.file?(real)

  Result.file(real)
rescue Errno::ENOENT, Errno::ELOOP, Errno::EACCES
  Result.error(404)
end