文件工具的最小路径边界。 s02 还没有权限系统,但文件读写至少要被限制在 workdir 内, 避免模型通过相对路径访问项目目录之外的文件。
| 10 | * 避免模型通过相对路径访问项目目录之外的文件。 |
| 11 | */ |
| 12 | public class PathGuard { |
| 13 | |
| 14 | private final File workdir; |
| 15 | |
| 16 | public PathGuard(File workdir) { |
| 17 | this.workdir = workdir; |
| 18 | } |
| 19 | |
| 20 | public File resolve(String path) throws IOException { |
| 21 | File target = new File(workdir, path).getCanonicalFile(); |
| 22 | File root = workdir.getCanonicalFile(); |
| 23 | if (!target.toPath().startsWith(root.toPath())) { |
| 24 | throw new IOException("Path escapes workspace: " + path); |
| 25 | } |
| 26 | return target; |
| 27 | } |
| 28 | } |
nothing calls this directly
no outgoing calls
no test coverage detected