Skip to content
3 changes: 3 additions & 0 deletions packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions packages/devtools_shared/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens
`api/serveAvailableExtensions`.
* Add `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` to
`devtools_shared.dart`.
* Add `isValidLocalFileUri`, `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 and resolve symlinks for detected package roots in `VmServiceHandler`
before caching or updating DTD IDE workspace roots.

# 14.0.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -151,12 +152,11 @@ class ExtensionsManager {
for (final extension in extensions) {
final config = extension.config;

if (extension.rootUri.scheme != 'file' ||
extension.rootUri.host.isNotEmpty) {
if (!isValidLocalFileUri(extension.rootUri)) {
parsingErrors.writeln(
'Ignoring extension from package "${extension.package}": invalid '
'package root URI "${extension.rootUri}" must be a file:// URI '
'with an empty host.',
'package root URI "${extension.rootUri}" '
'$invalidLocalFileUriMessage',
);
continue;
}
Expand Down Expand Up @@ -361,15 +361,11 @@ class ExtensionsManager {

void _assertUriFormat(String? uriString) {
if (uriString == null) return;
final uri = Uri.tryParse(uriString);
if (!uriString.startsWith('file://') ||
uri == null ||
uri.scheme != 'file' ||
uri.host.isNotEmpty) {
if (!isValidLocalFileUriString(uriString)) {
throw ArgumentError.value(
uriString,
'uriString',
'must be a file:// URI String with an empty host',
invalidLocalFileUriMessage,
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,7 @@ extension _ExtensionsApiHandler on Never {
// separators, so the check holds for Windows file URIs as well. Requiring
// an empty host rejects UNC paths (e.g. `file://server/share/...`) and
// keeps `toFilePath()` from throwing on a non-local authority.
final isFileUri =
devtoolsOptionsFileUri.scheme == 'file' &&
devtoolsOptionsFileUri.host.isEmpty;
final isFileUri = isValidLocalFileUri(devtoolsOptionsFileUri);
final fileName = isFileUri
? p.basename(devtoolsOptionsFileUri.toFilePath())
: '';
Expand All @@ -164,7 +162,7 @@ extension _ExtensionsApiHandler on Never {
extensionsManager.devtoolsExtensions.any((ext) {
final uri = Uri.tryParse(ext.devtoolsOptionsUri);
if (uri == null) return false;
if (uri.scheme == 'file' && uri.host.isEmpty) {
if (isValidLocalFileUri(uri)) {
// If these are equal, there's no need to call
// _resolveOptionsFilePath again, so return early.
final servedPathUnresolved = p.normalize(uri.toFilePath());
Expand Down Expand Up @@ -215,7 +213,7 @@ extension _ExtensionsApiHandler on Never {
/// [uri] is not a local `file:` URI, its parent directory does not exist, or
/// the `devtools_options.yaml` file itself is a symbolic link.
static String? _resolveOptionsFilePath(Uri uri) {
if (uri.scheme != 'file' || uri.host.isNotEmpty) return null;
if (!isValidLocalFileUri(uri)) return null;

final filePath = p.normalize(uri.toFilePath());
if (p.basename(filePath) != devtoolsOptionsFileName) return null;
Expand Down
161 changes: 160 additions & 1 deletion packages/devtools_shared/lib/src/server/handlers/_vm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ part of '../server_api.dart';
/// A namespace for VM service related server request handlers.
@visibleForTesting
extension VmServiceHandler on Never {
/// File name of a Dart or Flutter package manifest.
static const _pubspecYamlFileName = 'pubspec.yaml';

/// Name of the Dart tooling metadata directory in a package root.
static const _dartToolDirName = '.dart_tool';

/// File name of the package configuration file inside [_dartToolDirName].
static const _packageConfigJsonFileName = 'package_config.json';

/// Environment variables holding the user's home directory on POSIX (`HOME`)
/// and Windows (`USERPROFILE`).
static const _homeEnvVarKeys = ['HOME', 'USERPROFILE'];
Comment thread
johnpryan marked this conversation as resolved.
Resolved

/// Stores the calculated package roots for VM service connections that are
/// initiated in [handleNotifyForVmServiceConnection].
///
Expand Down Expand Up @@ -47,6 +60,138 @@ extension VmServiceHandler on Never {
_packageRootsForVmServiceConnections.clear();
}

/// Validates that [rootPackageUri] is a local `file://` URI pointing to an
/// existing Dart or Flutter package directory, and not the filesystem root or
/// the user's home directory (or an ancestor of it).
///
/// Returns the symlink-resolved [Uri] if [rootPackageUri] is valid, or an
/// error message if it must be rejected.
@visibleForTesting
static ({Uri? resolvedUri, String? error}) validateRootPackageUri(
Uri rootPackageUri, {
Map<String, String>? environment,
}) {
if (!isValidLocalFileUri(rootPackageUri)) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): '
'$invalidLocalFileUriMessage',
);
}

final dirPath = p.normalize(rootPackageUri.toFilePath());
final dir = Directory(dirPath);
if (!dir.existsSync()) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): directory does not '
'exist.',
);
}

final String resolvedDirPath;
try {
resolvedDirPath = p.normalize(dir.resolveSymbolicLinksSync());
} on FileSystemException catch (e) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): failed to resolve '
'symbolic links ($e).',
);
}

if (p.equals(resolvedDirPath, p.rootPrefix(resolvedDirPath))) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): cannot be the '
'filesystem root.',
);
}

if (_isUserHomeOrAncestorDirectory(
resolvedDirPath,
environment: environment ?? Platform.environment,
)) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): cannot be the user '
'home directory or an ancestor of it.',
);
}

final hasPubspec = File(
p.join(resolvedDirPath, _pubspecYamlFileName),
).existsSync();
final hasPackageConfig = File(
p.join(resolvedDirPath, _dartToolDirName, _packageConfigJsonFileName),
).existsSync();
if (!hasPubspec && !hasPackageConfig) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): directory does not '
'contain $_pubspecYamlFileName or '
'$_dartToolDirName/$_packageConfigJsonFileName.',
);
}

return (resolvedUri: Uri.file(resolvedDirPath), error: null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Windows, resolveSymbolicLinksSync() can resolve a symlink to a UNC share (or a mapped network drive) into \\server\share\..., so Uri.file(resolvedDirPath) ends up as file://server/share/.... That violates isValidLocalFileUri and will cause ExtensionsManager._assertUriFormat to throw an ArgumentError later. Can we construct resolvedUri = Uri.file(resolvedDirPath) right after resolving symlinks and check isValidLocalFileUri(resolvedUri) before proceeding?

}

/// 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<String, String> environment,
}) {
for (final envKey in _homeEnvVarKeys) {
final homePath = environment[envKey];
if (homePath == null || homePath.isEmpty) continue;
final normalizedHome = p.normalize(homePath);
final resolvedHome =
_tryResolveSymbolicLinks(Directory(normalizedHome)) ?? normalizedHome;
if (p.equals(resolvedDirPath, resolvedHome) ||
p.isWithin(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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: resolveSymbolicLinksSync() already throws FileSystemException when the directory doesn't exist, so existsSync() here is redundant. Since this only has one caller, I'd probably inline the try/on FileSystemException in _isUserHomeOrAncestorDirectory.

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<shelf.Response> handleNotifyForVmServiceConnection(
ServerApi api,
Map<String, String> queryParams,
Expand Down Expand Up @@ -171,7 +316,21 @@ extension VmServiceHandler on Never {
uri: null,
);
}
rootPackageUri = Uri.parse(root);
final parsedRoot = Uri.tryParse(root);
if (parsedRoot == null) {
return (
success: false,
message:
'Invalid package root URI ($root): '
'$invalidLocalFileUriMessage',
uri: null,
);
}
final validationResult = validateRootPackageUri(parsedRoot);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: we can destructure the record and check resolvedUri == null to avoid the !:

final (:resolvedUri, :error) = validateRootPackageUri(parsedRoot);
if (resolvedUri == null) {
  return (success: false, message: error, uri: null);
}
rootPackageUri = resolvedUri;

if (validationResult.error != null) {
return (success: false, message: validationResult.error, uri: null);
}
rootPackageUri = validationResult.resolvedUri!;
if (cacheResult) {
_packageRootsForVmServiceConnections[normalizedUriAsString] =
rootPackageUri;
Expand Down
1 change: 1 addition & 0 deletions packages/devtools_shared/lib/src/server/server_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import '../extensions/extension_enablement.dart';
import '../extensions/extension_manager.dart';
import '../service/service.dart';
import '../service_utils.dart';
import '../utils/file_utils.dart';
import 'devtools_store.dart';
import 'file_system.dart';
import 'flutter_store.dart';
Expand Down
37 changes: 37 additions & 0 deletions packages/devtools_shared/lib/src/utils/file_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,40 @@ String _assertUriFormatAndReturn(String uriString) {
);
return uriString;
}

/// Error description for invalid local `file://` URIs.
const invalidLocalFileUriMessage =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: do we want invalidLocalFileUriMessage (a lowercase error-message fragment) exported as public API from devtools_shared.dart? Since all callers live inside devtools_shared, I'd lean toward hide-ing it in devtools_shared.dart (and dropping it from the CHANGELOG.md entry).

'must be an absolute file:// URI with no host, query, or fragment.';

/// Returns whether [uri] is a valid local `file:` URI without an authority,
/// query, fragment, or null bytes, and can be converted to a local file path.
///
/// Requiring an empty authority rejects remote hosts, ports, user info, and
/// 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 ||
!uri.hasAbsolutePath ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still lets Windows UNC paths slip through via four leading slashes (e.g. file:////server/share/my_app). That parses with an empty authority and path == '//server/share/my_app', which uri.toFilePath() turns into \\server\share\my_app on Windows, reaching Directory.existsSync() (and even registering file://server/share/my_app with DTD if pubspec.yaml exists on the share).

Can we also reject uri.path.startsWith('//') here and add a test case for file:////server/share/my_app in file_utils_test.dart?

uri.hasQuery ||
uri.hasFragment) {
return false;
}
try {
final filePath = uri.toFilePath();
return !filePath.contains('\x00');
} catch (_) {
return false;
}
}

/// Returns whether [uriString] is a `file://` URI string that parses as a valid
/// local `file:` URI via [isValidLocalFileUri].
bool isValidLocalFileUriString(String? uriString) {
if (uriString == null || !uriString.startsWith(_fileUriPrefix)) {
return false;
}
final uri = Uri.tryParse(uriString);
return uri != null && isValidLocalFileUri(uri);
}
Loading
Loading