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` and `isValidLocalFileUriString` helpers to validate
local `file://` URIs without authorities, queries, fragments, or null bytes,
and apply them in `api/extensionEnabledState`, `VmServiceHandler`, and
`ExtensionsManager`.
* Validate and resolve symlinks for detected package roots in `VmServiceHandler`
before caching or updating DTD IDE workspace roots.

# 14.0.0

Expand Down
2 changes: 1 addition & 1 deletion packages/devtools_shared/lib/devtools_shared.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export 'src/memory/memory_json.dart';
export 'src/service_utils.dart';
export 'src/sse/sse_shim.dart';
export 'src/utils/compare.dart';
export 'src/utils/file_utils.dart';
export 'src/utils/file_utils.dart' hide invalidLocalFileUriMessage;
export 'src/utils/retry.dart';
export 'src/utils/semantic_version.dart';
export 'src/utils/serialization.dart';
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
166 changes: 165 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,143 @@ extension VmServiceHandler on Never {
_packageRootsForVmServiceConnections.clear();
}

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

final resolvedUri = Uri.file(resolvedDirPath);
if (!isValidLocalFileUri(resolvedUri)) {
return (
resolvedUri: null,
error:
'Invalid package root URI ($rootPackageUri): '
'$invalidLocalFileUriMessage',
);
}

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

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

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

return (resolvedUri: resolvedUri, error: null);
}

/// Returns whether [resolvedDirPath] matches or is an ancestor of the
/// current user's home directory from `HOME` or `USERPROFILE`.
static bool _isUserHomeOrAncestorDirectory(
String resolvedDirPath, {
required Map<String, String> environment,
}) {
for (final envKey in _homeEnvVarKeys) {
final homePath = environment[envKey];
if (homePath == null || homePath.isEmpty) continue;
final normalizedHome = p.normalize(homePath);
String resolvedHome;
try {
resolvedHome = p.normalize(
Directory(normalizedHome).resolveSymbolicLinksSync(),
);
} on FileSystemException {
resolvedHome = normalizedHome;
}
if (p.equals(resolvedDirPath, resolvedHome) ||
p.isWithin(resolvedDirPath, resolvedHome)) {
return true;
}
}
return false;
}

/// Handles an [apiNotifyForVmServiceConnection] request notifying the
/// DevTools server that a DevTools client connected to or disconnected from a
/// VM service.
///
/// Expects [queryParams] to contain [apiParameterValueKey] (the VM service
/// URI) and [apiParameterVmServiceConnected] (`'true'` or `'false'`).
///
/// When the DevTools server owns the Dart Tooling Daemon (DevTools was
/// launched outside of the IDE, and [dtd] has both a [DtdInfo.localUri] and a
/// [DtdInfo.secret]), this registers or unregisters the VM service with DTD,
/// resolves and validates the app's package root via
/// [detectRootPackageForVmService], and updates DTD's IDE workspace roots via
/// [updateDtdWorkspaceRoots].
///
/// Returns a [ServerApi.success] no-op response via [api] if [dtd] is
/// unavailable or has no secret, [ServerApi.badRequest] if required
/// parameters are missing or invalid, or [ServerApi.serverError] if package
/// root detection or DTD communication fails.
static Future<shelf.Response> handleNotifyForVmServiceConnection(
ServerApi api,
Map<String, String> queryParams,
Expand Down Expand Up @@ -171,7 +321,21 @@ extension VmServiceHandler on Never {
uri: null,
);
}
rootPackageUri = Uri.parse(root);
final parsedRoot = Uri.tryParse(root);
if (parsedRoot == null) {
return (
success: false,
message:
'Invalid package root URI ($root): '
'$invalidLocalFileUriMessage',
uri: null,
);
}
final (:resolvedUri, :error) = validateRootPackageUri(parsedRoot);
if (resolvedUri == null) {
return (success: false, message: error, uri: null);
}
rootPackageUri = resolvedUri;
if (cacheResult) {
_packageRootsForVmServiceConnections[normalizedUriAsString] =
rootPackageUri;
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
39 changes: 39 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,42 @@ String _assertUriFormatAndReturn(String uriString) {
);
return uriString;
}

/// Error description for invalid local `file://` URIs.
const invalidLocalFileUriMessage =
Comment thread
johnpryan marked this conversation as resolved.
Resolved
'must be an absolute file:// URI with no host, query, or fragment.';

/// Returns whether [uri] is a valid local `file:` URI without an authority,
/// query, fragment, or null bytes, and can be converted to a local file path.
///
/// Requiring an empty authority and disallowing a leading `//` in the path
/// rejects remote hosts, ports, user info, and Windows UNC paths (e.g.
/// `file://server/share/...` or `file:////server/share/...`). Checking
/// [Uri.toFilePath] ensures callers can convert [uri] without triggering an
/// [UnsupportedError] or [FormatException].
bool isValidLocalFileUri(Uri uri) {
if (uri.scheme != 'file' ||
uri.authority.isNotEmpty ||
!uri.hasAbsolutePath ||
Comment thread
johnpryan marked this conversation as resolved.
Resolved
uri.path.startsWith('//') ||
uri.hasQuery ||
uri.hasFragment) {
return false;
}
try {
final filePath = uri.toFilePath();
return !filePath.contains('\x00');
} catch (_) {
return false;
}
}

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