Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ TODO: Remove this section if there are not any updates.
* Validated DevTools extension version strings and prevented extension
identifier collisions when serving extension assets.
[#10090](https://github.com/flutter/devtools/pull/10090)
* Confined extension server package roots and options files to active workspace
roots and currently served extensions.
[#10089](https://github.com/flutter/devtools/pull/10089)

## Advanced developer mode updates

Expand Down
3 changes: 3 additions & 0 deletions packages/devtools_shared/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens
recursive directory creation when looking up `devtools_options.yaml`.
* Restrict `normalizeVmServiceUri` to allowed VM service schemes (`http`, `https`,
`ws`, `wss`, `sse`, `sses`) and loopback hosts (`localhost`, `127.0.0.0/8`, `::1`).
* Confine `packageRootUri` and `devtoolsOptionsUri` in extension server APIs to
active IDE workspace roots and currently served extensions, and prevent
recursive directory creation when looking up `devtools_options.yaml`.

# 14.0.0

Expand Down
175 changes: 145 additions & 30 deletions packages/devtools_shared/lib/src/extensions/extension_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,18 @@ import 'package:extension_discovery/extension_discovery.dart';
import 'package:path/path.dart' as path;

import '../common.dart';
import '../server/file_system.dart';
import 'constants.dart';
import 'extension_model.dart';

/// The default location for the DevTools extension, relative to
/// `<parent_package_root>/extension/devtools/`.
const extensionBuildDefault = 'build';

const _dartToolDirName = '.dart_tool';
const _packageConfigFileName = 'package_config.json';
const _pubspecFileName = 'pubspec.yaml';

/// Responsible for storing the available DevTools extensions and managing the
/// content that DevTools server will serve at `build/devtools_extensions`.
///
Expand Down Expand Up @@ -52,7 +57,8 @@ class ExtensionsManager {
/// Flutter project containing the `.dart_tool/` directory.
///
/// [rootFileUriString] is expected to be a file URI string (e.g. starting
/// with 'file://').
/// with 'file://'). [rootFileUriString] must resolve within one of the active
/// IDE workspace roots from [dtd].
///
/// This method first looks up the available extensions using
/// package:extension_discovery, and the available extension's
Expand All @@ -71,28 +77,44 @@ class ExtensionsManager {
_clear();
final parsingErrors = StringBuffer();

// Find all runtime extensions for [rootFileUriString], if non-null and
// non-empty.
if (rootFileUriString != null && rootFileUriString.isNotEmpty) {
logs.add(
'ExtensionsManager.serveAvailableExtensions adding extensions for app '
'root.',
);
await _addExtensionsForRoot(
rootFileUriString,
logs: logs,
parsingErrors: parsingErrors,
staticContext: false,
);
_assertUriFormat(rootFileUriString);
}

// Find all static extensions for the project roots, which are derived from
// the Dart Tooling Daemon, and add them to [devtoolsExtensions].
final dtdUri = dtd?.localUri;
if (dtdUri != null) {
DartToolingDaemon? dartToolingDaemon;
try {
DartToolingDaemon? dartToolingDaemon;
try {
if (dtdUri != null) {
dartToolingDaemon = await DartToolingDaemon.connect(dtdUri);
} else {
logs.add(
'ExtensionsManager.serveAvailableExtensions did not obtain a DTD URI.',
);
}

// Find all runtime extensions for [rootFileUriString], if non-null and
// non-empty.
if (rootFileUriString != null && rootFileUriString.isNotEmpty) {
await _validateRootFileUri(
rootFileUriString,
logs: logs,
dtd: dartToolingDaemon,
);
logs.add(
'ExtensionsManager.serveAvailableExtensions adding extensions for app '
'root.',
);
await _addExtensionsForRoot(
rootFileUriString,
logs: logs,
parsingErrors: parsingErrors,
staticContext: false,
);
}

// Find all static extensions for the project roots, which are derived
// from the Dart Tooling Daemon, and add them to [devtoolsExtensions].
if (dartToolingDaemon != null) {
final projectRoots = await dartToolingDaemon.getProjectRoots(
depth: staticExtensionsSearchDepth,
);
Expand All @@ -102,8 +124,8 @@ class ExtensionsManager {
);

for (final root in projectRoots.uris ?? const <Uri>[]) {
// Skip the runtime app root. These extensions have already been
// added to [devtoolsExtensions].
// Skip the runtime app root. These extensions have already been added
// to [devtoolsExtensions].
if (root.toString() == rootFileUriString) continue;

await _addExtensionsForRoot(
Expand All @@ -113,9 +135,9 @@ class ExtensionsManager {
staticContext: true,
);
}
} finally {
await dartToolingDaemon?.close();
}
} finally {
await dartToolingDaemon?.close();
}

if (parsingErrors.isNotEmpty) {
Expand All @@ -126,6 +148,86 @@ class ExtensionsManager {
}
}

/// Validates that [rootFileUriString] is a local `file://` URI pointing to an
/// existing Dart package root on disk that resolves within one of the active
/// IDE workspace roots from [dtd].
Future<void> _validateRootFileUri(
String rootFileUriString, {
required List<String> logs,
required DartToolingDaemon? dtd,
}) async {
Never logAndThrow(String reason) {
final message = 'Invalid rootFileUriString "$rootFileUriString": $reason';
logs.add(message);
throw ServeAvailableExtensionsException(message);
}

// Ensure the URI is non-empty and doesn't have relative segments.
final rootUri = Uri.parse(rootFileUriString);
if (rootUri.path.isEmpty ||
rootUri.pathSegments.contains('..') ||
rootUri.pathSegments.contains('.')) {
logAndThrow('must be a file:// URI with a non-empty normalized path.');
}

// Resolve symlinks and verify that the directory contains a Dart package.
final rootPath = path.normalize(rootUri.toFilePath());
final resolvedRootPath = tryResolveDirectoryPath(rootPath);
if (resolvedRootPath == null || !_isDartPackageRoot(resolvedRootPath)) {
logAndThrow('directory does not exist or is not a Dart package root.');
}

// Resolve the active IDE workspace roots from DTD.
final ideWorkspaceRoots = switch (dtd) {
null => const <Uri>[],
_ => (await dtd.getIDEWorkspaceRoots()).ideWorkspaceRoots,
};

final resolvedWorkspaceRoots = <String>[
for (final workspaceRootUri in ideWorkspaceRoots)
if (isLocalFileUri(workspaceRootUri))
?tryResolveDirectoryPath(
path.normalize(workspaceRootUri.toFilePath()),
Comment thread
johnpryan marked this conversation as resolved.
Resolved
),
];

bool isWithinAnyWorkspaceRoot(String? targetPath) =>
targetPath != null &&
resolvedWorkspaceRoots.any(
(workspaceRootPath) =>
isWithinOrEqualPath(workspaceRootPath, targetPath),
);

// Verify that the package root and its resolved package_config.json root
// are within an active IDE workspace root.
final packageConfigUri = findPackageConfig(Uri.file(resolvedRootPath));
final resolvedPackageConfigRoot = packageConfigUri == null
? null
: tryResolveDirectoryPath(
// Strip `.dart_tool/package_config.json` to get the owning root.
path.dirname(path.dirname(packageConfigUri.toFilePath())),
);

final isRootInWorkspace = isWithinAnyWorkspaceRoot(resolvedRootPath);
final isPackageConfigInWorkspace =
packageConfigUri == null ||
isWithinAnyWorkspaceRoot(resolvedPackageConfigRoot);

if (!isRootInWorkspace || !isPackageConfigInWorkspace) {
logAndThrow('must be within an active IDE workspace root.');
}
}

/// Returns whether [dirPath] contains a `.dart_tool/package_config.json` or
/// `pubspec.yaml` file.
bool _isDartPackageRoot(String dirPath) {
final hasPackageConfig = File(
path.join(dirPath, _dartToolDirName, _packageConfigFileName),
).existsSync();
final hasPubspec = File(path.join(dirPath, _pubspecFileName)).existsSync();
return hasPackageConfig || hasPubspec;
}

/// Finds the available extensions for the package root at
/// [rootFileUriString], generates [DevToolsExtensionConfig] objects, and adds
/// them to [devtoolsExtensions].
Expand All @@ -138,6 +240,13 @@ class ExtensionsManager {
_assertUriFormat(rootFileUriString);
final List<Extension> extensions;
final packageConfigPath = findPackageConfig(Uri.parse(rootFileUriString));
if (packageConfigPath == null) {
logs.add(
'ExtensionsManager._addExtensionsForRoot no $_packageConfigFileName '
'found for $rootFileUriString.',
);
return;
}
extensions = await findExtensions(
'devtools',
packageConfig: packageConfigPath,
Expand All @@ -151,8 +260,7 @@ class ExtensionsManager {
for (final extension in extensions) {
final config = extension.config;

if (extension.rootUri.scheme != 'file' ||
extension.rootUri.host.isNotEmpty) {
if (!isLocalFileUri(extension.rootUri)) {
parsingErrors.writeln(
'Ignoring extension from package "${extension.package}": invalid '
'package root URI "${extension.rootUri}" must be a file:// URI '
Expand Down Expand Up @@ -346,8 +454,7 @@ class ExtensionsManager {
// are rejected below.
}
if (resolvedTargetPath == null ||
(!path.isWithin(resolvedLocation, resolvedTargetPath) &&
!path.equals(resolvedLocation, resolvedTargetPath))) {
!isWithinOrEqualPath(resolvedLocation, resolvedTargetPath)) {
return (
resolvedLocation: null,
error:
Expand All @@ -362,10 +469,7 @@ class ExtensionsManager {
void _assertUriFormat(String? uriString) {
if (uriString == null) return;
final uri = Uri.tryParse(uriString);
if (!uriString.startsWith('file://') ||
uri == null ||
uri.scheme != 'file' ||
uri.host.isNotEmpty) {
if (!isLocalFileUri(uri)) {
throw ArgumentError.value(
uriString,
'uriString',
Expand All @@ -385,3 +489,14 @@ class ExtensionsManager {
class ExtensionParsingException extends FormatException {
const ExtensionParsingException(super.message);
}

/// Exception type for errors encountered while serving DevTools extensions.
class ServeAvailableExtensionsException implements Exception {
const ServeAvailableExtensionsException(this.message);

/// The error message describing why serving extensions failed.
final String message;

@override
String toString() => 'ServeAvailableExtensionsException: $message';
}
23 changes: 22 additions & 1 deletion packages/devtools_shared/lib/src/server/file_system.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,35 @@
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.

import 'dart:convert';
import 'dart:io' as io show Platform, File;
import 'dart:io' as io show Directory, File, FileSystemException, Platform;

import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:path/path.dart' as path;

import 'devtools_store.dart';

/// Returns whether [uri] is a non-null `file:` URI with an empty host (local
/// file path, rejecting non-`file` schemes and UNC/remote hosts).
bool isLocalFileUri(Uri? uri) =>
uri != null && uri.scheme == 'file' && uri.host.isEmpty;

/// Returns whether [childPath] is equal to or contained within [parentPath].
bool isWithinOrEqualPath(String parentPath, String childPath) =>
path.equals(parentPath, childPath) || path.isWithin(parentPath, childPath);

/// Returns the normalized, symlink-resolved path for [dirPath], or `null` if
/// [dirPath] does not exist as a directory or symbolic link resolution fails.
String? tryResolveDirectoryPath(String dirPath) {
final directory = io.Directory(dirPath);
if (!directory.existsSync()) return null;
try {
return path.normalize(directory.resolveSymbolicLinksSync());
} on io.FileSystemException {
return null;
}
}

/// The real, local file system, which can be avoided in tests.
const fileSystem = LocalFileSystem();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ extension _ExtensionsApiHandler on Never {
queryParams[ExtensionsApi.packageRootUriPropertyName];
if (rootFileUriString != null && rootFileUriString.isNotEmpty) {
final rootFileUri = Uri.tryParse(rootFileUriString);
if (!rootFileUriString.startsWith('file://') ||
rootFileUri == null ||
rootFileUri.scheme != 'file' ||
rootFileUri.host.isNotEmpty) {
if (!isLocalFileUri(rootFileUri)) {
return api.badRequest(
'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a '
'file:// URI with an empty host.',
Expand Down Expand Up @@ -59,6 +56,8 @@ extension _ExtensionsApiHandler on Never {
logs,
dtd,
);
} on ServeAvailableExtensionsException catch (e) {
return api.serverError('$e', logs);
} on ExtensionParsingException catch (e) {
// For [ExtensionParsingException]s, we should return a success response
// with a warning message.
Expand Down Expand Up @@ -103,9 +102,7 @@ extension _ExtensionsApiHandler on Never {
// separators, so the check holds for Windows file URIs as well. Requiring
// an empty host rejects UNC paths (e.g. `file://server/share/...`) and
// keeps `toFilePath()` from throwing on a non-local authority.
final isFileUri =
devtoolsOptionsFileUri.scheme == 'file' &&
devtoolsOptionsFileUri.host.isEmpty;
final isFileUri = isLocalFileUri(devtoolsOptionsFileUri);
final fileName = isFileUri
? p.basename(devtoolsOptionsFileUri.toFilePath())
: '';
Expand All @@ -130,7 +127,7 @@ extension _ExtensionsApiHandler on Never {
extensionsManager.devtoolsExtensions.any((ext) {
final uri = Uri.tryParse(ext.devtoolsOptionsUri);
if (uri == null) return false;
if (uri.scheme == 'file' && uri.host.isEmpty) {
if (isLocalFileUri(uri)) {
// If these are equal, there's no need to call
// _resolveOptionsFilePath again, so return early.
final servedPathUnresolved = p.normalize(uri.toFilePath());
Expand Down Expand Up @@ -181,21 +178,16 @@ extension _ExtensionsApiHandler on Never {
/// [uri] is not a local `file:` URI, its parent directory does not exist, or
/// the `devtools_options.yaml` file itself is a symbolic link.
static String? _resolveOptionsFilePath(Uri uri) {
if (uri.scheme != 'file' || uri.host.isNotEmpty) return null;
if (!isLocalFileUri(uri)) return null;

final filePath = p.normalize(uri.toFilePath());
if (p.basename(filePath) != devtoolsOptionsFileName) return null;

final parentDir = Directory(p.dirname(filePath));
if (!parentDir.existsSync()) return null;
final resolvedParent = tryResolveDirectoryPath(p.dirname(filePath));
if (resolvedParent == null) return null;

try {
final resolvedParent = p.normalize(parentDir.resolveSymbolicLinksSync());
final resolvedFilePath = p.join(resolvedParent, devtoolsOptionsFileName);
if (FileSystemEntity.isLinkSync(resolvedFilePath)) return null;
return resolvedFilePath;
} on FileSystemException {
return null;
}
final resolvedFilePath = p.join(resolvedParent, devtoolsOptionsFileName);
if (FileSystemEntity.isLinkSync(resolvedFilePath)) return null;
return resolvedFilePath;
}
}
Loading
Loading