Knaph

The Loop16 of 37

Stay in the Folder

In [Tools That Touch Files](tools-that-touch-files) you saw how mini keeps its file tools inside one folder. Here you'll write that check, and the tests try the tricky paths a model might send. ## The input The first line names the working folder, then one path per line, as a model might give them to a tool: ``text root /home/leila/project notes.txt ../secrets.txt /etc/passwd /home/leila/project-old/notes.txt ` ## What to write inside_folder(root, path) returns True if the path stays inside the folder and False if it would leave it. The code below it prints allowed or blocked before each path. For the example above: `text allowed notes.txt blocked ../secrets.txt blocked /etc/passwd blocked /home/leila/project-old/notes.txt ` The rules, the same as mini's inside: - A path is taken relative to the folder, unless it starts with /, in which case it is used as it is. posixpath.join(root, path) does exactly this. - Work out where it really leads with posixpath.normpath, which turns reports/../notes.txt into notes.txt. Normalise root the same way first, since it may end with a slash. - The path is inside if it is the folder itself, or starts with the folder followed by /. Without the slash, /home/leila/project-old would look like it was inside /home/leila/project. - One rule mini doesn't have: block any path that starts with ~. To a person, ~ means a home folder; to join it is just a folder called ~. Either way it isn't what a tool should guess about. Look only at the text of the path, never at the disk: posixpath` doesn't touch files. (That is also this check's limit: a link inside the folder that points outside it would get through. The lesson says what covers that.)

Sign in to try this exercise.