diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 1dfdcb637d3..9649c8ea363 100644 --- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md +++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md @@ -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 diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 50bc259549b..197ad7e279f 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -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 diff --git a/packages/devtools_shared/lib/src/extensions/extension_manager.dart b/packages/devtools_shared/lib/src/extensions/extension_manager.dart index acc0fd55258..fa85f53cea2 100644 --- a/packages/devtools_shared/lib/src/extensions/extension_manager.dart +++ b/packages/devtools_shared/lib/src/extensions/extension_manager.dart @@ -10,6 +10,7 @@ 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'; @@ -17,6 +18,10 @@ import 'extension_model.dart'; /// `/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`. /// @@ -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 @@ -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, ); @@ -102,8 +124,8 @@ class ExtensionsManager { ); for (final root in projectRoots.uris ?? const []) { - // 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( @@ -113,9 +135,9 @@ class ExtensionsManager { staticContext: true, ); } - } finally { - await dartToolingDaemon?.close(); } + } finally { + await dartToolingDaemon?.close(); } if (parsingErrors.isNotEmpty) { @@ -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 _validateRootFileUri( + String rootFileUriString, { + required List 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 [], + _ => (await dtd.getIDEWorkspaceRoots()).ideWorkspaceRoots, + }; + + final resolvedWorkspaceRoots = [ + for (final workspaceRootUri in ideWorkspaceRoots) + if (isLocalFileUri(workspaceRootUri)) + ?tryResolveDirectoryPath( + path.normalize(workspaceRootUri.toFilePath()), + ), + ]; + + 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]. @@ -138,6 +240,13 @@ class ExtensionsManager { _assertUriFormat(rootFileUriString); final List 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, @@ -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 ' @@ -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: @@ -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', @@ -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'; +} diff --git a/packages/devtools_shared/lib/src/server/file_system.dart b/packages/devtools_shared/lib/src/server/file_system.dart index 63918084354..bda127e51b2 100644 --- a/packages/devtools_shared/lib/src/server/file_system.dart +++ b/packages/devtools_shared/lib/src/server/file_system.dart @@ -3,7 +3,7 @@ // 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'; @@ -11,6 +11,27 @@ 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(); diff --git a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart index af2b3f33957..6a009d8f3bd 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -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.', @@ -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. @@ -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()) : ''; @@ -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()); @@ -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; } } diff --git a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart index 044d88620bd..a1b0c986ca1 100644 --- a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart +++ b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart @@ -645,6 +645,192 @@ void main() { ); }, ); + + test( + 'rejects packageRootUri when directory does not exist or is not a Dart ' + 'package root', + () async { + await initializeTestDirectory(); + final nonExistentRootUri = Uri.file( + p.join(extensionTestManager.packagesRootUri.toFilePath(), 'missing'), + ).toString(); + final nonPackageDir = Directory( + p.join( + extensionTestManager.packagesRootUri.toFilePath(), + 'empty_dir', + ), + )..createSync(recursive: true); + final nonPackageRootUri = Uri.file(nonPackageDir.path).toString(); + + for (final invalidRootUri in [nonExistentRootUri, nonPackageRootUri]) { + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: ExtensionsApi.apiServeAvailableExtensions, + queryParameters: { + ExtensionsApi.packageRootUriPropertyName: invalidRootUri, + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await ServerApi.handle( + request, + extensionsManager: extensionsManager, + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + } + }, + ); + + test('rejects packageRootUri outside IDE workspace roots', () async { + await initializeTestDirectory(); + final outsidePackageDir = Directory( + p.join(extensionTestManager.testDirectory.path, 'outside_pkg'), + )..createSync(recursive: true); + File(p.join(outsidePackageDir.path, 'pubspec.yaml')).writeAsStringSync(''' +name: outside_pkg +environment: + sdk: "^3.5.0" +'''); + final outsideRootUri = Uri.file(outsidePackageDir.path).toString(); + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: ExtensionsApi.apiServeAvailableExtensions, + queryParameters: { + ExtensionsApi.packageRootUriPropertyName: outsideRootUri, + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await ServerApi.handle( + request, + extensionsManager: extensionsManager, + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + }); + + test('rejects packageRootUri when IDE workspace roots are empty', () async { + await initializeTestDirectory(); + await testDtdConnection!.setIDEWorkspaceRoots( + dtd!.info!.secret!, + const [], + ); + + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: ExtensionsApi.apiServeAvailableExtensions, + queryParameters: { + ExtensionsApi.packageRootUriPropertyName: + extensionTestManager.runtimeAppRoot, + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await ServerApi.handle( + request, + extensionsManager: extensionsManager, + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + }); + + test('rejects packageRootUri symlink inside workspace pointing outside ' + 'workspace', () async { + await initializeTestDirectory(); + final outsidePackageDir = Directory( + p.join(extensionTestManager.testDirectory.path, 'outside_pkg'), + )..createSync(recursive: true); + File(p.join(outsidePackageDir.path, 'pubspec.yaml')).writeAsStringSync(''' +name: outside_pkg +environment: + sdk: "^3.5.0" +'''); + final symlinkInWorkspace = Link( + p.join( + extensionTestManager.packagesRootUri.toFilePath(), + 'linked_outside_pkg', + ), + )..createSync(outsidePackageDir.path); + + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: ExtensionsApi.apiServeAvailableExtensions, + queryParameters: { + ExtensionsApi.packageRootUriPropertyName: Uri.file( + symlinkInWorkspace.path, + ).toString(), + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await ServerApi.handle( + request, + extensionsManager: extensionsManager, + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + }); + + test('rejects packageRootUri whose package_config.json resolves above ' + 'the IDE workspace root', () async { + await initializeTestDirectory(); + final workspaceMemberDir = Directory( + p.join( + extensionTestManager.packagesRootUri.toFilePath(), + 'workspace_root', + 'workspace_member', + ), + ); + // Set the IDE workspace root to the sub-package only, so the parent + // workspace_root/.dart_tool/package_config.json is outside the IDE + // workspace root. + await testDtdConnection!.setIDEWorkspaceRoots(dtd!.info!.secret!, [ + workspaceMemberDir.uri, + ]); + + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: ExtensionsApi.apiServeAvailableExtensions, + queryParameters: { + ExtensionsApi.packageRootUriPropertyName: workspaceMemberDir.uri + .toString(), + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await ServerApi.handle( + request, + extensionsManager: extensionsManager, + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + }); }); group(ExtensionsApi.apiExtensionEnabledState, () {