-
Notifications
You must be signed in to change notification settings - Fork 694
Add PathFence #805
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
garydgregory
wants to merge
3
commits into
apache:master
Choose a base branch
from
garydgregory:path_fence
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+262
−0
Open
Add PathFence #805
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
161 changes: 161 additions & 0 deletions
161
src/main/java/org/apache/commons/io/file/PathFence.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache license, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the license for the specific language governing permissions and | ||
* limitations under the license. | ||
*/ | ||
|
||
package org.apache.commons.io.file; | ||
|
||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import java.util.Optional; | ||
import java.util.function.Supplier; | ||
import java.util.stream.Collectors; | ||
|
||
/** | ||
* A Path fence guards against using paths outside of a "fence" of made of root paths. | ||
* <p> | ||
* For example, to prevent an application from using paths outside of its configuration folder: | ||
* </p> | ||
* <pre> | ||
* Path config = Paths.get("path/to/config"); | ||
* PathFence fence = PathFence.builder().setRoots(config).get(); | ||
* </pre> | ||
* <p> | ||
* You call one of the {@code apply} methods to validate paths in your application: | ||
* </p> | ||
* <pre> | ||
* // Gets a Path or throws IllegalArgumentException | ||
* Path file1 = fence.{@link #apply(String) apply}("someName"); | ||
* Path file2 = fence.{@link #apply(Path) apply}(somePath); | ||
* </pre> | ||
* <p> | ||
* You can also use multiple roots as the path fence: | ||
* </p> | ||
* <pre> | ||
* Path globalConfig = Paths.get("path1/to/global-config"); | ||
* Path userConfig = Paths.get("path2/to/user-config"); | ||
* Path localConfig = Paths.get("path3/to/sys-config"); | ||
* PathFence fence = PathFence.builder().setRoots(globalConfig, userConfig, localConfig).get(); | ||
* </pre> | ||
* <p> | ||
* To use the current directory as the path fence: | ||
* </p> | ||
* <pre> | ||
* PathFence fence = PathFence.builder().setRoots(PathUtils.current()).get(); | ||
* </pre> | ||
* | ||
* @since 2.21.0 | ||
*/ | ||
// Cannot implement both UnaryOperator<Path> and Function<String, Path>, so don't pick one over the other | ||
public final class PathFence { | ||
|
||
/** | ||
* Builds {@link PathFence} instances. | ||
*/ | ||
public static final class Builder implements Supplier<PathFence> { | ||
|
||
/** The empty Path array. */ | ||
private static final Path[] EMPTY = {}; | ||
|
||
/** | ||
* A fence is made of root Paths. | ||
*/ | ||
private Path[] roots = EMPTY; | ||
|
||
/** | ||
* Constructs a new instance. | ||
*/ | ||
private Builder() { | ||
// empty | ||
} | ||
|
||
@Override | ||
public PathFence get() { | ||
return new PathFence(this); | ||
} | ||
|
||
/** | ||
* Sets the paths that delineate this fence. | ||
* | ||
* @param roots the paths that delineate this fence. | ||
* @return {@code this} instance. | ||
*/ | ||
Builder setRoots(final Path... roots) { | ||
this.roots = roots != null ? roots.clone() : EMPTY; | ||
return this; | ||
} | ||
} | ||
|
||
/** | ||
* Creates a new builder. | ||
* | ||
* @return a new builder. | ||
*/ | ||
public static Builder builder() { | ||
return new Builder(); | ||
} | ||
|
||
/** | ||
* A fence is made of Paths guarding Path resolution. | ||
*/ | ||
private final List<Path> roots; | ||
|
||
/** | ||
* Constructs a new instance. | ||
* | ||
* @param builder A builder. | ||
*/ | ||
private PathFence(final Builder builder) { | ||
this.roots = Arrays.stream(builder.roots).map(Path::toAbsolutePath).collect(Collectors.toList()); | ||
} | ||
|
||
/** | ||
* Checks that that a Path resolves within our fence. | ||
* | ||
* @param path The path to test. | ||
* @return The given path. | ||
* @throws IllegalArgumentException Thrown if the file name is not without our fence. | ||
*/ | ||
// Cannot implement both UnaryOperator<Path> and Function<String, Path> | ||
public Path apply(final Path path) { | ||
return getPath(path.toString(), path); | ||
} | ||
|
||
/** | ||
* Gets a Path for the given file name, checking that it resolves within our fence. | ||
* | ||
* @param fileName the file name to resolve. | ||
* @return a fenced Path. | ||
* @throws IllegalArgumentException Thrown if the file name is not without our fence. | ||
*/ | ||
// Cannot implement both UnaryOperator<Path> and Function<String, Path> | ||
public Path apply(final String fileName) { | ||
return getPath(fileName, Paths.get(fileName)); | ||
} | ||
|
||
private Path getPath(final String fileName, final Path path) { | ||
if (roots.isEmpty()) { | ||
return path; | ||
} | ||
final Path pathAbs = path.normalize().toAbsolutePath(); | ||
final Optional<Path> first = roots.stream().filter(pathAbs::startsWith).findFirst(); | ||
if (first.isPresent()) { | ||
return path; | ||
} | ||
throw new IllegalArgumentException(String.format("[%s] -> [%s] not in the fence %s", fileName, pathAbs, roots)); | ||
} | ||
} |
101 changes: 101 additions & 0 deletions
101
src/test/java/org/apache/commons/io/file/PathFenceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.apache.commons.io.file; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
import static org.junit.jupiter.api.Assertions.assertSame; | ||
import static org.junit.jupiter.api.Assertions.assertThrows; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
||
import java.io.IOException; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.io.TempDir; | ||
import org.junit.jupiter.params.ParameterizedTest; | ||
import org.junit.jupiter.params.provider.ValueSource; | ||
|
||
/** | ||
* Tests {@link PathFence}. | ||
*/ | ||
public class PathFenceTest { | ||
|
||
private Path createDirectory(final Path tempDir, final String other) throws IOException { | ||
return Files.createDirectory(tempDir.resolve(other)); | ||
} | ||
|
||
@Test | ||
void testAbsolutePath(@TempDir final Path fenceRootPath) throws Exception { | ||
// tempDir is the fence | ||
final Path childTest = fenceRootPath.resolve("child/file.txt"); | ||
final PathFence fence = PathFence.builder().setRoots(fenceRootPath).get(); | ||
// getPath with an absolute string should be allowed | ||
final Path childOk = fence.apply(childTest.toString()); | ||
assertEquals(childTest.toAbsolutePath().normalize(), childOk.toAbsolutePath().normalize()); | ||
// check with a Path instance should return the same instance when allowed | ||
assertSame(childTest, fence.apply(childTest)); | ||
} | ||
|
||
@ParameterizedTest | ||
@ValueSource(strings = { "", ".", "some", "some/relative", "some/relative/path" }) | ||
void testEmpty(final String test) { | ||
// An empty fence accepts anything | ||
final PathFence fence = PathFence.builder().get(); | ||
final Path path = Paths.get(test); | ||
assertEquals(path, fence.apply(test)); | ||
assertSame(path, fence.apply(path)); | ||
} | ||
|
||
@Test | ||
void testMultipleFencePaths(@TempDir final Path tempDir) throws Exception { | ||
// The fence is inside tempDir | ||
final Path fenceRootPath1 = createDirectory(tempDir, "root-one"); | ||
final Path fenceRootPath2 = createDirectory(tempDir, "root-two"); | ||
final PathFence fence = PathFence.builder().setRoots(fenceRootPath1, fenceRootPath2).get(); | ||
// Path under the first path should be allowed | ||
final Path inPath1 = fenceRootPath1.resolve("a/b.txt"); | ||
assertSame(inPath1, fence.apply(inPath1)); | ||
// Path under the second path should be allowed | ||
final Path inPath2 = fenceRootPath2.resolve("a/b.txt"); | ||
assertSame(inPath2, fence.apply(inPath2)); | ||
} | ||
|
||
@Test | ||
void testNormalization(@TempDir final Path tempDir) throws Exception { | ||
final Path fenceRootPath = createDirectory(tempDir, "root-one"); | ||
final Path weird = fenceRootPath.resolve("subdir/../other.txt"); | ||
final PathFence fence = PathFence.builder().setRoots(fenceRootPath).get(); | ||
// Path contains '..' but after normalization it's still inside the base | ||
assertSame(weird, fence.apply(weird)); | ||
} | ||
|
||
@Test | ||
void testOutsideFenceThrows(@TempDir final Path tempDir) throws Exception { | ||
final Path fenceRootPath = createDirectory(tempDir, "root-one"); | ||
final Path other = createDirectory(tempDir, "other"); | ||
final PathFence fence = PathFence.builder().setRoots(fenceRootPath).get(); | ||
final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> fence.apply(other.toString())); | ||
final String msg = ex.getMessage(); | ||
assertNotNull(msg); | ||
assertTrue(msg.contains("not in the fence"), () -> "Expected message to mention fence: " + msg); | ||
assertTrue(msg.contains(other.toAbsolutePath().toString()), () -> "Expected message to contain the path: " + msg); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you call it in the reverse order,
normalize()
will not remove leading..
segments. For example on UNIX:path
equals../../etc/passwd
,path.normalize()
equals../../etc/passwd
,path.normalize().toAbsolutePath()
equals/home/piotr/../../etc/passwd
.