diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 9bf254debd6..be6ca145a34 100644 --- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md +++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md @@ -35,6 +35,9 @@ such as black or white, are now adjusted to remain legible. [#10082](https://github.com/flutter/devtools/pull/10082) * Restricted VM service connection URIs to allowed schemes and loopback hosts. [#10091](https://github.com/flutter/devtools/pull/10091) +* Validated package root URIs detected from VM service connections before + registering them as Dart Tooling Daemon (DTD) IDE workspace roots. + [#10096](https://github.com/flutter/devtools/pull/10096) ## Inspector updates diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 383137873c1..5e14030fbcd 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -41,6 +41,12 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens `api/serveAvailableExtensions`. * Add `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` to `devtools_shared.dart`. +* Add `isValidLocalFileUri` and `isValidLocalFileUriString` helpers to validate + local `file://` URIs without authorities, queries, fragments, or null bytes, + and apply them in `api/extensionEnabledState`, `VmServiceHandler`, and + `ExtensionsManager`. +* Validate and resolve symlinks for detected package roots in `VmServiceHandler` + before caching or updating DTD IDE workspace roots. # 14.0.0 diff --git a/packages/devtools_shared/lib/devtools_shared.dart b/packages/devtools_shared/lib/devtools_shared.dart index a9e9e3bcd3a..3815e81eeac 100644 --- a/packages/devtools_shared/lib/devtools_shared.dart +++ b/packages/devtools_shared/lib/devtools_shared.dart @@ -13,7 +13,7 @@ export 'src/memory/memory_json.dart'; export 'src/service_utils.dart'; export 'src/sse/sse_shim.dart'; export 'src/utils/compare.dart'; -export 'src/utils/file_utils.dart'; +export 'src/utils/file_utils.dart' hide invalidLocalFileUriMessage; export 'src/utils/retry.dart'; export 'src/utils/semantic_version.dart'; export 'src/utils/serialization.dart'; diff --git a/packages/devtools_shared/lib/src/extensions/extension_manager.dart b/packages/devtools_shared/lib/src/extensions/extension_manager.dart index acc0fd55258..85762fbdd48 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 '../utils/file_utils.dart'; import 'constants.dart'; import 'extension_model.dart'; @@ -151,12 +152,11 @@ class ExtensionsManager { for (final extension in extensions) { final config = extension.config; - if (extension.rootUri.scheme != 'file' || - extension.rootUri.host.isNotEmpty) { + if (!isValidLocalFileUri(extension.rootUri)) { parsingErrors.writeln( 'Ignoring extension from package "${extension.package}": invalid ' - 'package root URI "${extension.rootUri}" must be a file:// URI ' - 'with an empty host.', + 'package root URI "${extension.rootUri}" ' + '$invalidLocalFileUriMessage', ); continue; } @@ -361,15 +361,11 @@ 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 (!isValidLocalFileUriString(uriString)) { throw ArgumentError.value( uriString, 'uriString', - 'must be a file:// URI String with an empty host', + invalidLocalFileUriMessage, ); } } 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 6cfdd7c2558..6a0d4304c5b 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -137,9 +137,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 = isValidLocalFileUri(devtoolsOptionsFileUri); final fileName = isFileUri ? p.basename(devtoolsOptionsFileUri.toFilePath()) : ''; @@ -164,7 +162,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 (isValidLocalFileUri(uri)) { // If these are equal, there's no need to call // _resolveOptionsFilePath again, so return early. final servedPathUnresolved = p.normalize(uri.toFilePath()); @@ -215,7 +213,7 @@ 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 (!isValidLocalFileUri(uri)) return null; final filePath = p.normalize(uri.toFilePath()); if (p.basename(filePath) != devtoolsOptionsFileName) return null; diff --git a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart index e51f13f30e7..126d8c8c48e 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -7,6 +7,19 @@ part of '../server_api.dart'; /// A namespace for VM service related server request handlers. @visibleForTesting extension VmServiceHandler on Never { + /// File name of a Dart or Flutter package manifest. + static const _pubspecYamlFileName = 'pubspec.yaml'; + + /// Name of the Dart tooling metadata directory in a package root. + static const _dartToolDirName = '.dart_tool'; + + /// File name of the package configuration file inside [_dartToolDirName]. + static const _packageConfigJsonFileName = 'package_config.json'; + + /// Environment variables holding the user's home directory on POSIX (`HOME`) + /// and Windows (`USERPROFILE`). + static const _homeEnvVarKeys = ['HOME', 'USERPROFILE']; + /// Stores the calculated package roots for VM service connections that are /// initiated in [handleNotifyForVmServiceConnection]. /// @@ -47,6 +60,143 @@ extension VmServiceHandler on Never { _packageRootsForVmServiceConnections.clear(); } + /// Validates that [rootPackageUri] is a local `file://` URI pointing to an + /// existing Dart or Flutter package directory, and not the filesystem root or + /// the user's home directory (or an ancestor of it). + /// + /// Returns the symlink-resolved [Uri] if [rootPackageUri] is valid, or an + /// error message if it must be rejected. + @visibleForTesting + static ({Uri? resolvedUri, String? error}) validateRootPackageUri( + Uri rootPackageUri, { + Map? environment, + }) { + if (!isValidLocalFileUri(rootPackageUri)) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): ' + '$invalidLocalFileUriMessage', + ); + } + + final dirPath = p.normalize(rootPackageUri.toFilePath()); + final dir = Directory(dirPath); + if (!dir.existsSync()) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): directory does not ' + 'exist.', + ); + } + + final String resolvedDirPath; + try { + resolvedDirPath = p.normalize(dir.resolveSymbolicLinksSync()); + } on FileSystemException catch (e) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): failed to resolve ' + 'symbolic links ($e).', + ); + } + + final resolvedUri = Uri.file(resolvedDirPath); + if (!isValidLocalFileUri(resolvedUri)) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): ' + '$invalidLocalFileUriMessage', + ); + } + + if (p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): cannot be the ' + 'filesystem root.', + ); + } + + if (_isUserHomeOrAncestorDirectory( + resolvedDirPath, + environment: environment ?? Platform.environment, + )) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): cannot be the user ' + 'home directory or an ancestor of it.', + ); + } + + final hasPubspec = File( + p.join(resolvedDirPath, _pubspecYamlFileName), + ).existsSync(); + final hasPackageConfig = File( + p.join(resolvedDirPath, _dartToolDirName, _packageConfigJsonFileName), + ).existsSync(); + if (!hasPubspec && !hasPackageConfig) { + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): directory does not ' + 'contain $_pubspecYamlFileName or ' + '$_dartToolDirName/$_packageConfigJsonFileName.', + ); + } + + return (resolvedUri: resolvedUri, error: null); + } + + /// Returns whether [resolvedDirPath] matches or is an ancestor of the + /// current user's home directory from `HOME` or `USERPROFILE`. + static bool _isUserHomeOrAncestorDirectory( + String resolvedDirPath, { + required Map environment, + }) { + for (final envKey in _homeEnvVarKeys) { + final homePath = environment[envKey]; + if (homePath == null || homePath.isEmpty) continue; + final normalizedHome = p.normalize(homePath); + String resolvedHome; + try { + resolvedHome = p.normalize( + Directory(normalizedHome).resolveSymbolicLinksSync(), + ); + } on FileSystemException { + resolvedHome = normalizedHome; + } + if (p.equals(resolvedDirPath, resolvedHome) || + p.isWithin(resolvedDirPath, resolvedHome)) { + return true; + } + } + return false; + } + + /// Handles an [apiNotifyForVmServiceConnection] request notifying the + /// DevTools server that a DevTools client connected to or disconnected from a + /// VM service. + /// + /// Expects [queryParams] to contain [apiParameterValueKey] (the VM service + /// URI) and [apiParameterVmServiceConnected] (`'true'` or `'false'`). + /// + /// When the DevTools server owns the Dart Tooling Daemon (DevTools was + /// launched outside of the IDE, and [dtd] has both a [DtdInfo.localUri] and a + /// [DtdInfo.secret]), this registers or unregisters the VM service with DTD, + /// resolves and validates the app's package root via + /// [detectRootPackageForVmService], and updates DTD's IDE workspace roots via + /// [updateDtdWorkspaceRoots]. + /// + /// Returns a [ServerApi.success] no-op response via [api] if [dtd] is + /// unavailable or has no secret, [ServerApi.badRequest] if required + /// parameters are missing or invalid, or [ServerApi.serverError] if package + /// root detection or DTD communication fails. static Future handleNotifyForVmServiceConnection( ServerApi api, Map queryParams, @@ -171,7 +321,21 @@ extension VmServiceHandler on Never { uri: null, ); } - rootPackageUri = Uri.parse(root); + final parsedRoot = Uri.tryParse(root); + if (parsedRoot == null) { + return ( + success: false, + message: + 'Invalid package root URI ($root): ' + '$invalidLocalFileUriMessage', + uri: null, + ); + } + final (:resolvedUri, :error) = validateRootPackageUri(parsedRoot); + if (resolvedUri == null) { + return (success: false, message: error, uri: null); + } + rootPackageUri = resolvedUri; if (cacheResult) { _packageRootsForVmServiceConnections[normalizedUriAsString] = rootPackageUri; diff --git a/packages/devtools_shared/lib/src/server/server_api.dart b/packages/devtools_shared/lib/src/server/server_api.dart index 854eb5bb9cd..f284d7f281f 100644 --- a/packages/devtools_shared/lib/src/server/server_api.dart +++ b/packages/devtools_shared/lib/src/server/server_api.dart @@ -23,6 +23,7 @@ import '../extensions/extension_enablement.dart'; import '../extensions/extension_manager.dart'; import '../service/service.dart'; import '../service_utils.dart'; +import '../utils/file_utils.dart'; import 'devtools_store.dart'; import 'file_system.dart'; import 'flutter_store.dart'; diff --git a/packages/devtools_shared/lib/src/utils/file_utils.dart b/packages/devtools_shared/lib/src/utils/file_utils.dart index e9137974545..449e6c9d0ae 100644 --- a/packages/devtools_shared/lib/src/utils/file_utils.dart +++ b/packages/devtools_shared/lib/src/utils/file_utils.dart @@ -100,3 +100,42 @@ String _assertUriFormatAndReturn(String uriString) { ); return uriString; } + +/// Error description for invalid local `file://` URIs. +const invalidLocalFileUriMessage = + 'must be an absolute file:// URI with no host, query, or fragment.'; + +/// Returns whether [uri] is a valid local `file:` URI without an authority, +/// query, fragment, or null bytes, and can be converted to a local file path. +/// +/// Requiring an empty authority and disallowing a leading `//` in the path +/// rejects remote hosts, ports, user info, and Windows UNC paths (e.g. +/// `file://server/share/...` or `file:////server/share/...`). Checking +/// [Uri.toFilePath] ensures callers can convert [uri] without triggering an +/// [UnsupportedError] or [FormatException]. +bool isValidLocalFileUri(Uri uri) { + if (uri.scheme != 'file' || + uri.authority.isNotEmpty || + !uri.hasAbsolutePath || + uri.path.startsWith('//') || + uri.hasQuery || + uri.hasFragment) { + return false; + } + try { + final filePath = uri.toFilePath(); + return !filePath.contains('\x00'); + } catch (_) { + return false; + } +} + +/// Returns whether [uriString] is a `file://` URI string that parses as a valid +/// local `file:` URI via [isValidLocalFileUri]. +bool isValidLocalFileUriString(String? uriString) { + if (uriString == null || !uriString.startsWith(_fileUriPrefix)) { + return false; + } + final uri = Uri.tryParse(uriString); + return uri != null && isValidLocalFileUri(uri); +} diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index c2d2aedf1b0..0804088754f 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -9,8 +9,10 @@ import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_shared/src/extensions/extension_manager.dart'; import 'package:devtools_shared/src/server/server_api.dart' as server; import 'package:dtd/dtd.dart'; +import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; import 'package:test/test.dart'; +import 'package:vm_service/utils.dart'; import '../fakes.dart'; import '../helpers/helpers.dart'; @@ -636,6 +638,190 @@ void main() { ); }); + group('validateRootPackageUri', () { + late Directory tempDir; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('root_pkg_valid_test_'); + }); + + tearDown(() async { + await deleteDirectoryWithRetry(tempDir); + }); + + test( + 'accepts existing directories with pubspec.yaml or .dart_tool/package_config.json and returns resolved URI', + () { + final pkgWithPubspec = Directory(p.join(tempDir.path, 'pkg_1')) + ..createSync(recursive: true); + File(p.join(pkgWithPubspec.path, 'pubspec.yaml')).createSync(); + final resolvedPubspecPath = p.normalize( + pkgWithPubspec.resolveSymbolicLinksSync(), + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(pkgWithPubspec.path), + ), + (resolvedUri: Uri.file(resolvedPubspecPath), error: null), + ); + + // A symlink pointing to a valid package resolves to the target URI. + final symlinkToPkg = Link(p.join(tempDir.path, 'pkg_link')) + ..createSync(pkgWithPubspec.path); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(symlinkToPkg.path), + ), + (resolvedUri: Uri.file(resolvedPubspecPath), error: null), + ); + + final pkgWithConfig = Directory(p.join(tempDir.path, 'pkg_2')) + ..createSync(recursive: true); + File( + p.join(pkgWithConfig.path, '.dart_tool', 'package_config.json'), + ).createSync(recursive: true); + final resolvedConfigPath = p.normalize( + pkgWithConfig.resolveSymbolicLinksSync(), + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(pkgWithConfig.path), + ), + (resolvedUri: Uri.file(resolvedConfigPath), error: null), + ); + }, + ); + + test('rejects filesystem root and symlinks to filesystem root', () { + final rootPrefix = p.rootPrefix(tempDir.path); + final rootResult = server.VmServiceHandler.validateRootPackageUri( + Uri.file(rootPrefix), + ); + expect(rootResult.resolvedUri, isNull); + expect(rootResult.error, contains('filesystem root')); + + final symlinkToRoot = Link(p.join(tempDir.path, 'root_link')) + ..createSync(rootPrefix); + final symlinkResult = server.VmServiceHandler.validateRootPackageUri( + Uri.file(symlinkToRoot.path), + ); + expect(symlinkResult.resolvedUri, isNull); + expect(symlinkResult.error, contains('filesystem root')); + }); + + test('rejects invalid local file URIs', () { + final validPkg = Directory(p.join(tempDir.path, 'valid_pkg')) + ..createSync(recursive: true); + File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); + final invalidUri = Uri.parse('${Uri.file(validPkg.path)}?query=1'); + + final result = server.VmServiceHandler.validateRootPackageUri( + invalidUri, + ); + expect(result.resolvedUri, isNull); + expect(result.error, contains('must be an absolute file:// URI')); + }); + + test( + 'rejects user home directory and its ancestors (HOME and USERPROFILE)', + () { + final homeDir = Platform.isWindows + ? Platform.environment['USERPROFILE'] ?? + Platform.environment['HOME'] + : Platform.environment['HOME'] ?? + Platform.environment['USERPROFILE']; + if (homeDir != null && homeDir.isNotEmpty) { + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(homeDir), + ).error, + contains('home directory'), + ); + + // Also verify a symlink pointing to the home directory is rejected. + final symlinkToHome = Link(p.join(tempDir.path, 'home_link')) + ..createSync(homeDir); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(symlinkToHome.path), + ).error, + contains('home directory'), + ); + } + + // Verify both HOME and USERPROFILE environment variables (and their + // ancestors) are rejected even when the directory contains a + // pubspec.yaml file. + final usersDir = Directory(p.join(tempDir.path, 'users')) + ..createSync(recursive: true); + File(p.join(usersDir.path, 'pubspec.yaml')).createSync(); + final fakeHomePkg = Directory(p.join(usersDir.path, 'fake_home')) + ..createSync(recursive: true); + File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(fakeHomePkg.path), + ).error, + isNull, + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'HOME': fakeHomePkg.path}, + ).error, + contains('home directory'), + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'USERPROFILE': fakeHomePkg.path}, + ).error, + contains('home directory'), + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(usersDir.path), + environment: {'HOME': fakeHomePkg.path}, + ).error, + contains('home directory or an ancestor of it'), + ); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(usersDir.path), + environment: {'USERPROFILE': fakeHomePkg.path}, + ).error, + contains('home directory or an ancestor of it'), + ); + }, + ); + + test('rejects directories that do not exist or lack package markers', () { + // Non-existent directory. + final nonExistentUri = Uri.file(p.join(tempDir.path, 'does_not_exist')); + expect( + server.VmServiceHandler.validateRootPackageUri(nonExistentUri).error, + contains('directory does not exist'), + ); + + // Existing directory without pubspec.yaml or + // .dart_tool/package_config.json (only an empty .dart_tool dir). + final nonPackageDir = Directory(p.join(tempDir.path, 'not_a_pkg')) + ..createSync(recursive: true); + Directory( + p.join(nonPackageDir.path, '.dart_tool'), + ).createSync(recursive: true); + expect( + server.VmServiceHandler.validateRootPackageUri( + Uri.file(nonPackageDir.path), + ).error, + contains( + 'directory does not contain pubspec.yaml or ' + '.dart_tool/package_config.json', + ), + ); + }); + }); + group('endpoints that require DTD', () { TestDtdConnectionInfo? dtd; DartToolingDaemon? testDtdConnection; @@ -702,12 +888,20 @@ void main() { group('detectRootPackageForVmService', () { TestDartApp? app; + late String resolvedAppDirectoryPath; String? vmServiceUriString; setUp(() async { app = TestDartApp(); + // Resolve symlinks and Windows 8.3 short paths (e.g. `RUNNER~1` in + // `Directory.systemTemp` on Windows CI) so expectations match the + // canonical path returned by `validateRootPackageUri`. + resolvedAppDirectoryPath = p.normalize( + app!.directory.resolveSymbolicLinksSync(), + ); vmServiceUriString = await app!.start(); expect(vmServiceUriString, isNotEmpty); + File(p.join(app!.directory.path, 'pubspec.yaml')).createSync(); }); tearDown(() async { @@ -717,34 +911,51 @@ void main() { vmServiceUriString = null; }); - test('does not populate cache when cacheResult is false', () async { - final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); - expect(vmServiceUri, isNotNull); + /// Retries [server.VmServiceHandler.detectRootPackageForVmService] + /// until [isReady] returns `true` (defaults to `response.success`). + Future detectRootWithRetry( + Uri vmServiceUri, { + bool cacheResult = true, + bool Function(server.DetectRootPackageResponse response)? isReady, + }) async { late server.DetectRootPackageResponse response; await runWithRetry( callback: () async { response = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: true, dtd: testDtdConnection!, - cacheResult: false, + cacheResult: cacheResult, ); - if (!response.success) throw Exception('VM not ready'); + final ready = isReady?.call(response) ?? response.success; + if (!ready) { + throw Exception('VM not ready: ${response.message}'); + } }, maxRetries: 20, retryDelay: const Duration(milliseconds: 500), ); + return response; + } + + test('does not populate cache when cacheResult is false', () async { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + final response = await detectRootWithRetry( + vmServiceUri!, + cacheResult: false, + ); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); - expect(response.uri!.toFilePath(), endsWith(app!.directory.path)); + expect(response.uri!.toFilePath(), resolvedAppDirectoryPath); final disconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: false, dtd: testDtdConnection!, ); @@ -754,25 +965,11 @@ void main() { test('succeeds for a connect event', () async { final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); expect(vmServiceUri, isNotNull); - late server.DetectRootPackageResponse response; - await runWithRetry( - callback: () async { - response = - await server.VmServiceHandler.detectRootPackageForVmService( - vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, - connected: true, - dtd: testDtdConnection!, - ); - if (!response.success) throw Exception('VM not ready'); - }, - maxRetries: 20, - retryDelay: const Duration(milliseconds: 500), - ); + final response = await detectRootWithRetry(vmServiceUri!); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); - expect(response.uri!.toFilePath(), endsWith(app!.directory.path)); + expect(response.uri!.toFilePath(), resolvedAppDirectoryPath); }); test('succeeds for a disconnect event when cache is empty', () async { @@ -791,30 +988,53 @@ void main() { () async { final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); expect(vmServiceUri, isNotNull); - late server.DetectRootPackageResponse response; - await runWithRetry( - callback: () async { - response = - await server.VmServiceHandler.detectRootPackageForVmService( - vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, - connected: true, - dtd: testDtdConnection!, - ); - if (!response.success) throw Exception('VM not ready'); - }, - maxRetries: 20, - retryDelay: const Duration(milliseconds: 500), - ); + final response = await detectRootWithRetry(vmServiceUri!); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); - expect(response.uri!.toFilePath(), endsWith(app!.directory.path)); + expect(response.uri!.toFilePath(), resolvedAppDirectoryPath); + + final disconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(disconnectResponse.success, true); + expect(disconnectResponse.message, isNull); + expect(disconnectResponse.uri, isNotNull); + expect( + disconnectResponse.uri!.toFilePath(), + resolvedAppDirectoryPath, + ); + + // Verify the cache entry was removed on disconnect. + final secondDisconnect = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(secondDisconnect, (success: true, message: null, uri: null)); + }, + ); + + test( + 'succeeds for a disconnect event even if pubspec.yaml was deleted', + () async { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + final response = await detectRootWithRetry(vmServiceUri!); + expect(response.success, true); + + File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); final disconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: false, dtd: testDtdConnection!, ); @@ -823,7 +1043,7 @@ void main() { expect(disconnectResponse.uri, isNotNull); expect( disconnectResponse.uri!.toFilePath(), - endsWith(app!.directory.path), + resolvedAppDirectoryPath, ); // Disconnecting again should be a no-op since the cache entry was @@ -842,6 +1062,95 @@ void main() { )); }, ); + + test( + 'rejects and does not cache root directory without package markers', + () async { + File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + final response = await detectRootWithRetry( + vmServiceUri!, + isReady: (r) => + r.message?.contains('Invalid package root URI') ?? false, + ); + expect(response.success, false); + expect( + response.message, + contains( + 'directory does not contain pubspec.yaml or ' + '.dart_tool/package_config.json', + ), + ); + expect(response.uri, isNull); + + // Verify the rejected root was not cached for disconnect. + final disconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(disconnectResponse, ( + success: true, + message: null, + uri: null, + )); + }, + ); + + test( + '$apiNotifyForVmServiceConnection rejects root without package markers and leaves DTD workspace roots empty', + () async { + File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + + // Wait until the test app's main isolate is ready before invoking + // the full HTTP handler. + await detectRootWithRetry( + vmServiceUri!, + isReady: (r) => + r.message?.contains('Invalid package root URI') ?? false, + ); + + final wsVmServiceUri = convertToWebSocketUrl( + serviceProtocolUrl: Uri.parse(vmServiceUriString!), + ).toString(); + final request = Request( + 'post', + Uri( + scheme: 'https', + host: 'localhost', + path: apiNotifyForVmServiceConnection, + queryParameters: { + apiParameterValueKey: wsVmServiceUri, + apiParameterVmServiceConnected: 'true', + }, + ), + headers: const {devToolsRequestHeader: '1'}, + ); + final response = await server.ServerApi.handle( + request, + extensionsManager: ExtensionsManager(), + deeplinkManager: FakeDeeplinkManager(), + dtd: dtd!.info, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect( + await response.readAsString(), + contains( + 'directory does not contain pubspec.yaml or ' + '.dart_tool/package_config.json', + ), + ); + final currentRoots = + (await testDtdConnection!.getIDEWorkspaceRoots()) + .ideWorkspaceRoots; + expect(currentRoots, isEmpty); + }, + ); }); }); }); diff --git a/packages/devtools_shared/test/utils/file_utils_test.dart b/packages/devtools_shared/test/utils/file_utils_test.dart index f8b5bdc2f0b..c397d11fb2e 100644 --- a/packages/devtools_shared/test/utils/file_utils_test.dart +++ b/packages/devtools_shared/test/utils/file_utils_test.dart @@ -155,6 +155,80 @@ void main() { ); } }); + + group('isValidLocalFileUri and isValidLocalFileUriString', () { + test('accepts valid POSIX and Windows local file URIs', () { + for (final valid in const [ + 'file:///Users/me/my_app', + 'file:///Users/me/my%20app/.dart_tool', + 'file:///app', + 'file:///C:/my_app', + 'file:///C:/Users/me/my_app', + ]) { + expect(isValidLocalFileUriString(valid), isTrue, reason: valid); + expect(isValidLocalFileUri(Uri.parse(valid)), isTrue, reason: valid); + } + }); + + test('rejects null, empty, relative, and non-file:// URI strings', () { + expect(isValidLocalFileUriString(null), isFalse); + expect(isValidLocalFileUriString(''), isFalse); + expect(isValidLocalFileUriString('/Users/me/my_app'), isFalse); + expect(isValidLocalFileUriString('file:/Users/me/my_app'), isFalse); + expect(isValidLocalFileUriString('file:relative/my_app'), isFalse); + expect(isValidLocalFileUriString('http://localhost/my_app'), isFalse); + expect(isValidLocalFileUriString('package:my_app/main.dart'), isFalse); + expect(isValidLocalFileUri(Uri.parse('/Users/me/my_app')), isFalse); + expect(isValidLocalFileUri(Uri.parse('relative/my_app')), isFalse); + expect( + isValidLocalFileUri(Uri.parse('http://localhost/my_app')), + isFalse, + ); + expect( + isValidLocalFileUri(Uri.parse('package:my_app/main.dart')), + isFalse, + ); + }); + + test( + 'rejects non-empty authorities, UNC paths, queries, and fragments', + () { + for (final invalid in const [ + 'file://server/share/my_app', + 'file:////server/share/my_app', + 'file://localhost/Users/me/my_app', + 'file://127.0.0.1/Users/me/my_app', + 'file://user@/Users/me/my_app', + 'file:///Users/me/my_app?query=1', + 'file:///Users/me/my_app#fragment', + ]) { + expect(isValidLocalFileUriString(invalid), isFalse, reason: invalid); + expect( + isValidLocalFileUri(Uri.parse(invalid)), + isFalse, + reason: invalid, + ); + } + }, + ); + + test('rejects encoded slashes, null bytes, and invalid file paths', () { + for (final invalid in [ + 'file:///tmp/a%2f..%2fb', + 'file:///tmp/a%2Fb', + 'file:///tmp/a%00b', + 'file:///tmp/%FF', + if (Platform.isWindows) ...['file:///C:foo', 'file:///tmp/a%5cb'], + ]) { + expect(isValidLocalFileUriString(invalid), isFalse, reason: invalid); + expect( + isValidLocalFileUri(Uri.parse(invalid)), + isFalse, + reason: invalid, + ); + } + }); + }); } /// Sets up the directory structure for each test.