From bed25d3d0497d1ee72af2d0f813055a0fdeacccf Mon Sep 17 00:00:00 2001 From: John Ryan Date: Tue, 17 Nov 2026 10:47:32 -0800 Subject: [PATCH 1/7] Validates package root URIs This change validates the detected directory in VmServiceHandler before caching it or updating DTD, requiring that it: is a local file:// URI with no authority, query, fragment, or dot-segment traversal (. / ..), does not point or resolve (via symlinks) to the filesystem root or the user's home directory (HOME / USERPROFILE), and exists on disk and contains either pubspec.yaml or .dart_tool/package_config.json. It also extracts shared isValidLocalFileUri and isValidLocalFileUriString helpers in file_utils.dart (reused by ExtensionsManager and the extensions API handler) and adds unit and server API tests covering valid roots, invalid URI forms, filesystem/home root rejection, missing package markers, and end-to-end /api/notifyForVmServiceConnection handling. Makes progress towards: * https://github.com/flutter/dash-devexp-internal/issues/88 * https://github.com/flutter/dash-devexp-internal/issues/93 --- packages/devtools_shared/CHANGELOG.md | 2 + .../lib/src/extensions/extension_manager.dart | 10 +- .../server/handlers/_devtools_extensions.dart | 26 +- .../lib/src/server/handlers/_vm_service.dart | 145 ++++++++ .../lib/src/utils/file_utils.dart | 50 +++ .../test/server/general_api_test.dart | 334 +++++++++++++++++- .../test/utils/file_utils_test.dart | 80 +++++ 7 files changed, 614 insertions(+), 33 deletions(-) diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 50bc259549b..22fd1a07d74 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -35,6 +35,8 @@ 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`). +* Validate detected package roots in `VmServiceHandler` before caching or updating DTD + IDE workspace roots. # 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..532e384ac08 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,8 +152,7 @@ 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 ' @@ -361,11 +361,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 (!isValidLocalFileUriString(uriString)) { throw ArgumentError.value( uriString, 'uriString', 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..f61ad6600b6 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -23,17 +23,13 @@ extension _ExtensionsApiHandler on Never { final logs = []; final rootFileUriString = 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) { - return api.badRequest( - 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a ' - 'file:// URI with an empty host.', - ); - } + if (rootFileUriString != null && + rootFileUriString.isNotEmpty && + !isValidLocalFileUriString(rootFileUriString)) { + return api.badRequest( + 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a ' + 'file:// URI with an empty host.', + ); } final result = {}; @@ -103,9 +99,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()) : ''; @@ -130,7 +124,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()); @@ -181,7 +175,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 94fd867e199..a960efadd78 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,11 @@ part of '../server_api.dart'; /// A namespace for VM service related server request handlers. @visibleForTesting extension VmServiceHandler on Never { + static const _pubspecYamlFileName = 'pubspec.yaml'; + static const _dartToolDirName = '.dart_tool'; + static const _packageConfigJsonFileName = 'package_config.json'; + static const _homeEnvVarKeys = ['HOME', 'USERPROFILE']; + /// Stores the calculated package roots for VM service connections that are /// initiated in [handleNotifyForVmServiceConnection]. /// @@ -18,6 +23,133 @@ extension VmServiceHandler on Never { /// never be used. static final _packageRootsForVmServiceConnections = {}; + /// Returns whether [rootPackageUri] is a valid Dart or Flutter package root + /// directory that can safely be registered as a DTD IDE workspace root. + @visibleForTesting + static bool isValidRootPackageUri( + Uri rootPackageUri, { + @visibleForTesting Map? environment, + }) => + _validateRootPackageUri(rootPackageUri, environment: environment) == null; + + /// 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. + /// + /// Returns `null` if [rootPackageUri] is valid, or an error message if it + /// must be rejected. + static String? _validateRootPackageUri( + Uri rootPackageUri, { + Map? environment, + }) { + if (!isValidLocalFileUri(rootPackageUri)) { + return 'Invalid package root URI ($rootPackageUri): must be a file:// ' + 'URI with an empty host.'; + } + + final String dirPath; + try { + dirPath = p.normalize(rootPackageUri.toFilePath()); + } catch (e) { + return 'Invalid package root URI ($rootPackageUri): $e'; + } + + if (p.equals(dirPath, p.rootPrefix(dirPath))) { + return 'Invalid package root URI ($rootPackageUri): cannot be the ' + 'filesystem root.'; + } + + final dir = Directory(dirPath); + final resolvedDirPath = _tryResolveSymbolicLinks(dir); + if (resolvedDirPath != null && + p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) { + return 'Invalid package root URI ($rootPackageUri): cannot resolve to ' + 'the filesystem root.'; + } + + if (_isUserHomeDirectory( + dirPath, + resolvedDirPath: resolvedDirPath, + environment: environment ?? Platform.environment, + )) { + return 'Invalid package root URI ($rootPackageUri): cannot be the user ' + 'home directory.'; + } + + if (!dir.existsSync()) { + return 'Invalid package root URI ($rootPackageUri): directory does not ' + 'exist.'; + } + + final hasPubspec = File(p.join(dirPath, _pubspecYamlFileName)).existsSync(); + final hasPackageConfig = File( + p.join(dirPath, _dartToolDirName, _packageConfigJsonFileName), + ).existsSync(); + if (!hasPubspec && !hasPackageConfig) { + return 'Invalid package root URI ($rootPackageUri): directory does not ' + 'contain $_pubspecYamlFileName or ' + '$_dartToolDirName/$_packageConfigJsonFileName.'; + } + + return null; + } + + /// Returns whether [dirPath] (or its resolved target [resolvedDirPath]) + /// matches the current user's home directory from `HOME` or `USERPROFILE`. + static bool _isUserHomeDirectory( + String dirPath, { + required 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); + if (p.equals(dirPath, normalizedHome) || + (resolvedDirPath != null && + p.equals(resolvedDirPath, normalizedHome))) { + return true; + } + final resolvedHome = _tryResolveSymbolicLinks(Directory(normalizedHome)); + if (resolvedHome != null && + (p.equals(dirPath, resolvedHome) || + (resolvedDirPath != null && + p.equals(resolvedDirPath, resolvedHome)))) { + return true; + } + } + return false; + } + + /// Resolves symbolic links for [directory] if it exists, returning `null` if + /// it does not exist or resolution fails. + static String? _tryResolveSymbolicLinks(Directory directory) { + if (!directory.existsSync()) return null; + try { + return p.normalize(directory.resolveSymbolicLinksSync()); + } on FileSystemException { + return null; + } + } + + /// 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, @@ -137,6 +269,10 @@ extension VmServiceHandler on Never { ); } rootPackageUri = Uri.parse(root); + final validationError = _validateRootPackageUri(rootPackageUri); + if (validationError != null) { + return (success: false, message: validationError, uri: null); + } _packageRootsForVmServiceConnections[vmServiceUriAsString] = rootPackageUri; } catch (e) { @@ -156,6 +292,11 @@ extension VmServiceHandler on Never { // If there is no root to remove, there is nothing for us to do. return (success: true, message: null, uri: null); } + final validationError = _validateRootPackageUri(cachedRootForVmService); + if (validationError != null) { + _packageRootsForVmServiceConnections.remove(vmServiceUriAsString); + return (success: false, message: validationError, uri: null); + } rootPackageUri = cachedRootForVmService; } return (success: true, message: null, uri: rootPackageUri); @@ -169,6 +310,10 @@ extension VmServiceHandler on Never { required bool connected, required ServerApi api, }) async { + final validationError = _validateRootPackageUri(rootFromVmService); + if (validationError != null) { + return api.badRequest(validationError); + } final currentRoots = (await dtd.getIDEWorkspaceRoots()).ideWorkspaceRoots .toSet(); // Add or remove [rootFromVmService] depending on whether this was a diff --git a/packages/devtools_shared/lib/src/utils/file_utils.dart b/packages/devtools_shared/lib/src/utils/file_utils.dart index e9137974545..c35b3cf2df2 100644 --- a/packages/devtools_shared/lib/src/utils/file_utils.dart +++ b/packages/devtools_shared/lib/src/utils/file_utils.dart @@ -100,3 +100,53 @@ String _assertUriFormatAndReturn(String uriString) { ); return uriString; } + +/// Returns whether [uri] is a valid local `file:` URI without an authority, +/// query, fragment, or dot path traversal segments. +/// +/// Requiring an empty authority rejects remote hosts, ports, user info, and +/// Windows UNC paths (e.g. `file://server/share/...`). Requiring an absolute +/// path without query or fragment components ensures [Uri.toFilePath] will not +/// throw an [UnsupportedError]. +bool isValidLocalFileUri(Uri uri) { + if (uri.scheme != 'file' || + uri.authority.isNotEmpty || + !uri.hasAbsolutePath || + uri.hasQuery || + uri.hasFragment) { + return false; + } + for (final segment in uri.pathSegments) { + for (final part in segment.split(r'\')) { + if (part == '.' || part == '..') return false; + } + } + return true; +} + +/// Returns whether [uriString] is a `file://` URI string without dot-segment +/// traversal (`.` or `..`) 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); + if (uri == null || !isValidLocalFileUri(uri)) { + return false; + } + // Check raw segments before `Uri.tryParse` normalizes `.` and `..` away. + final rawPath = uriString.substring(_fileUriPrefix.length); + for (final segment in rawPath.split('/')) { + if (segment == '.' || segment == '..') return false; + try { + final decoded = Uri.decodeComponent(segment); + for (final part in decoded.split(r'\')) { + if (part == '.' || part == '..') return false; + } + } on ArgumentError { + return false; + } + } + return true; +} diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index f0902307d63..5578968841d 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'; @@ -656,11 +658,21 @@ void main() { }); group('updateDtdWorkspaceRoots', () { - Future updateWorkspaceRoots({ + late Directory tempDir; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('dtd_roots_test_'); + }); + + tearDown(() async { + await deleteDirectoryWithRetry(tempDir); + }); + + Future updateWorkspaceRoots({ required Uri root, required bool connected, - }) async { - await server.VmServiceHandler.updateDtdWorkspaceRoots( + }) { + return server.VmServiceHandler.updateDtdWorkspaceRoots( testDtdConnection!, dtdConnectionInfo: dtd!.info!, rootFromVmService: root, @@ -678,26 +690,213 @@ void main() { test('adds and removes workspace roots', () async { await verifyWorkspaceRoots({}); - final rootUri1 = Uri.parse('file:///Users/me/package_root_1'); - final rootUri2 = Uri.parse('file:///Users/me/package_root_2'); + final pkgDir1 = Directory(p.join(tempDir.path, 'package_root_1')) + ..createSync(recursive: true); + File(p.join(pkgDir1.path, 'pubspec.yaml')).createSync(); + final pkgDir2 = Directory(p.join(tempDir.path, 'package_root_2')) + ..createSync(recursive: true); + File( + p.join(pkgDir2.path, '.dart_tool', 'package_config.json'), + ).createSync(recursive: true); + + final rootUri1 = Uri.file(pkgDir1.path); + final rootUri2 = Uri.file(pkgDir2.path); - await updateWorkspaceRoots(root: rootUri1, connected: true); + final add1Response = await updateWorkspaceRoots( + root: rootUri1, + connected: true, + ); + expect(add1Response.statusCode, HttpStatus.ok); await verifyWorkspaceRoots({rootUri1}); // Add a second root and verify the roots are unioned. - await updateWorkspaceRoots(root: rootUri2, connected: true); + final add2Response = await updateWorkspaceRoots( + root: rootUri2, + connected: true, + ); + expect(add2Response.statusCode, HttpStatus.ok); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify duplicates cannot be added. - await updateWorkspaceRoots(root: rootUri2, connected: true); + final dupResponse = await updateWorkspaceRoots( + root: rootUri2, + connected: true, + ); + expect(dupResponse.statusCode, HttpStatus.ok); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify roots are removed for disconnect events. - await updateWorkspaceRoots(root: rootUri2, connected: false); + final remove2Response = await updateWorkspaceRoots( + root: rootUri2, + connected: false, + ); + expect(remove2Response.statusCode, HttpStatus.ok); await verifyWorkspaceRoots({rootUri1}); - await updateWorkspaceRoots(root: rootUri1, connected: false); + final remove1Response = await updateWorkspaceRoots( + root: rootUri1, + connected: false, + ); + expect(remove1Response.statusCode, HttpStatus.ok); await verifyWorkspaceRoots({}); }, timeout: const Timeout.factor(4)); + + test( + 'rejects filesystem root and symlinks to filesystem root', + () async { + await verifyWorkspaceRoots({}); + final rootPrefix = p.rootPrefix(tempDir.path); + final response = await updateWorkspaceRoots( + root: Uri.file(rootPrefix), + connected: true, + ); + expect(response.statusCode, HttpStatus.badRequest); + expect(await response.readAsString(), contains('filesystem root')); + + final symlinkToRoot = Link(p.join(tempDir.path, 'root_link')) + ..createSync(rootPrefix); + final symlinkResponse = await updateWorkspaceRoots( + root: Uri.file(symlinkToRoot.path), + connected: true, + ); + expect(symlinkResponse.statusCode, HttpStatus.badRequest); + expect( + await symlinkResponse.readAsString(), + contains('filesystem root'), + ); + + await verifyWorkspaceRoots({}); + }, + ); + + test( + 'rejects non-file schemes, non-empty authorities, and invalid URI components', + () async { + await verifyWorkspaceRoots({}); + final validPkg = Directory(p.join(tempDir.path, 'valid_pkg')) + ..createSync(recursive: true); + File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); + final validPkgUri = Uri.file(validPkg.path); + + for (final invalidUri in [ + Uri.parse('http://localhost/path/to/pkg'), + Uri.parse('file://evil.host/path/to/pkg'), + Uri.parse('file://user@/path/to/pkg'), + Uri.parse('$validPkgUri?query=1'), + Uri.parse('$validPkgUri#fragment'), + Uri.parse('${Uri.directory(tempDir.path)}other%5c..%5cvalid_pkg'), + ]) { + final response = await updateWorkspaceRoots( + root: invalidUri, + connected: true, + ); + expect( + response.statusCode, + HttpStatus.badRequest, + reason: 'Expected $invalidUri to be rejected', + ); + } + await verifyWorkspaceRoots({}); + }, + ); + + test('rejects user home directory (HOME and USERPROFILE)', () async { + await verifyWorkspaceRoots({}); + final homeDir = + Platform.environment['HOME'] ?? + Platform.environment['USERPROFILE']; + if (homeDir != null && homeDir.isNotEmpty) { + final response = await updateWorkspaceRoots( + root: Uri.file(homeDir), + connected: true, + ); + expect(response.statusCode, HttpStatus.badRequest); + expect(await response.readAsString(), 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); + final symlinkResponse = await updateWorkspaceRoots( + root: Uri.file(symlinkToHome.path), + connected: true, + ); + expect(symlinkResponse.statusCode, HttpStatus.badRequest); + expect( + await symlinkResponse.readAsString(), + contains('home directory'), + ); + } + + // Verify both HOME and USERPROFILE environment variables are checked + // even when the directory contains a pubspec.yaml file. + final fakeHomePkg = Directory(p.join(tempDir.path, 'fake_home')) + ..createSync(recursive: true); + File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + ), + isTrue, + ); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'HOME': fakeHomePkg.path}, + ), + isFalse, + ); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'USERPROFILE': fakeHomePkg.path}, + ), + isFalse, + ); + + await verifyWorkspaceRoots({}); + }); + + test( + 'rejects directories that do not exist or lack package markers', + () async { + await verifyWorkspaceRoots({}); + + // Non-existent directory. + final nonExistentUri = Uri.file( + p.join(tempDir.path, 'does_not_exist'), + ); + final nonExistentResponse = await updateWorkspaceRoots( + root: nonExistentUri, + connected: true, + ); + expect(nonExistentResponse.statusCode, HttpStatus.badRequest); + expect( + await nonExistentResponse.readAsString(), + 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); + final nonPackageResponse = await updateWorkspaceRoots( + root: Uri.file(nonPackageDir.path), + connected: true, + ); + expect(nonPackageResponse.statusCode, HttpStatus.badRequest); + expect( + await nonPackageResponse.readAsString(), + contains( + 'directory does not contain pubspec.yaml or ' + '.dart_tool/package_config.json', + ), + ); + + await verifyWorkspaceRoots({}); + }, + ); }); group('detectRootPackageForVmService', () { @@ -708,6 +907,7 @@ void main() { app = TestDartApp(); vmServiceUriString = await app!.start(); expect(vmServiceUriString, isNotEmpty); + File(p.join(app!.directory.path, 'pubspec.yaml')).createSync(); }); tearDown(() async { @@ -792,6 +992,120 @@ 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); + late server.DetectRootPackageResponse response; + await runWithRetry( + callback: () async { + response = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri!, + connected: true, + dtd: testDtdConnection!, + ); + if (response.message == null || + !response.message!.contains('Invalid package root URI')) { + throw Exception('VM not ready: ${response.message}'); + } + }, + maxRetries: 20, + retryDelay: const Duration(milliseconds: 500), + ); + 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 runWithRetry( + callback: () async { + final probe = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri!, + connected: true, + dtd: testDtdConnection!, + ); + if (probe.message == null || + !probe.message!.contains('Invalid package root URI')) { + throw Exception('VM not ready: ${probe.message}'); + } + }, + maxRetries: 20, + retryDelay: const Duration(milliseconds: 500), + ); + + 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..bc62753fa2e 100644 --- a/packages/devtools_shared/test/utils/file_utils_test.dart +++ b/packages/devtools_shared/test/utils/file_utils_test.dart @@ -155,6 +155,86 @@ 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, queries, and fragments', () { + for (final invalid in const [ + '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 dot and dot-dot path traversal segments', () { + for (final traversalString in const [ + 'file:///Users/me/../other_app', + 'file:///Users/me/./my_app', + 'file:///Users/me/%2e%2e/other_app', + 'file:///Users/me/%2e/my_app', + 'file:///C:/Users/me%5c..%5cother_app', + ]) { + expect( + isValidLocalFileUriString(traversalString), + isFalse, + reason: traversalString, + ); + } + + for (final traversalUri in [ + Uri.parse('file:///C:/Users/me%5c..%5cother_app'), + Uri.parse('file:///C:/Users/me%5c.%5cmy_app'), + ]) { + expect( + isValidLocalFileUri(traversalUri), + isFalse, + reason: '$traversalUri', + ); + } + }); + }); } /// Sets up the directory structure for each test. From c94e2e6fce09789acd98fae7e1fa6da0c167e9d4 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Wed, 18 Nov 2026 15:26:19 -0800 Subject: [PATCH 2/7] Allow disconnect when path is invalid, fix bug in disconnect code --- .../lib/src/server/handlers/_vm_service.dart | 17 ++-- .../test/server/general_api_test.dart | 78 +++++++++++++++++++ 2 files changed, 85 insertions(+), 10 deletions(-) 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 a960efadd78..b1eb4221a64 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -286,17 +286,12 @@ extension VmServiceHandler on Never { vmService = null; } } else { - final cachedRootForVmService = - _packageRootsForVmServiceConnections[vmServiceUriAsString]; + final cachedRootForVmService = _packageRootsForVmServiceConnections + .remove(vmServiceUriAsString); if (cachedRootForVmService == null) { // If there is no root to remove, there is nothing for us to do. return (success: true, message: null, uri: null); } - final validationError = _validateRootPackageUri(cachedRootForVmService); - if (validationError != null) { - _packageRootsForVmServiceConnections.remove(vmServiceUriAsString); - return (success: false, message: validationError, uri: null); - } rootPackageUri = cachedRootForVmService; } return (success: true, message: null, uri: rootPackageUri); @@ -310,9 +305,11 @@ extension VmServiceHandler on Never { required bool connected, required ServerApi api, }) async { - final validationError = _validateRootPackageUri(rootFromVmService); - if (validationError != null) { - return api.badRequest(validationError); + if (connected) { + final validationError = _validateRootPackageUri(rootFromVmService); + if (validationError != null) { + return api.badRequest(validationError); + } } final currentRoots = (await dtd.getIDEWorkspaceRoots()).ideWorkspaceRoots .toSet(); diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index 5578968841d..99e03875693 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -740,6 +740,33 @@ void main() { await verifyWorkspaceRoots({}); }, timeout: const Timeout.factor(4)); + test( + 'removes workspace root on disconnect even if directory was deleted', + () async { + await verifyWorkspaceRoots({}); + final pkgDir = Directory(p.join(tempDir.path, 'deleted_pkg')) + ..createSync(recursive: true); + File(p.join(pkgDir.path, 'pubspec.yaml')).createSync(); + final rootUri = Uri.file(pkgDir.path); + + final addResponse = await updateWorkspaceRoots( + root: rootUri, + connected: true, + ); + expect(addResponse.statusCode, HttpStatus.ok); + await verifyWorkspaceRoots({rootUri}); + + pkgDir.deleteSync(recursive: true); + + final removeResponse = await updateWorkspaceRoots( + root: rootUri, + connected: false, + ); + expect(removeResponse.statusCode, HttpStatus.ok); + await verifyWorkspaceRoots({}); + }, + ); + test( 'rejects filesystem root and symlinks to filesystem root', () async { @@ -990,6 +1017,57 @@ void main() { disconnectResponse.uri!.toFilePath(), endsWith(app!.directory.path), ); + + // 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); + 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), + ); + expect(response.success, true); + + File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); + + 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(), + endsWith(app!.directory.path), + ); }, ); From 42b33a668215e083c4277f2f8ea7c29caaaee197 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Wed, 18 Nov 2026 15:30:06 -0800 Subject: [PATCH 3/7] Add release note entry --- packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 1dfdcb637d3..05780bed740 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 From 351c413b8f846f026417e9029545a67fa1ee1b88 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Mon, 23 Nov 2026 08:43:58 -0800 Subject: [PATCH 4/7] Address PR #10096 review feedback for local file URI and package root validation. * Reject encoded slashes (`/` / `%2f`) in `isValidLocalFileUri` path segments and validate raw `root` strings with `isValidLocalFileUriString` before `Uri.parse` in `detectRootPackageForVmService`, with new `%2f` test coverage. * Simplify `_validateRootPackageUri` to check `dir.existsSync()` first, resolve symlinks once (failing closed on `FileSystemException`), and compare only the resolved path against the filesystem root and resolved home directory. * Remove duplicate `_validateRootPackageUri` validation from `updateDtdWorkspaceRoots` and move its rejection tests to standalone `isValidRootPackageUri` unit tests without DTD. * Extract the repeated `runWithRetry` polling blocks in `detectRootPackageForVmService` tests into a shared `detectRootWithRetry` helper. * Update invalid-URI error messages in `_vm_service.dart` and `_devtools_extensions.dart`, add doc comments to `VmServiceHandler` constants, remove redundant `@visibleForTesting`, and document the new helpers and stricter URI checks in `packages/devtools_shared/CHANGELOG.md`. --- packages/devtools_shared/CHANGELOG.md | 5 + .../server/handlers/_devtools_extensions.dart | 5 +- .../lib/src/server/handlers/_vm_service.dart | 92 ++-- .../lib/src/utils/file_utils.dart | 1 + .../test/server/general_api_test.dart | 412 ++++++++---------- .../test/utils/file_utils_test.dart | 4 + 6 files changed, 247 insertions(+), 272 deletions(-) diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 22fd1a07d74..4f7cfe6cf26 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -35,6 +35,11 @@ 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`). +* Add `isValidLocalFileUri` and `isValidLocalFileUriString` helpers to validate + local `file://` URIs without authorities, queries, fragments, encoded slashes, + or `.`/`..` path traversal segments, and apply them in + `api/serveAvailableExtensions`, `api/extensionEnabledState`, and + `ExtensionsManager`. * Validate detected package roots in `VmServiceHandler` before caching or updating DTD IDE workspace roots. 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 f61ad6600b6..7ca3a2e0af9 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -27,8 +27,9 @@ extension _ExtensionsApiHandler on Never { rootFileUriString.isNotEmpty && !isValidLocalFileUriString(rootFileUriString)) { return api.badRequest( - 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a ' - 'file:// URI with an empty host.', + 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be an ' + 'absolute file:// URI with no host, query, fragment, or `.`/`..` ' + 'segments.', ); } final result = {}; 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 b1eb4221a64..cf6335e0e01 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -7,11 +7,24 @@ 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']; + /// Error description for invalid local `file://` package root URIs. + static const _invalidLocalFileUriMessage = + 'must be an absolute file:// URI with no host, query, fragment, or ' + '`.`/`..` segments.'; + /// Stores the calculated package roots for VM service connections that are /// initiated in [handleNotifyForVmServiceConnection]. /// @@ -28,7 +41,7 @@ extension VmServiceHandler on Never { @visibleForTesting static bool isValidRootPackageUri( Uri rootPackageUri, { - @visibleForTesting Map? environment, + Map? environment, }) => _validateRootPackageUri(rootPackageUri, environment: environment) == null; @@ -43,8 +56,8 @@ extension VmServiceHandler on Never { Map? environment, }) { if (!isValidLocalFileUri(rootPackageUri)) { - return 'Invalid package root URI ($rootPackageUri): must be a file:// ' - 'URI with an empty host.'; + return 'Invalid package root URI ($rootPackageUri): ' + '$_invalidLocalFileUriMessage'; } final String dirPath; @@ -54,36 +67,38 @@ extension VmServiceHandler on Never { return 'Invalid package root URI ($rootPackageUri): $e'; } - if (p.equals(dirPath, p.rootPrefix(dirPath))) { - return 'Invalid package root URI ($rootPackageUri): cannot be the ' - 'filesystem root.'; + final dir = Directory(dirPath); + if (!dir.existsSync()) { + return 'Invalid package root URI ($rootPackageUri): directory does not ' + 'exist.'; } - final dir = Directory(dirPath); - final resolvedDirPath = _tryResolveSymbolicLinks(dir); - if (resolvedDirPath != null && - p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) { - return 'Invalid package root URI ($rootPackageUri): cannot resolve to ' - 'the filesystem root.'; + final String resolvedDirPath; + try { + resolvedDirPath = p.normalize(dir.resolveSymbolicLinksSync()); + } on FileSystemException catch (e) { + return 'Invalid package root URI ($rootPackageUri): failed to resolve ' + 'symbolic links ($e).'; + } + + if (p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) { + return 'Invalid package root URI ($rootPackageUri): cannot be the ' + 'filesystem root.'; } if (_isUserHomeDirectory( - dirPath, - resolvedDirPath: resolvedDirPath, + resolvedDirPath, environment: environment ?? Platform.environment, )) { return 'Invalid package root URI ($rootPackageUri): cannot be the user ' 'home directory.'; } - if (!dir.existsSync()) { - return 'Invalid package root URI ($rootPackageUri): directory does not ' - 'exist.'; - } - - final hasPubspec = File(p.join(dirPath, _pubspecYamlFileName)).existsSync(); + final hasPubspec = File( + p.join(resolvedDirPath, _pubspecYamlFileName), + ).existsSync(); final hasPackageConfig = File( - p.join(dirPath, _dartToolDirName, _packageConfigJsonFileName), + p.join(resolvedDirPath, _dartToolDirName, _packageConfigJsonFileName), ).existsSync(); if (!hasPubspec && !hasPackageConfig) { return 'Invalid package root URI ($rootPackageUri): directory does not ' @@ -94,27 +109,19 @@ extension VmServiceHandler on Never { return null; } - /// Returns whether [dirPath] (or its resolved target [resolvedDirPath]) - /// matches the current user's home directory from `HOME` or `USERPROFILE`. + /// Returns whether [resolvedDirPath] matches the current user's home + /// directory from `HOME` or `USERPROFILE`. static bool _isUserHomeDirectory( - String dirPath, { - required String? resolvedDirPath, + 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); - if (p.equals(dirPath, normalizedHome) || - (resolvedDirPath != null && - p.equals(resolvedDirPath, normalizedHome))) { - return true; - } - final resolvedHome = _tryResolveSymbolicLinks(Directory(normalizedHome)); - if (resolvedHome != null && - (p.equals(dirPath, resolvedHome) || - (resolvedDirPath != null && - p.equals(resolvedDirPath, resolvedHome)))) { + final resolvedHome = + _tryResolveSymbolicLinks(Directory(normalizedHome)) ?? normalizedHome; + if (p.equals(resolvedDirPath, resolvedHome)) { return true; } } @@ -268,6 +275,15 @@ extension VmServiceHandler on Never { uri: null, ); } + if (!isValidLocalFileUriString(root)) { + return ( + success: false, + message: + 'Invalid package root URI ($root): ' + '$_invalidLocalFileUriMessage', + uri: null, + ); + } rootPackageUri = Uri.parse(root); final validationError = _validateRootPackageUri(rootPackageUri); if (validationError != null) { @@ -305,12 +321,6 @@ extension VmServiceHandler on Never { required bool connected, required ServerApi api, }) async { - if (connected) { - final validationError = _validateRootPackageUri(rootFromVmService); - if (validationError != null) { - return api.badRequest(validationError); - } - } final currentRoots = (await dtd.getIDEWorkspaceRoots()).ideWorkspaceRoots .toSet(); // Add or remove [rootFromVmService] depending on whether this was a diff --git a/packages/devtools_shared/lib/src/utils/file_utils.dart b/packages/devtools_shared/lib/src/utils/file_utils.dart index c35b3cf2df2..b26d6adc684 100644 --- a/packages/devtools_shared/lib/src/utils/file_utils.dart +++ b/packages/devtools_shared/lib/src/utils/file_utils.dart @@ -117,6 +117,7 @@ bool isValidLocalFileUri(Uri uri) { return false; } for (final segment in uri.pathSegments) { + if (segment.contains('/')) return false; for (final part in segment.split(r'\')) { if (part == '.' || part == '..') return false; } diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index 99e03875693..0fd107ab74e 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -638,6 +638,158 @@ void main() { ); }); + group('isValidRootPackageUri', () { + 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', + () { + final pkgWithPubspec = Directory(p.join(tempDir.path, 'pkg_1')) + ..createSync(recursive: true); + File(p.join(pkgWithPubspec.path, 'pubspec.yaml')).createSync(); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(pkgWithPubspec.path), + ), + isTrue, + ); + + 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); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(pkgWithConfig.path), + ), + isTrue, + ); + }, + ); + + test('rejects filesystem root and symlinks to filesystem root', () { + final rootPrefix = p.rootPrefix(tempDir.path); + expect( + server.VmServiceHandler.isValidRootPackageUri(Uri.file(rootPrefix)), + isFalse, + ); + + final symlinkToRoot = Link(p.join(tempDir.path, 'root_link')) + ..createSync(rootPrefix); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(symlinkToRoot.path), + ), + isFalse, + ); + }); + + test( + 'rejects non-file schemes, non-empty authorities, and invalid URI components', + () { + final validPkg = Directory(p.join(tempDir.path, 'valid_pkg')) + ..createSync(recursive: true); + File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); + final validPkgUri = Uri.file(validPkg.path); + + for (final invalidUri in [ + Uri.parse('http://localhost/path/to/pkg'), + Uri.parse('file://evil.host/path/to/pkg'), + Uri.parse('file://user@/path/to/pkg'), + Uri.parse('$validPkgUri?query=1'), + Uri.parse('$validPkgUri#fragment'), + Uri.parse('${Uri.directory(tempDir.path)}other%5c..%5cvalid_pkg'), + Uri.parse('${Uri.directory(tempDir.path)}other%2f..%2fvalid_pkg'), + ]) { + expect( + server.VmServiceHandler.isValidRootPackageUri(invalidUri), + isFalse, + reason: 'Expected $invalidUri to be rejected', + ); + } + }, + ); + + test('rejects user home directory (HOME and USERPROFILE)', () { + final homeDir = + Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; + if (homeDir != null && homeDir.isNotEmpty) { + expect( + server.VmServiceHandler.isValidRootPackageUri(Uri.file(homeDir)), + isFalse, + ); + + // 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.isValidRootPackageUri( + Uri.file(symlinkToHome.path), + ), + isFalse, + ); + } + + // Verify both HOME and USERPROFILE environment variables are checked + // even when the directory contains a pubspec.yaml file. + final fakeHomePkg = Directory(p.join(tempDir.path, 'fake_home')) + ..createSync(recursive: true); + File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + ), + isTrue, + ); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'HOME': fakeHomePkg.path}, + ), + isFalse, + ); + expect( + server.VmServiceHandler.isValidRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'USERPROFILE': fakeHomePkg.path}, + ), + isFalse, + ); + }); + + 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.isValidRootPackageUri(nonExistentUri), + isFalse, + ); + + // 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.isValidRootPackageUri( + Uri.file(nonPackageDir.path), + ), + isFalse, + ); + }); + }); + group('endpoints that require DTD', () { TestDtdConnectionInfo? dtd; DartToolingDaemon? testDtdConnection; @@ -766,164 +918,6 @@ void main() { await verifyWorkspaceRoots({}); }, ); - - test( - 'rejects filesystem root and symlinks to filesystem root', - () async { - await verifyWorkspaceRoots({}); - final rootPrefix = p.rootPrefix(tempDir.path); - final response = await updateWorkspaceRoots( - root: Uri.file(rootPrefix), - connected: true, - ); - expect(response.statusCode, HttpStatus.badRequest); - expect(await response.readAsString(), contains('filesystem root')); - - final symlinkToRoot = Link(p.join(tempDir.path, 'root_link')) - ..createSync(rootPrefix); - final symlinkResponse = await updateWorkspaceRoots( - root: Uri.file(symlinkToRoot.path), - connected: true, - ); - expect(symlinkResponse.statusCode, HttpStatus.badRequest); - expect( - await symlinkResponse.readAsString(), - contains('filesystem root'), - ); - - await verifyWorkspaceRoots({}); - }, - ); - - test( - 'rejects non-file schemes, non-empty authorities, and invalid URI components', - () async { - await verifyWorkspaceRoots({}); - final validPkg = Directory(p.join(tempDir.path, 'valid_pkg')) - ..createSync(recursive: true); - File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); - final validPkgUri = Uri.file(validPkg.path); - - for (final invalidUri in [ - Uri.parse('http://localhost/path/to/pkg'), - Uri.parse('file://evil.host/path/to/pkg'), - Uri.parse('file://user@/path/to/pkg'), - Uri.parse('$validPkgUri?query=1'), - Uri.parse('$validPkgUri#fragment'), - Uri.parse('${Uri.directory(tempDir.path)}other%5c..%5cvalid_pkg'), - ]) { - final response = await updateWorkspaceRoots( - root: invalidUri, - connected: true, - ); - expect( - response.statusCode, - HttpStatus.badRequest, - reason: 'Expected $invalidUri to be rejected', - ); - } - await verifyWorkspaceRoots({}); - }, - ); - - test('rejects user home directory (HOME and USERPROFILE)', () async { - await verifyWorkspaceRoots({}); - final homeDir = - Platform.environment['HOME'] ?? - Platform.environment['USERPROFILE']; - if (homeDir != null && homeDir.isNotEmpty) { - final response = await updateWorkspaceRoots( - root: Uri.file(homeDir), - connected: true, - ); - expect(response.statusCode, HttpStatus.badRequest); - expect(await response.readAsString(), 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); - final symlinkResponse = await updateWorkspaceRoots( - root: Uri.file(symlinkToHome.path), - connected: true, - ); - expect(symlinkResponse.statusCode, HttpStatus.badRequest); - expect( - await symlinkResponse.readAsString(), - contains('home directory'), - ); - } - - // Verify both HOME and USERPROFILE environment variables are checked - // even when the directory contains a pubspec.yaml file. - final fakeHomePkg = Directory(p.join(tempDir.path, 'fake_home')) - ..createSync(recursive: true); - File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); - expect( - server.VmServiceHandler.isValidRootPackageUri( - Uri.file(fakeHomePkg.path), - ), - isTrue, - ); - expect( - server.VmServiceHandler.isValidRootPackageUri( - Uri.file(fakeHomePkg.path), - environment: {'HOME': fakeHomePkg.path}, - ), - isFalse, - ); - expect( - server.VmServiceHandler.isValidRootPackageUri( - Uri.file(fakeHomePkg.path), - environment: {'USERPROFILE': fakeHomePkg.path}, - ), - isFalse, - ); - - await verifyWorkspaceRoots({}); - }); - - test( - 'rejects directories that do not exist or lack package markers', - () async { - await verifyWorkspaceRoots({}); - - // Non-existent directory. - final nonExistentUri = Uri.file( - p.join(tempDir.path, 'does_not_exist'), - ); - final nonExistentResponse = await updateWorkspaceRoots( - root: nonExistentUri, - connected: true, - ); - expect(nonExistentResponse.statusCode, HttpStatus.badRequest); - expect( - await nonExistentResponse.readAsString(), - 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); - final nonPackageResponse = await updateWorkspaceRoots( - root: Uri.file(nonPackageDir.path), - connected: true, - ); - expect(nonPackageResponse.statusCode, HttpStatus.badRequest); - expect( - await nonPackageResponse.readAsString(), - contains( - 'directory does not contain pubspec.yaml or ' - '.dart_tool/package_config.json', - ), - ); - - await verifyWorkspaceRoots({}); - }, - ); }); group('detectRootPackageForVmService', () { @@ -943,24 +937,35 @@ void main() { vmServiceUriString = null; }); - test('succeeds for a connect event', () async { - final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); - expect(vmServiceUri, isNotNull); + Future detectRootWithRetry( + Uri vmServiceUri, { + 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!, ); - 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('succeeds for a connect event', () async { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + final response = await detectRootWithRetry(vmServiceUri!); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); @@ -983,21 +988,7 @@ 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); @@ -1006,7 +997,7 @@ void main() { final disconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: false, dtd: testDtdConnection!, ); @@ -1035,21 +1026,7 @@ 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); File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); @@ -1057,7 +1034,7 @@ void main() { final disconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: false, dtd: testDtdConnection!, ); @@ -1077,23 +1054,11 @@ void main() { File(p.join(app!.directory.path, 'pubspec.yaml')).deleteSync(); 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.message == null || - !response.message!.contains('Invalid package root URI')) { - throw Exception('VM not ready: ${response.message}'); - } - }, - maxRetries: 20, - retryDelay: const Duration(milliseconds: 500), + final response = await detectRootWithRetry( + vmServiceUri!, + isReady: (r) => + r.message != null && + r.message!.contains('Invalid package root URI'), ); expect(response.success, false); expect( @@ -1109,7 +1074,7 @@ void main() { final disconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, + vmServiceUri: vmServiceUri, connected: false, dtd: testDtdConnection!, ); @@ -1130,22 +1095,11 @@ void main() { // Wait until the test app's main isolate is ready before invoking // the full HTTP handler. - await runWithRetry( - callback: () async { - final probe = - await server.VmServiceHandler.detectRootPackageForVmService( - vmServiceUriAsString: vmServiceUriString!, - vmServiceUri: vmServiceUri!, - connected: true, - dtd: testDtdConnection!, - ); - if (probe.message == null || - !probe.message!.contains('Invalid package root URI')) { - throw Exception('VM not ready: ${probe.message}'); - } - }, - maxRetries: 20, - retryDelay: const Duration(milliseconds: 500), + await detectRootWithRetry( + vmServiceUri!, + isReady: (r) => + r.message != null && + r.message!.contains('Invalid package root URI'), ); final wsVmServiceUri = convertToWebSocketUrl( diff --git a/packages/devtools_shared/test/utils/file_utils_test.dart b/packages/devtools_shared/test/utils/file_utils_test.dart index bc62753fa2e..ae3343326da 100644 --- a/packages/devtools_shared/test/utils/file_utils_test.dart +++ b/packages/devtools_shared/test/utils/file_utils_test.dart @@ -215,6 +215,8 @@ void main() { 'file:///Users/me/%2e%2e/other_app', 'file:///Users/me/%2e/my_app', 'file:///C:/Users/me%5c..%5cother_app', + 'file:///tmp/a%2f..%2fb', + 'file:///tmp/a%2Fb', ]) { expect( isValidLocalFileUriString(traversalString), @@ -226,6 +228,8 @@ void main() { for (final traversalUri in [ Uri.parse('file:///C:/Users/me%5c..%5cother_app'), Uri.parse('file:///C:/Users/me%5c.%5cmy_app'), + Uri.parse('file:///tmp/a%2f..%2fb'), + Uri.parse('file:///tmp/a%2Fb'), ]) { expect( isValidLocalFileUri(traversalUri), From daff89e2616f98897c6410d06f8840bf33f265d8 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Mon, 23 Nov 2026 10:08:58 -0800 Subject: [PATCH 5/7] Address PR #10096 review feedback for URI validation and tests. - Move `_invalidLocalFileUriMessage` to a library-private constant in `server_api.dart` and reuse it in `_devtools_extensions.dart` and `_vm_service.dart` so invalid local file URI error messages stay in sync. - Expose `VmServiceHandler.validateRootPackageUri` as `@visibleForTesting`, remove `isValidRootPackageUri`, and assert on specific rejection reason messages in `general_api_test.dart`. - Trim the invalid local file URI test in `general_api_test.dart` to a single query URI case since `file_utils_test.dart` already covers all invalid URI components. - Restore plain `Uri.parse` fixtures in `updateDtdWorkspaceRoots` tests and remove the unnecessary temporary directory setup and deleted-directory test. - Document `detectRootWithRetry`'s default `isReady` behavior and simplify its `isReady` callbacks to use null-aware `contains`. --- .../server/handlers/_devtools_extensions.dart | 5 +- .../lib/src/server/handlers/_vm_service.dart | 19 +- .../lib/src/server/server_api.dart | 5 + .../test/server/general_api_test.dart | 179 +++++------------- 4 files changed, 61 insertions(+), 147 deletions(-) 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 7ca3a2e0af9..487fda71ef3 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -27,9 +27,8 @@ extension _ExtensionsApiHandler on Never { rootFileUriString.isNotEmpty && !isValidLocalFileUriString(rootFileUriString)) { return api.badRequest( - 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be an ' - 'absolute file:// URI with no host, query, fragment, or `.`/`..` ' - 'segments.', + 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: ' + '$_invalidLocalFileUriMessage', ); } final result = {}; 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 cf6335e0e01..a7d70e651e2 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -20,11 +20,6 @@ extension VmServiceHandler on Never { /// and Windows (`USERPROFILE`). static const _homeEnvVarKeys = ['HOME', 'USERPROFILE']; - /// Error description for invalid local `file://` package root URIs. - static const _invalidLocalFileUriMessage = - 'must be an absolute file:// URI with no host, query, fragment, or ' - '`.`/`..` segments.'; - /// Stores the calculated package roots for VM service connections that are /// initiated in [handleNotifyForVmServiceConnection]. /// @@ -36,22 +31,14 @@ extension VmServiceHandler on Never { /// never be used. static final _packageRootsForVmServiceConnections = {}; - /// Returns whether [rootPackageUri] is a valid Dart or Flutter package root - /// directory that can safely be registered as a DTD IDE workspace root. - @visibleForTesting - static bool isValidRootPackageUri( - Uri rootPackageUri, { - Map? environment, - }) => - _validateRootPackageUri(rootPackageUri, environment: environment) == null; - /// 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. /// /// Returns `null` if [rootPackageUri] is valid, or an error message if it /// must be rejected. - static String? _validateRootPackageUri( + @visibleForTesting + static String? validateRootPackageUri( Uri rootPackageUri, { Map? environment, }) { @@ -285,7 +272,7 @@ extension VmServiceHandler on Never { ); } rootPackageUri = Uri.parse(root); - final validationError = _validateRootPackageUri(rootPackageUri); + final validationError = validateRootPackageUri(rootPackageUri); if (validationError != null) { return (success: false, message: validationError, uri: null); } diff --git a/packages/devtools_shared/lib/src/server/server_api.dart b/packages/devtools_shared/lib/src/server/server_api.dart index f284d7f281f..2ea78b622cd 100644 --- a/packages/devtools_shared/lib/src/server/server_api.dart +++ b/packages/devtools_shared/lib/src/server/server_api.dart @@ -38,6 +38,11 @@ part 'handlers/_storage.dart'; part 'handlers/_survey.dart'; part 'handlers/_vm_service.dart'; +/// Error description for invalid local `file://` URIs. +const _invalidLocalFileUriMessage = + 'must be an absolute file:// URI with no host, query, fragment, or ' + '`.`/`..` segments.'; + /// The DevTools server API. /// /// This defines endpoints that serve all requests that come in over api/. diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index 0fd107ab74e..075e0960cf3 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -638,7 +638,7 @@ void main() { ); }); - group('isValidRootPackageUri', () { + group('validateRootPackageUri', () { late Directory tempDir; setUp(() { @@ -656,10 +656,10 @@ void main() { ..createSync(recursive: true); File(p.join(pkgWithPubspec.path, 'pubspec.yaml')).createSync(); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(pkgWithPubspec.path), ), - isTrue, + isNull, ); final pkgWithConfig = Directory(p.join(tempDir.path, 'pkg_2')) @@ -668,10 +668,10 @@ void main() { p.join(pkgWithConfig.path, '.dart_tool', 'package_config.json'), ).createSync(recursive: true); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(pkgWithConfig.path), ), - isTrue, + isNull, ); }, ); @@ -679,63 +679,49 @@ void main() { test('rejects filesystem root and symlinks to filesystem root', () { final rootPrefix = p.rootPrefix(tempDir.path); expect( - server.VmServiceHandler.isValidRootPackageUri(Uri.file(rootPrefix)), - isFalse, + server.VmServiceHandler.validateRootPackageUri(Uri.file(rootPrefix)), + contains('filesystem root'), ); final symlinkToRoot = Link(p.join(tempDir.path, 'root_link')) ..createSync(rootPrefix); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(symlinkToRoot.path), ), - isFalse, + contains('filesystem root'), ); }); - test( - 'rejects non-file schemes, non-empty authorities, and invalid URI components', - () { - final validPkg = Directory(p.join(tempDir.path, 'valid_pkg')) - ..createSync(recursive: true); - File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); - final validPkgUri = Uri.file(validPkg.path); - - for (final invalidUri in [ - Uri.parse('http://localhost/path/to/pkg'), - Uri.parse('file://evil.host/path/to/pkg'), - Uri.parse('file://user@/path/to/pkg'), - Uri.parse('$validPkgUri?query=1'), - Uri.parse('$validPkgUri#fragment'), - Uri.parse('${Uri.directory(tempDir.path)}other%5c..%5cvalid_pkg'), - Uri.parse('${Uri.directory(tempDir.path)}other%2f..%2fvalid_pkg'), - ]) { - expect( - server.VmServiceHandler.isValidRootPackageUri(invalidUri), - isFalse, - reason: 'Expected $invalidUri to be rejected', - ); - } - }, - ); + 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'); + + expect( + server.VmServiceHandler.validateRootPackageUri(invalidUri), + contains('must be an absolute file:// URI'), + ); + }); test('rejects user home directory (HOME and USERPROFILE)', () { final homeDir = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; if (homeDir != null && homeDir.isNotEmpty) { expect( - server.VmServiceHandler.isValidRootPackageUri(Uri.file(homeDir)), - isFalse, + server.VmServiceHandler.validateRootPackageUri(Uri.file(homeDir)), + 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.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(symlinkToHome.path), ), - isFalse, + contains('home directory'), ); } @@ -745,24 +731,24 @@ void main() { ..createSync(recursive: true); File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(fakeHomePkg.path), ), - isTrue, + isNull, ); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(fakeHomePkg.path), environment: {'HOME': fakeHomePkg.path}, ), - isFalse, + contains('home directory'), ); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(fakeHomePkg.path), environment: {'USERPROFILE': fakeHomePkg.path}, ), - isFalse, + contains('home directory'), ); }); @@ -770,8 +756,8 @@ void main() { // Non-existent directory. final nonExistentUri = Uri.file(p.join(tempDir.path, 'does_not_exist')); expect( - server.VmServiceHandler.isValidRootPackageUri(nonExistentUri), - isFalse, + server.VmServiceHandler.validateRootPackageUri(nonExistentUri), + contains('directory does not exist'), ); // Existing directory without pubspec.yaml or @@ -782,10 +768,13 @@ void main() { p.join(nonPackageDir.path, '.dart_tool'), ).createSync(recursive: true); expect( - server.VmServiceHandler.isValidRootPackageUri( + server.VmServiceHandler.validateRootPackageUri( Uri.file(nonPackageDir.path), ), - isFalse, + contains( + 'directory does not contain pubspec.yaml or ' + '.dart_tool/package_config.json', + ), ); }); }); @@ -810,21 +799,11 @@ void main() { }); group('updateDtdWorkspaceRoots', () { - late Directory tempDir; - - setUp(() { - tempDir = Directory.systemTemp.createTempSync('dtd_roots_test_'); - }); - - tearDown(() async { - await deleteDirectoryWithRetry(tempDir); - }); - - Future updateWorkspaceRoots({ + Future updateWorkspaceRoots({ required Uri root, required bool connected, - }) { - return server.VmServiceHandler.updateDtdWorkspaceRoots( + }) async { + await server.VmServiceHandler.updateDtdWorkspaceRoots( testDtdConnection!, dtdConnectionInfo: dtd!.info!, rootFromVmService: root, @@ -842,82 +821,26 @@ void main() { test('adds and removes workspace roots', () async { await verifyWorkspaceRoots({}); - final pkgDir1 = Directory(p.join(tempDir.path, 'package_root_1')) - ..createSync(recursive: true); - File(p.join(pkgDir1.path, 'pubspec.yaml')).createSync(); - final pkgDir2 = Directory(p.join(tempDir.path, 'package_root_2')) - ..createSync(recursive: true); - File( - p.join(pkgDir2.path, '.dart_tool', 'package_config.json'), - ).createSync(recursive: true); + final rootUri1 = Uri.parse('file:///Users/me/package_root_1'); + final rootUri2 = Uri.parse('file:///Users/me/package_root_2'); - final rootUri1 = Uri.file(pkgDir1.path); - final rootUri2 = Uri.file(pkgDir2.path); - - final add1Response = await updateWorkspaceRoots( - root: rootUri1, - connected: true, - ); - expect(add1Response.statusCode, HttpStatus.ok); + await updateWorkspaceRoots(root: rootUri1, connected: true); await verifyWorkspaceRoots({rootUri1}); // Add a second root and verify the roots are unioned. - final add2Response = await updateWorkspaceRoots( - root: rootUri2, - connected: true, - ); - expect(add2Response.statusCode, HttpStatus.ok); + await updateWorkspaceRoots(root: rootUri2, connected: true); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify duplicates cannot be added. - final dupResponse = await updateWorkspaceRoots( - root: rootUri2, - connected: true, - ); - expect(dupResponse.statusCode, HttpStatus.ok); + await updateWorkspaceRoots(root: rootUri2, connected: true); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify roots are removed for disconnect events. - final remove2Response = await updateWorkspaceRoots( - root: rootUri2, - connected: false, - ); - expect(remove2Response.statusCode, HttpStatus.ok); + await updateWorkspaceRoots(root: rootUri2, connected: false); await verifyWorkspaceRoots({rootUri1}); - final remove1Response = await updateWorkspaceRoots( - root: rootUri1, - connected: false, - ); - expect(remove1Response.statusCode, HttpStatus.ok); + await updateWorkspaceRoots(root: rootUri1, connected: false); await verifyWorkspaceRoots({}); }, timeout: const Timeout.factor(4)); - - test( - 'removes workspace root on disconnect even if directory was deleted', - () async { - await verifyWorkspaceRoots({}); - final pkgDir = Directory(p.join(tempDir.path, 'deleted_pkg')) - ..createSync(recursive: true); - File(p.join(pkgDir.path, 'pubspec.yaml')).createSync(); - final rootUri = Uri.file(pkgDir.path); - - final addResponse = await updateWorkspaceRoots( - root: rootUri, - connected: true, - ); - expect(addResponse.statusCode, HttpStatus.ok); - await verifyWorkspaceRoots({rootUri}); - - pkgDir.deleteSync(recursive: true); - - final removeResponse = await updateWorkspaceRoots( - root: rootUri, - connected: false, - ); - expect(removeResponse.statusCode, HttpStatus.ok); - await verifyWorkspaceRoots({}); - }, - ); }); group('detectRootPackageForVmService', () { @@ -937,6 +860,8 @@ void main() { vmServiceUriString = null; }); + /// Retries [server.VmServiceHandler.detectRootPackageForVmService] + /// until [isReady] returns `true` (defaults to `response.success`). Future detectRootWithRetry( Uri vmServiceUri, { bool Function(server.DetectRootPackageResponse response)? isReady, @@ -1057,8 +982,7 @@ void main() { final response = await detectRootWithRetry( vmServiceUri!, isReady: (r) => - r.message != null && - r.message!.contains('Invalid package root URI'), + r.message?.contains('Invalid package root URI') ?? false, ); expect(response.success, false); expect( @@ -1098,8 +1022,7 @@ void main() { await detectRootWithRetry( vmServiceUri!, isReady: (r) => - r.message != null && - r.message!.contains('Invalid package root URI'), + r.message?.contains('Invalid package root URI') ?? false, ); final wsVmServiceUri = convertToWebSocketUrl( From df0612a8fc745b756639cb64def310b41bb8de70 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Mon, 23 Nov 2026 11:53:18 -0800 Subject: [PATCH 6/7] [agent] Address PR review feedback on URI validation and symlink handling --- packages/devtools_shared/CHANGELOG.md | 10 +- .../lib/src/extensions/extension_manager.dart | 6 +- .../lib/src/server/handlers/_vm_service.dart | 92 ++++++----- .../lib/src/server/server_api.dart | 5 - .../lib/src/utils/file_utils.dart | 46 ++---- .../test/server/general_api_test.dart | 151 +++++++++++------- .../test/utils/file_utils_test.dart | 30 +--- 7 files changed, 184 insertions(+), 156 deletions(-) diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index bcc07398955..50ec8d17345 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -41,12 +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, encoded slashes, - or `.`/`..` path traversal segments, and apply them in +* Add `isValidLocalFileUri`, `isValidLocalFileUriString`, and + `invalidLocalFileUriMessage` helpers to validate local `file://` URIs without + authorities, queries, fragments, or null bytes, and apply them in `api/extensionEnabledState`, `VmServiceHandler`, and `ExtensionsManager`. -* Validate detected package roots in `VmServiceHandler` before caching or updating DTD - IDE workspace roots. +* 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/src/extensions/extension_manager.dart b/packages/devtools_shared/lib/src/extensions/extension_manager.dart index 532e384ac08..85762fbdd48 100644 --- a/packages/devtools_shared/lib/src/extensions/extension_manager.dart +++ b/packages/devtools_shared/lib/src/extensions/extension_manager.dart @@ -155,8 +155,8 @@ class ExtensionsManager { 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; } @@ -365,7 +365,7 @@ class ExtensionsManager { 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/_vm_service.dart b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart index d73030bffb7..c0271eded9d 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -62,52 +62,66 @@ extension VmServiceHandler on Never { /// 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. + /// the user's home directory (or an ancestor of it). /// - /// Returns `null` if [rootPackageUri] is valid, or an error message if it - /// must be rejected. + /// Returns the symlink-resolved [Uri] if [rootPackageUri] is valid, or an + /// error message if it must be rejected. @visibleForTesting - static String? validateRootPackageUri( + static ({Uri? resolvedUri, String? error}) validateRootPackageUri( Uri rootPackageUri, { Map? environment, }) { if (!isValidLocalFileUri(rootPackageUri)) { - return 'Invalid package root URI ($rootPackageUri): ' - '$_invalidLocalFileUriMessage'; - } - - final String dirPath; - try { - dirPath = p.normalize(rootPackageUri.toFilePath()); - } catch (e) { - return 'Invalid package root URI ($rootPackageUri): $e'; + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): ' + '$invalidLocalFileUriMessage', + ); } + final dirPath = p.normalize(rootPackageUri.toFilePath()); final dir = Directory(dirPath); if (!dir.existsSync()) { - return 'Invalid package root URI ($rootPackageUri): directory does not ' - 'exist.'; + 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 'Invalid package root URI ($rootPackageUri): failed to resolve ' - 'symbolic links ($e).'; + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): failed to resolve ' + 'symbolic links ($e).', + ); } if (p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) { - return 'Invalid package root URI ($rootPackageUri): cannot be the ' - 'filesystem root.'; + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): cannot be the ' + 'filesystem root.', + ); } - if (_isUserHomeDirectory( + if (_isUserHomeOrAncestorDirectory( resolvedDirPath, environment: environment ?? Platform.environment, )) { - return 'Invalid package root URI ($rootPackageUri): cannot be the user ' - 'home directory.'; + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): cannot be the user ' + 'home directory or an ancestor of it.', + ); } final hasPubspec = File( @@ -117,17 +131,21 @@ extension VmServiceHandler on Never { p.join(resolvedDirPath, _dartToolDirName, _packageConfigJsonFileName), ).existsSync(); if (!hasPubspec && !hasPackageConfig) { - return 'Invalid package root URI ($rootPackageUri): directory does not ' - 'contain $_pubspecYamlFileName or ' - '$_dartToolDirName/$_packageConfigJsonFileName.'; + return ( + resolvedUri: null, + error: + 'Invalid package root URI ($rootPackageUri): directory does not ' + 'contain $_pubspecYamlFileName or ' + '$_dartToolDirName/$_packageConfigJsonFileName.', + ); } - return null; + return (resolvedUri: Uri.file(resolvedDirPath), error: null); } - /// Returns whether [resolvedDirPath] matches the current user's home - /// directory from `HOME` or `USERPROFILE`. - static bool _isUserHomeDirectory( + /// 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, }) { @@ -137,7 +155,8 @@ extension VmServiceHandler on Never { final normalizedHome = p.normalize(homePath); final resolvedHome = _tryResolveSymbolicLinks(Directory(normalizedHome)) ?? normalizedHome; - if (p.equals(resolvedDirPath, resolvedHome)) { + if (p.equals(resolvedDirPath, resolvedHome) || + p.isWithin(resolvedDirPath, resolvedHome)) { return true; } } @@ -297,20 +316,21 @@ extension VmServiceHandler on Never { uri: null, ); } - if (!isValidLocalFileUriString(root)) { + final parsedRoot = Uri.tryParse(root); + if (parsedRoot == null) { return ( success: false, message: 'Invalid package root URI ($root): ' - '$_invalidLocalFileUriMessage', + '$invalidLocalFileUriMessage', uri: null, ); } - rootPackageUri = Uri.parse(root); - final validationError = validateRootPackageUri(rootPackageUri); - if (validationError != null) { - return (success: false, message: validationError, uri: null); + final validationResult = validateRootPackageUri(parsedRoot); + if (validationResult.error != null) { + return (success: false, message: validationResult.error, uri: null); } + rootPackageUri = validationResult.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 2ea78b622cd..f284d7f281f 100644 --- a/packages/devtools_shared/lib/src/server/server_api.dart +++ b/packages/devtools_shared/lib/src/server/server_api.dart @@ -38,11 +38,6 @@ part 'handlers/_storage.dart'; part 'handlers/_survey.dart'; part 'handlers/_vm_service.dart'; -/// Error description for invalid local `file://` URIs. -const _invalidLocalFileUriMessage = - 'must be an absolute file:// URI with no host, query, fragment, or ' - '`.`/`..` segments.'; - /// The DevTools server API. /// /// This defines endpoints that serve all requests that come in over api/. diff --git a/packages/devtools_shared/lib/src/utils/file_utils.dart b/packages/devtools_shared/lib/src/utils/file_utils.dart index b26d6adc684..b22569cf3f6 100644 --- a/packages/devtools_shared/lib/src/utils/file_utils.dart +++ b/packages/devtools_shared/lib/src/utils/file_utils.dart @@ -101,13 +101,17 @@ 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 dot path traversal segments. +/// query, fragment, or null bytes, and can be converted to a local file path. /// /// Requiring an empty authority rejects remote hosts, ports, user info, and -/// Windows UNC paths (e.g. `file://server/share/...`). Requiring an absolute -/// path without query or fragment components ensures [Uri.toFilePath] will not -/// throw an [UnsupportedError]. +/// Windows UNC paths (e.g. `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 || @@ -116,38 +120,20 @@ bool isValidLocalFileUri(Uri uri) { uri.hasFragment) { return false; } - for (final segment in uri.pathSegments) { - if (segment.contains('/')) return false; - for (final part in segment.split(r'\')) { - if (part == '.' || part == '..') return false; - } + try { + final filePath = uri.toFilePath(); + return !filePath.contains('\x00'); + } catch (_) { + return false; } - return true; } -/// Returns whether [uriString] is a `file://` URI string without dot-segment -/// traversal (`.` or `..`) that parses as a valid local `file:` URI via -/// [isValidLocalFileUri]. +/// 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); - if (uri == null || !isValidLocalFileUri(uri)) { - return false; - } - // Check raw segments before `Uri.tryParse` normalizes `.` and `..` away. - final rawPath = uriString.substring(_fileUriPrefix.length); - for (final segment in rawPath.split('/')) { - if (segment == '.' || segment == '..') return false; - try { - final decoded = Uri.decodeComponent(segment); - for (final part in decoded.split(r'\')) { - if (part == '.' || part == '..') return false; - } - } on ArgumentError { - return false; - } - } - return true; + 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 e20f3fdb247..a5a05d47727 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -650,16 +650,29 @@ void main() { }); test( - 'accepts existing directories with pubspec.yaml or .dart_tool/package_config.json', + '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), ), - isNull, + (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')) @@ -667,30 +680,33 @@ void main() { 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), ), - isNull, + (resolvedUri: Uri.file(resolvedConfigPath), error: null), ); }, ); test('rejects filesystem root and symlinks to filesystem root', () { final rootPrefix = p.rootPrefix(tempDir.path); - expect( - server.VmServiceHandler.validateRootPackageUri(Uri.file(rootPrefix)), - contains('filesystem root'), + 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); - expect( - server.VmServiceHandler.validateRootPackageUri( - Uri.file(symlinkToRoot.path), - ), - contains('filesystem root'), + 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', () { @@ -699,64 +715,89 @@ void main() { File(p.join(validPkg.path, 'pubspec.yaml')).createSync(); final invalidUri = Uri.parse('${Uri.file(validPkg.path)}?query=1'); - expect( - server.VmServiceHandler.validateRootPackageUri(invalidUri), - contains('must be an absolute file:// URI'), + 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 (HOME and USERPROFILE)', () { - final homeDir = - Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; - if (homeDir != null && homeDir.isNotEmpty) { + test( + 'rejects user home directory and its ancestors (HOME and USERPROFILE)', + () { + final homeDir = + 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(homeDir)), + server.VmServiceHandler.validateRootPackageUri( + Uri.file(fakeHomePkg.path), + environment: {'HOME': fakeHomePkg.path}, + ).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), - ), + Uri.file(fakeHomePkg.path), + environment: {'USERPROFILE': fakeHomePkg.path}, + ).error, contains('home directory'), ); - } - - // Verify both HOME and USERPROFILE environment variables are checked - // even when the directory contains a pubspec.yaml file. - final fakeHomePkg = Directory(p.join(tempDir.path, 'fake_home')) - ..createSync(recursive: true); - File(p.join(fakeHomePkg.path, 'pubspec.yaml')).createSync(); - expect( - server.VmServiceHandler.validateRootPackageUri( - Uri.file(fakeHomePkg.path), - ), - isNull, - ); - expect( - server.VmServiceHandler.validateRootPackageUri( - Uri.file(fakeHomePkg.path), - environment: {'HOME': fakeHomePkg.path}, - ), - contains('home directory'), - ); - expect( - server.VmServiceHandler.validateRootPackageUri( - Uri.file(fakeHomePkg.path), - environment: {'USERPROFILE': fakeHomePkg.path}, - ), - 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), + server.VmServiceHandler.validateRootPackageUri(nonExistentUri).error, contains('directory does not exist'), ); @@ -770,7 +811,7 @@ void main() { expect( server.VmServiceHandler.validateRootPackageUri( Uri.file(nonPackageDir.path), - ), + ).error, contains( 'directory does not contain pubspec.yaml or ' '.dart_tool/package_config.json', diff --git a/packages/devtools_shared/test/utils/file_utils_test.dart b/packages/devtools_shared/test/utils/file_utils_test.dart index ae3343326da..85e61146d0d 100644 --- a/packages/devtools_shared/test/utils/file_utils_test.dart +++ b/packages/devtools_shared/test/utils/file_utils_test.dart @@ -208,33 +208,19 @@ void main() { } }); - test('rejects dot and dot-dot path traversal segments', () { - for (final traversalString in const [ - 'file:///Users/me/../other_app', - 'file:///Users/me/./my_app', - 'file:///Users/me/%2e%2e/other_app', - 'file:///Users/me/%2e/my_app', - 'file:///C:/Users/me%5c..%5cother_app', + 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( - isValidLocalFileUriString(traversalString), - isFalse, - reason: traversalString, - ); - } - - for (final traversalUri in [ - Uri.parse('file:///C:/Users/me%5c..%5cother_app'), - Uri.parse('file:///C:/Users/me%5c.%5cmy_app'), - Uri.parse('file:///tmp/a%2f..%2fb'), - Uri.parse('file:///tmp/a%2Fb'), - ]) { - expect( - isValidLocalFileUri(traversalUri), + isValidLocalFileUri(Uri.parse(invalid)), isFalse, - reason: '$traversalUri', + reason: invalid, ); } }); From b73fd27d266eebe3afd08fce291468b943db2cba Mon Sep 17 00:00:00 2001 From: ryjohn Date: Tue, 24 Nov 2026 17:33:23 +0000 Subject: [PATCH 7/7] Fix Windows path resolution assertions in general_api_test --- .../test/server/general_api_test.dart | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index a5a05d47727..0804088754f 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -725,9 +725,11 @@ void main() { test( 'rejects user home directory and its ancestors (HOME and USERPROFILE)', () { - final homeDir = - Platform.environment['HOME'] ?? - Platform.environment['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( @@ -886,10 +888,17 @@ 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(); @@ -941,7 +950,7 @@ void main() { 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( @@ -960,7 +969,7 @@ void main() { 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 { @@ -983,7 +992,7 @@ void main() { 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( @@ -997,7 +1006,7 @@ void main() { expect(disconnectResponse.uri, isNotNull); expect( disconnectResponse.uri!.toFilePath(), - endsWith(app!.directory.path), + resolvedAppDirectoryPath, ); // Verify the cache entry was removed on disconnect. @@ -1034,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