I have two paths: application root path and target path. What is the simplest way to ensure that the target path is the children of application root path?
Basically the target path provided by the user is to be displayed by my server. But I want to constrain my server so only the files under the application root path are displayable. So I want to check that the target path is under the root path.
The root path can contain nested directories.
Another way:
def child?(root, target)
raise ArgumentError, "target.size=#{target.size} < #{root.size} = root.size"\
if target.size < root.size
target[0...root.size] == root &&
(target.size == root.size || target[root.size] == ?/)
end
root = "/root/app"
p child?(root, "/root/app/some/path") # => true
p child?(root, "/root/apple") # => false
p child?(root, "/root/app") # => true
p child?(root, "/root") # => ArgumentError: target.size = 5 < 9 = root.size
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With