|
1 | 1 | package org.labkey.vfs; |
2 | 2 |
|
3 | 3 | 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; |
4 | 7 | import org.labkey.api.util.FileUtil; |
5 | 8 | import org.labkey.api.util.MemTracker; |
6 | 9 | import org.labkey.api.util.Path; |
7 | 10 | import org.labkey.api.util.URIUtil; |
| 11 | +import org.labkey.api.view.NotFoundException; |
8 | 12 |
|
9 | 13 | import java.io.File; |
10 | 14 | import java.io.FileNotFoundException; |
@@ -266,6 +270,45 @@ static Map<String, FileLike> wrapFiles(Map<String, File> files) |
266 | 270 | } |
267 | 271 | return ret; |
268 | 272 | } |
| 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 | + } |
269 | 312 | } |
270 | 313 |
|
271 | 314 |
|
0 commit comments