Skip to content

Commit 80da89f

Browse files
committed
Add helper method to validate FileLike from a string path
1 parent b342eb8 commit 80da89f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

api/src/org/labkey/vfs/FileSystemLike.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
package org.labkey.vfs;
22

33
import org.labkey.api.collections.CaseInsensitiveHashMap;
4+
import org.labkey.api.data.Container;
5+
import org.labkey.api.pipeline.PipeRoot;
6+
import org.labkey.api.pipeline.PipelineService;
47
import org.labkey.api.util.FileUtil;
58
import org.labkey.api.util.MemTracker;
69
import org.labkey.api.util.Path;
710
import org.labkey.api.util.URIUtil;
11+
import org.labkey.api.view.NotFoundException;
812

913
import java.io.File;
1014
import java.io.FileNotFoundException;
@@ -266,6 +270,45 @@ static Map<String, FileLike> wrapFiles(Map<String, File> files)
266270
}
267271
return ret;
268272
}
273+
274+
/**
275+
* Verify that the provided path is within the Pipeline for the container and is usable as file
276+
* @param container scope and context
277+
* @param filePath to verify
278+
* @return A FileLike object representation of the provided file path relative to the container's pipeline root
279+
*/
280+
static FileLike getVerifiedFileLike(Container container, String filePath)
281+
{
282+
if (filePath == null)
283+
{
284+
throw new IllegalArgumentException("File name is required");
285+
}
286+
287+
File fileToVerify = new File(filePath);
288+
PipeRoot pipeRoot = PipelineService.get().findPipelineRoot(container);
289+
if (pipeRoot == null)
290+
{
291+
throw new NotFoundException("Could not find a pipeline root for '" + container.getPath() + "'");
292+
}
293+
294+
FileLike allowedRoot = pipeRoot.getRootFileLike();
295+
// if root = /a/b/c/ and file = /a/b/c/d/e/f.xlsx, relativeURI = d/e/f.xlsx
296+
// if root = /a/b/c/ and file = /x/y/z.xlsx, relativeURI = null
297+
URI relativeURI = URIUtil.relativize(allowedRoot.toURI(), fileToVerify.toURI());
298+
299+
if (relativeURI == null)
300+
{
301+
throw new IllegalArgumentException("File '" + fileToVerify.toURI().getPath() + "' is outside the allowed root '" + allowedRoot.toURI().getPath() + "'");
302+
}
303+
304+
if (!allowedRoot.isDescendant(fileToVerify.toURI()))
305+
{
306+
throw new IllegalArgumentException("File '" + relativeURI.getPath() + "' is not a descendent of '" + allowedRoot.toURI().getPath() + "'");
307+
}
308+
309+
// if root = /a/b/c/ and file = /a/b/c/d/e/f.xlsx - among other things, this essentially checks if '/a/b/c/d/e/f.xlsx' starts with '/a/b/c/'
310+
return allowedRoot.resolveFile(new Path(relativeURI.getPath()));
311+
}
269312
}
270313

271314

0 commit comments

Comments
 (0)