Skip to content

Commit 0c2832a

Browse files
Replace packageRootUri with vmServiceUri (#10097)
* Replace `packageRootUri` with `vmServiceUri` This replaces the `packageRootUri` query parameter with `VmServiceUri` in `api/serveAvailableExtensions`. Before this change, the DevTools app requested the user's package root file path from the VM service, and passed it along to `api/serveAvailableExtensions` using the `packageRootUri` query parameter. This meant that an untrusted caller could pass any directory on the host fileystem to probe directories or serve extensions outside of the active project directory. This deprecates the `packageRootUri` query parameter and replaces it with `vmServiceUri`, which allows the DevTools server to validate `vmServiceUri` and resolve the package root in `VmServiceHandler.detectRootPackageForVmService`. * Update CHANGELOG * Apply batched suggestions from code review Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * Apply suggestion from code review * Fix analyzer warning * Refactor ExtensionService to use named constructors for each situation 1. ExtensionService() – tracks the current app via the global service connection 2. ExtensionService.forVmService()– tracks extensions outside the current VSCode workspace. 3. ExtensionService.forWorkspace - tracks extensions for projects in the user's current VSCode workspace. * Remove unneeded check for mainIsolate.value != null _refresh() no longer queries the main isolate on the client—it just passes serviceConnection.serviceManager.serviceUri to the server. So the mainIsolate.value != null guard was just a leftover from when the client had to inspect mainIsolate to compute _appRoot. * use isNullOrEmpty extension method * Make `_detectExtensions` take two optional parameters * Revert changes to pubspec.lock * Address agent feedback - Record VM service root-detection failures as warnings in `handleServeAvailableExtensions` and still serve static DTD extensions, returning HTTP 500 only when no static extensions are found. - Key `_packageRootsForVmServiceConnections` solely by normalized `vmServiceUri.toString()`, normalize arguments in `setPackageRootForVmServiceForTesting`, and remove cached entries on disconnect. - Extract `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` into `devtools_shared` (`service_utils.dart`) and remove the duplicated logic from `_vm_service.dart`. - Deprecate `ServiceManager.connectedAppPackageRoot` in `devtools_app_shared`, delegate it to `VmService.rootPackageDirectoryForMainIsolate`, add a `TODO(johnpryan)` to remove it in the next breaking release, and clean up unused private helpers and imports. - Await `ws.ready` in `_connectWithWebSocket` to prevent unhandled `WebSocketChannelException` errors when a VM service connection fails. - Add tests for uncached unreachable loopback `vmServiceUri` handling (with and without static extensions) and for cache eviction on VM service disconnect. - Update `CHANGELOG.md` in `devtools_shared` and `devtools_app_shared`. * Simplify ExtensionService constructors * Remove unused path dependency * Update comments * [agent] Address PR review feedback on VM service package root caching and truncated string evaluation. * Evict `_packageRootsForVmServiceConnections` on disconnect in `handleNotifyForVmServiceConnection` before returning early when DTD or its secret is unavailable. * Add a `cacheResult` parameter to `detectRootPackageForVmService` and pass `cacheResult: false` from `handleServeAvailableExtensions` so callers that never send disconnect notifications do not leave stale cache entries, and update the cache doc comment accordingly. * Fetch the full string via `getObject` in `_lookupTestTargetPackageRoot` when `VmService.evaluate` returns a truncated `packageConfigLocation` `InstanceRef`. * Add unit tests covering disconnect cache eviction without DTD, non-caching root detection, and truncated `packageConfigLocation` evaluation results. * Address PR review comments on VM service package root detection This updates ServiceManager.connectedAppPackageRoot, VmServicePackageRootExtension, and VmServiceHandler to preserve prior isolate-handling behavior and remove unreachable cache eviction logic. - Await isolateManager.waitForMainIsolateState() in ServiceManager.connectedAppPackageRoot before querying the VM service so early calls on connect wait for the main isolate. - Remove the unreachable disconnect cache-eviction path when DTD is unavailable in VmServiceHandler.handleNotifyForVmServiceConnection, along with its doc note and unit test. - Return null from VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate when test-target package root lookup fails instead of falling back to a .dart file URI. - Catch SentinelException per isolate in _detectMainIsolate and handle null isolate name values safely, with unit tests covering these cases. * Add comment for `ws.ready` --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 7af53a8 commit 0c2832a

20 files changed

Lines changed: 676 additions & 279 deletions

‎packages/devtools_app/lib/src/extensions/extension_service.dart‎

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -34,22 +34,21 @@ typedef DevToolsExtensionsGroup = ({
3434

3535
class ExtensionService extends DisposableController
3636
with AutoDisposeControllerMixin {
37-
ExtensionService({this.fixedAppRoot, this.ignoreServiceConnection = false});
38-
39-
/// The fixed (unchanging) root file:// URI for the application this
40-
/// [ExtensionService] will manage DevTools extensions for.
37+
/// Detects runtime and static DevTools extensions.
4138
///
42-
/// When null, [_appRoot] will be calculated from the
43-
/// `serviceConnection.serviceManager`'s currently connected app.
44-
final Uri? fixedAppRoot;
39+
/// When [fixedVmServiceUri] is provided, runtime extensions are detected for
40+
/// that VM service instead of listening to `serviceConnection.serviceManager`.
41+
ExtensionService({String? fixedVmServiceUri})
42+
: _fixedVmServiceUri = fixedVmServiceUri,
43+
_useGlobalServiceConnection = fixedVmServiceUri == null;
4544

46-
/// Whether to ignore the VM service connection for the context of this
47-
/// service.
48-
final bool ignoreServiceConnection;
45+
/// Detects static DevTools extensions for the IDE workspace only.
46+
ExtensionService.forWorkspace()
47+
: _fixedVmServiceUri = null,
48+
_useGlobalServiceConnection = false;
4949

50-
/// The root file:// URI for the Dart / Flutter application this
51-
/// [ExtensionService] will manage DevTools extensions for.
52-
Uri? _appRoot;
50+
final String? _fixedVmServiceUri;
51+
final bool _useGlobalServiceConnection;
5352

5453
/// A listenable for the current set of DevTools extensions.
5554
///
@@ -132,10 +131,7 @@ class ExtensionService extends DisposableController
132131
await _refresh();
133132
cancelListeners();
134133

135-
// We only need to add VM service manager related listeners when we are
136-
// interacting with the currently connected app (i.e. when
137-
// [fixedAppRootUri] is null).
138-
if (fixedAppRoot == null && !ignoreServiceConnection) {
134+
if (_useGlobalServiceConnection) {
139135
addAutoDisposeListener(
140136
serviceConnection.serviceManager.connectedState,
141137
() async {
@@ -171,24 +167,22 @@ class ExtensionService extends DisposableController
171167
_log.fine('refreshing the ExtensionService');
172168
_reset();
173169

174-
_appRoot = null;
175-
if (fixedAppRoot != null) {
176-
_appRoot = fixedAppRoot;
177-
} else if (!ignoreServiceConnection &&
178-
serviceConnection.serviceManager.connectedState.value.connected &&
179-
serviceConnection.serviceManager.isolateManager.mainIsolate.value !=
180-
null) {
181-
_appRoot = await serviceConnection.serviceManager.connectedAppPackageRoot(
182-
dtdManager,
183-
);
170+
String? vmServiceUri;
171+
if (_fixedVmServiceUri != null) {
172+
vmServiceUri = _fixedVmServiceUri;
173+
} else if (_useGlobalServiceConnection &&
174+
serviceConnection.serviceManager.connectedState.value.connected) {
175+
vmServiceUri = serviceConnection.serviceManager.serviceUri;
184176
}
185177

186178
// TODO(kenz): gracefully handle app connections / disconnects when there
187179
// are already static extensions in use. The current code resets everything
188180
// when connection states change or hot restarts occur.
189181

190182
_refreshInProgress.value = true;
191-
final allExtensions = await server.refreshAvailableExtensions(_appRoot);
183+
final allExtensions = await server.refreshAvailableExtensions(
184+
vmServiceUri: vmServiceUri,
185+
);
192186
runtimeExtensions = allExtensions
193187
.where((e) => !e.detectedFromStaticContext)
194188
.toList();
@@ -336,7 +330,6 @@ class ExtensionService extends DisposableController
336330

337331
void _reset() {
338332
_log.fine('resetting the ExtensionService');
339-
_appRoot = null;
340333
runtimeExtensions.clear();
341334
staticExtensions.clear();
342335
_ignoredStaticExtensionsByHashCode.clear();

‎packages/devtools_app/lib/src/shared/server/_extensions_api.dart‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,19 @@ part of 'server.dart';
77
/// Makes a request to the server to refresh the list of available extensions,
88
/// serve their assets on the server, and return the list of available
99
/// extensions here.
10-
Future<List<DevToolsExtensionConfig>> refreshAvailableExtensions(
11-
// TODO(https://github.com/flutter/devtools/issues/7944): pass the URI to the
12-
// package config file instead of passing the app root and rebulding the URI
13-
// to the package config file.
14-
Uri? appRoot,
15-
) async {
16-
_log.fine('refreshAvailableExtensions for app root: ${appRoot.toString()}');
10+
Future<List<DevToolsExtensionConfig>> refreshAvailableExtensions({
11+
String? vmServiceUri,
12+
}) async {
13+
_log.fine('refreshAvailableExtensions for vmServiceUri: $vmServiceUri');
1714
if (debugDevToolsExtensions) {
1815
return debugHandleRefreshAvailableExtensions(
19-
includeRuntime: appRoot != null,
16+
includeRuntime: !vmServiceUri.isNullOrEmpty,
2017
);
2118
}
2219
if (isDevToolsServerAvailable) {
2320
final uri = Uri(
2421
path: ExtensionsApi.apiServeAvailableExtensions,
25-
queryParameters: {
26-
ExtensionsApi.packageRootUriPropertyName: appRoot?.toString(),
27-
},
22+
queryParameters: {ExtensionsApi.vmServiceUriPropertyName: vmServiceUri},
2823
);
2924
final resp = await request(uri.toString());
3025
if (resp?.statusOk ?? false) {

‎packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -133,17 +133,22 @@ class SidebarDevToolsExtensionsController extends DisposableController
133133
);
134134
}
135135

136-
// Pass a null project root URI to initialize the set of extensions
137-
// available for the entire workspace.
138-
await _detectExtensions(null);
136+
// Initialize extensions available for the entire workspace.
137+
await _detectExtensions();
139138
}
140139

141140
Future<void> _initExtensionsForDebugSessions() async {
142141
for (final debugSession in _debugSessions.values) {
143142
final fileUri = debugSession.projectRootFileUri;
144-
if (fileUri != null && !_searchedProjectRoots.contains(fileUri)) {
143+
final vmServiceUri = debugSession.vmServiceUri;
144+
if (fileUri != null &&
145+
vmServiceUri != null &&
146+
!_searchedProjectRoots.contains(fileUri)) {
145147
_searchedProjectRoots.add(fileUri);
146-
await _detectExtensions(fileUri);
148+
await _detectExtensions(
149+
projectRootUri: fileUri,
150+
vmServiceUri: vmServiceUri,
151+
);
147152
}
148153
}
149154
}
@@ -162,16 +167,19 @@ class SidebarDevToolsExtensionsController extends DisposableController
162167
// the workspace or for a debug session changes. We will likely need some
163168
// watch event from the IDE or analysis server to signal when any
164169
// package_config.json file in the workspace changes.
165-
Future<void> _detectExtensions(Uri? projectRootUri) async {
166-
final extensionService = projectRootUri == null
167-
?
168-
// A null [projectRootUri] indicates that this is an extensions lookup
169-
// for the entire workspace, not a debug session with a fixed root URI.
170-
ExtensionService(ignoreServiceConnection: true)
171-
: ExtensionService(
172-
fixedAppRoot: projectRootUri,
173-
ignoreServiceConnection: true,
174-
);
170+
Future<void> _detectExtensions({
171+
Uri? projectRootUri,
172+
String? vmServiceUri,
173+
}) async {
174+
assert(
175+
(projectRootUri == null) == (vmServiceUri == null),
176+
'projectRootUri ($projectRootUri) and vmServiceUri ($vmServiceUri) '
177+
'must either both be null (workspace lookup) or both be non-null '
178+
'(debug session lookup).',
179+
);
180+
final extensionService = vmServiceUri == null
181+
? ExtensionService.forWorkspace()
182+
: ExtensionService(fixedVmServiceUri: vmServiceUri);
175183
assert(
176184
!_extensionServiceByRootUri.containsKey(projectRootUri),
177185
'The initialization for the ExtensionService for root uri '

‎packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ TODO: Remove this section if there are not any updates.
114114
* Validated DevTools extension version strings and prevented extension
115115
identifier collisions when serving extension assets.
116116
[#10090](https://github.com/flutter/devtools/pull/10090)
117+
* Resolved the connected application's package root on the DevTools server via
118+
the VM service URI when serving DevTools extensions instead of accepting a
119+
package root file URI from the client.
120+
[#10097](https://github.com/flutter/devtools/pull/10097)
117121

118122
## Advanced developer mode updates
119123

‎packages/devtools_app/test/extensions/extension_screen_test.dart‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ void main() {
3636

3737
setGlobal(
3838
ExtensionService,
39-
ExtensionService(
40-
fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'),
41-
),
39+
ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'),
4240
);
4341
await extensionService.initialize();
4442
expect(extensionService.staticExtensions.length, 4);

‎packages/devtools_app/test/extensions/extension_service_test.dart‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ void main() {
3434
resetDevToolsExtensionEnabledStates();
3535
});
3636

37-
test('initialize when connected', () async {
37+
test('initialize with fixedVmServiceUri', () async {
3838
final service = ExtensionService(
39-
fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'),
39+
fixedVmServiceUri: 'ws://127.0.0.1:8181/ws',
4040
);
4141
expect(service.availableExtensions, isEmpty);
4242
expect(service.staticExtensions, isEmpty);
@@ -61,12 +61,12 @@ void main() {
6161
expect(ignoredRuntimeExtensions.length, 0);
6262
});
6363

64-
test('initialize with ignoreServiceConnection', () async {
64+
test('initialize with forWorkspace', () async {
6565
when(
6666
mockServiceManager.connectedState,
6767
).thenReturn(ValueNotifier(const ConnectedState(false)));
6868

69-
final service = ExtensionService(ignoreServiceConnection: true);
69+
final service = ExtensionService.forWorkspace();
7070
expect(service.staticExtensions, isEmpty);
7171
expect(service.runtimeExtensions, isEmpty);
7272
expect(service.availableExtensions, isEmpty);
@@ -87,7 +87,7 @@ void main() {
8787

8888
test('setExtensionEnabledState', () async {
8989
final service = ExtensionService(
90-
fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'),
90+
fixedVmServiceUri: 'ws://127.0.0.1:8181/ws',
9191
);
9292
await service.initialize();
9393
expect(service.staticExtensions.length, 4);

‎packages/devtools_app/test/extensions/extension_settings_test.dart‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ void main() {
3636

3737
setGlobal(
3838
ExtensionService,
39-
ExtensionService(
40-
fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'),
41-
),
39+
ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'),
4240
);
4341
await extensionService.initialize();
4442
expect(extensionService.staticExtensions.length, 4);

‎packages/devtools_app_shared/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens
1919
such as the `file:` URI of a Dart CLI app started with `dart run`. Previously it
2020
was the scheme of the URI, such as `file:`, which is not a package.
2121
* Updates `devtools_shared` constraint to `^14.0.1`.
22+
* Deprecate `ServiceManager.connectedAppPackageRoot` in favor of
23+
`VmService.rootPackageDirectoryForMainIsolate` from `devtools_shared`.
2224

2325
## 0.5.1
2426
* Add DevTools-styled text field `DevToolsTextField`.

0 commit comments

Comments
 (0)