validatePathWithinRoot static method
Rejects application-relative paths that escape through an existing
symbolic link. Lexical .. checks alone do not protect a write such as
integration_test/entry.dart when integration_test points elsewhere.
Implementation
static void validatePathWithinRoot({
required String root,
required String relativePath,
}) {
validateRelativePath(relativePath);
final rootPath = Directory(root).resolveSymbolicLinksSync();
var current = rootPath;
for (final component in p.split(p.normalize(relativePath))) {
if (component.isEmpty || component == p.current) continue;
current = p.join(current, component);
final type = FileSystemEntity.typeSync(current, followLinks: false);
if (type == FileSystemEntityType.link) {
try {
current = Link(current).resolveSymbolicLinksSync();
} on FileSystemException catch (error) {
throw StateError(
'Path contains an unresolved symbolic link: $relativePath '
'(${error.message})',
);
}
}
final fromRoot = p.relative(current, from: rootPath);
if (p.isAbsolute(fromRoot) ||
fromRoot == '..' ||
fromRoot.startsWith('..${p.separator}')) {
throw StateError(
'Path must remain inside the application: $relativePath');
}
}
}