File: extension_action_runner.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (554 lines) | stat: -rw-r--r-- 20,397 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_action_runner.h"

#include <algorithm>
#include <memory>
#include <tuple>
#include <vector>

#include "base/auto_reset.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/extensions/extension_action_dispatcher.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/permissions/permissions_updater.h"
#include "chrome/browser/extensions/permissions/scripting_permissions_modifier.h"
#include "chrome/browser/extensions/permissions/site_permissions_helper.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
#include "components/crx_file/id_util.h"
#include "components/sessions/content/session_tab_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/api/declarative_net_request/action_tracker.h"
#include "extensions/browser/api/declarative_net_request/rules_monitor_service.h"
#include "extensions/browser/extension_action.h"
#include "extensions/browser/extension_action_manager.h"
#include "extensions/browser/permissions_manager.h"
#include "extensions/common/api/extension_action/action_info.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
#include "url/origin.h"

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/api/side_panel/side_panel_service.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/extensions_dialogs.h"
#endif

namespace {

std::vector<extensions::ExtensionId> GetExtensionIds(
    std::vector<const extensions::Extension*> extensions) {
  std::vector<extensions::ExtensionId> extension_ids;
  extension_ids.reserve(extensions.size());
  for (auto* extension : extensions) {
    extension_ids.push_back(extension->id());
  }
  return extension_ids;
}

}  // namespace

namespace extensions {

ExtensionActionRunner::PendingScript::PendingScript(
    mojom::RunLocation run_location,
    ScriptInjectionCallback permit_script)
    : run_location(run_location), permit_script(std::move(permit_script)) {}

ExtensionActionRunner::PendingScript::~PendingScript() = default;

ExtensionActionRunner::ExtensionActionRunner(content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      browser_context_(web_contents->GetBrowserContext()) {
  CHECK(web_contents);
  extension_registry_observation_.Observe(
      ExtensionRegistry::Get(browser_context_));
}

ExtensionActionRunner::~ExtensionActionRunner() {
  LogUMA();
}

// static
ExtensionActionRunner* ExtensionActionRunner::GetForWebContents(
    content::WebContents* web_contents) {
  if (!web_contents) {
    return nullptr;
  }
  TabHelper* tab_helper = TabHelper::FromWebContents(web_contents);
  return tab_helper ? tab_helper->extension_action_runner() : nullptr;
}

ExtensionAction::ShowAction ExtensionActionRunner::RunAction(
    const Extension* extension,
    bool grant_tab_permissions) {
  int tab_id = sessions::SessionTabHelper::IdForTab(web_contents()).id();

  if (grant_tab_permissions && GetBlockedActions(extension->id())) {
    // If the extension had blocked actions before granting tab permissions,
    // granting active tab will have run the extension. Don't execute further
    // since clicking should run blocked actions *or* the normal extension
    // action, not both.
    GrantTabPermissions({extension});
    return ExtensionAction::ShowAction::kNone;
  }

#if BUILDFLAG(ENABLE_EXTENSIONS)
  // Anything that gets here should have a page or browser action, or toggle the
  // extension's side panel, and not blocked actions.
  // This method is only called to execute an action by the user, so we can
  // grant tab permissions unless `action` will toggle the side panel. Tab
  // permissions are not granted in this case because:
  //  - the extension's side panel entry can be opened through the side panel
  //    itself which does not grant tab permissions
  //  - extension side panels can persist through tab changes and so
  //  permissions
  //    granted for one tab shouldn't persist on that side panel across tab
  //    changes.
  // TODO(crbug.com/40904917): Evaluate if this is the best course of action.
  SidePanelService* side_panel_service =
      SidePanelService::Get(browser_context_);
  if (side_panel_service &&
      side_panel_service->HasSidePanelActionForTab(*extension, tab_id)) {
    return ExtensionAction::ShowAction::kToggleSidePanel;
  }
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

  if (grant_tab_permissions) {
    GrantTabPermissions({extension});
  }

  ExtensionAction* extension_action =
      ExtensionActionManager::Get(browser_context_)
          ->GetExtensionAction(*extension);
  DCHECK(extension_action);

  if (!extension_action->GetIsVisible(tab_id)) {
    return ExtensionAction::ShowAction::kNone;
  }

  if (extension_action->HasPopup(tab_id)) {
    return ExtensionAction::ShowAction::kShowPopup;
  }

  ExtensionActionDispatcher::Get(browser_context_)
      ->DispatchExtensionActionClicked(*extension_action, web_contents(),
                                       extension);
  return ExtensionAction::ShowAction::kNone;
}

// TODO(crbug.com/40883928): Consider moving this to SitePermissionsHelper since
// it's more about permissions than running an action.
void ExtensionActionRunner::GrantTabPermissions(
    const std::vector<const Extension*>& extensions) {
  SitePermissionsHelper permissions_helper(
      Profile::FromBrowserContext(browser_context_));
  bool refresh_required = std::ranges::any_of(
      extensions, [this, &permissions_helper](const Extension* extension) {
        return permissions_helper.PageNeedsRefreshToRun(
            GetBlockedActions(extension->id()));
      });

  // If a refresh is required this prevents blocked actions (that wouldn't run
  // at the right time) from running until the user refreshes the page.
  base::AutoReset<bool> ignore_active_tab(&ignore_active_tab_granted_,
                                          refresh_required);
  // Immediately grant permissions to every extension.
  for (auto* extension : extensions) {
    ActiveTabPermissionGranter::FromWebContents(web_contents())
        ->GrantIfRequested(extension);
  }

  if (!refresh_required) {
    return;
  }

  // Every extension that was granted tab permission should currently have
  // "on click" site access, but extension actions are still blocked as page
  // hasn't been refreshed yet.
  const GURL& url = web_contents()->GetLastCommittedURL();
  auto* permissions_manager = PermissionsManager::Get(browser_context_);
  DCHECK(std::ranges::all_of(
      extensions, [url, &permissions_manager](const Extension* extension) {
        return permissions_manager->GetUserSiteAccess(*extension, url) ==
               PermissionsManager::UserSiteAccess::kOnClick;
      }));

  std::vector<ExtensionId> extension_ids = GetExtensionIds(extensions);
  ShowReloadPageBubble(extension_ids);
}

void ExtensionActionRunner::OnActiveTabPermissionGranted(
    const Extension* extension) {
  if (ignore_active_tab_granted_) {
    return;
  }

  if (WantsToRun(extension)) {
    RunBlockedActions(extension);
  }
}

void ExtensionActionRunner::OnWebRequestBlocked(const Extension* extension) {
  bool inserted = false;
  std::tie(std::ignore, inserted) =
      web_request_blocked_.insert(extension->id());
  if (inserted) {
    NotifyChange(extension);
  }

  for (TestObserver& observer : test_observers_) {
    observer.OnBlockedActionAdded();
  }
}

int ExtensionActionRunner::GetBlockedActions(
    const ExtensionId& extension_id) const {
  int blocked_actions = BLOCKED_ACTION_NONE;
  if (web_request_blocked_.count(extension_id) != 0) {
    blocked_actions |= BLOCKED_ACTION_WEB_REQUEST;
  }
  auto iter = pending_scripts_.find(extension_id);
  if (iter != pending_scripts_.end()) {
    for (const auto& script : iter->second) {
      switch (script->run_location) {
        case mojom::RunLocation::kDocumentStart:
          blocked_actions |= BLOCKED_ACTION_SCRIPT_AT_START;
          break;
        case mojom::RunLocation::kDocumentEnd:
        case mojom::RunLocation::kDocumentIdle:
        case mojom::RunLocation::kBrowserDriven:
          blocked_actions |= BLOCKED_ACTION_SCRIPT_OTHER;
          break;
        case mojom::RunLocation::kUndefined:
        case mojom::RunLocation::kRunDeferred:
          NOTREACHED();
      }
    }
  }

  return blocked_actions;
}

bool ExtensionActionRunner::WantsToRun(const Extension* extension) {
  return GetBlockedActions(extension->id()) != BLOCKED_ACTION_NONE;
}

void ExtensionActionRunner::RunForTesting(const Extension* extension) {
  if (WantsToRun(extension)) {
    ActiveTabPermissionGranter::FromWebContents(web_contents())
        ->GrantIfRequested(extension);
  }
}

PermissionsData::PageAccess
ExtensionActionRunner::RequiresUserConsentForScriptInjection(
    const Extension* extension,
    mojom::InjectionType type) {
  CHECK(extension);

  // Allow the extension if it's been explicitly granted permission.
  if (permitted_extensions_.count(extension->id()) > 0) {
    return PermissionsData::PageAccess::kAllowed;
  }

  GURL url = web_contents()->GetVisibleURL();
  int tab_id = sessions::SessionTabHelper::IdForTab(web_contents()).id();
  switch (type) {
    case mojom::InjectionType::kContentScript:
      return extension->permissions_data()->GetContentScriptAccess(url, tab_id,
                                                                   nullptr);
    case mojom::InjectionType::kProgrammaticScript:
      return extension->permissions_data()->GetPageAccess(url, tab_id, nullptr);
  }

  NOTREACHED();
}

void ExtensionActionRunner::RequestScriptInjection(
    const Extension* extension,
    mojom::RunLocation run_location,
    ScriptInjectionCallback callback) {
  CHECK(extension);
  PendingScriptList& list = pending_scripts_[extension->id()];
  list.push_back(
      std::make_unique<PendingScript>(run_location, std::move(callback)));

  // If this was the first entry, we need to notify that a new extension wants
  // to run.
  if (list.size() == 1u) {
    NotifyChange(extension);
  }

  was_used_on_page_ = true;

  for (TestObserver& observer : test_observers_) {
    observer.OnBlockedActionAdded();
  }
}

void ExtensionActionRunner::RunPendingScriptsForExtension(
    const Extension* extension) {
  DCHECK(extension);

  content::NavigationEntry* visible_entry =
      web_contents()->GetController().GetVisibleEntry();
  // Refuse to run if the visible entry is the initial NavigationEntry, because
  // we have no way of determining if it's the proper page. This should rarely,
  // if ever, happen.
  if (visible_entry->IsInitialEntry()) {
    return;
  }

  // We add this to the list of permitted extensions and erase pending entries
  // *before* running them to guard against the crazy case where running the
  // callbacks adds more entries.
  permitted_extensions_.insert(extension->id());

  auto iter = pending_scripts_.find(extension->id());
  if (iter == pending_scripts_.end()) {
    return;
  }

  PendingScriptList scripts;
  iter->second.swap(scripts);
  pending_scripts_.erase(extension->id());

  // Run all pending injections for the given extension.
  RunCallbackOnPendingScript(scripts, true);
}

void ExtensionActionRunner::OnRequestScriptInjectionPermission(
    const ExtensionId& extension_id,
    mojom::InjectionType script_type,
    mojom::RunLocation run_location,
    mojom::LocalFrameHost::RequestScriptInjectionPermissionCallback callback) {
  const Extension* extension = ExtensionRegistry::Get(browser_context_)
                                   ->enabled_extensions()
                                   .GetByID(extension_id);
  // We shouldn't allow extensions which are no longer enabled to run any
  // scripts. Ignore the request.
  if (!extension) {
    std::move(callback).Run(false);
    return;
  }

  ++num_page_requests_;

  switch (RequiresUserConsentForScriptInjection(extension, script_type)) {
    case PermissionsData::PageAccess::kAllowed:
      std::move(callback).Run(true);
      break;
    case PermissionsData::PageAccess::kWithheld:
      RequestScriptInjection(extension, run_location, std::move(callback));
      break;
    case PermissionsData::PageAccess::kDenied:
      std::move(callback).Run(false);
      // We should usually only get a "deny access" if the page changed (as the
      // renderer wouldn't have requested permission if the answer was always
      // "no"). Just let the request fizzle and die.
      break;
  }
}

void ExtensionActionRunner::AddObserver(TestObserver* observer) {
  test_observers_.AddObserver(observer);
}

void ExtensionActionRunner::RemoveObserver(TestObserver* observer) {
  test_observers_.RemoveObserver(observer);
}

void ExtensionActionRunner::NotifyChange(const Extension* extension) {
  ExtensionActionDispatcher* extension_action_api =
      ExtensionActionDispatcher::Get(browser_context_);
  ExtensionAction* extension_action =
      ExtensionActionManager::Get(browser_context_)
          ->GetExtensionAction(*extension);
  // If the extension has an action, we need to notify that it's updated.
  if (extension_action) {
    extension_action_api->NotifyChange(extension_action, web_contents(),
                                       browser_context_);
  }
}

void ExtensionActionRunner::LogUMA() const {
  // We only log the permitted extensions metric if the feature was used at all
  // on the page, because otherwise the data will be boring.
  if (was_used_on_page_) {
    UMA_HISTOGRAM_COUNTS_100(
        "Extensions.ActiveScriptController.PermittedExtensions",
        permitted_extensions_.size());
    UMA_HISTOGRAM_COUNTS_100(
        "Extensions.ActiveScriptController.DeniedExtensions",
        pending_scripts_.size());
  }
}

void ExtensionActionRunner::ShowReloadPageBubble(
    const std::vector<ExtensionId>& extension_ids) {
  // For testing, simulate the bubble being accepted by directly invoking the
  // callback, or rejected by skipping the callback.
  if (accept_bubble_for_testing_.has_value()) {
    if (*accept_bubble_for_testing_) {
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE,
          base::BindOnce(&ExtensionActionRunner::OnReloadPageBubbleAccepted,
                         weak_factory_.GetWeakPtr()));
    }
    return;
  }

#if BUILDFLAG(ENABLE_EXTENSIONS)
  // TODO(emiliapaz): Consider showing the dialog as a modal if container
  // doesn't exist. Currently we get the extension's icon via the action
  // controller from the container, so the container must exist.
  Browser* browser = chrome::FindBrowserWithTab(web_contents());
  ExtensionsContainer* const extensions_container =
      browser ? browser->window()->GetExtensionsContainer() : nullptr;
  if (!extensions_container) {
    return;
  }

  ShowReloadPageDialog(
      browser, extension_ids,
      base::BindOnce(&ExtensionActionRunner::OnReloadPageBubbleAccepted,
                     weak_factory_.GetWeakPtr()));
#else
  // TODO(crbug.com/371432155): Add the above code to desktop Android when we
  // have a tab interface that works on Android. For now, just accept the
  // dialog.
  NOTIMPLEMENTED() << "Accepting reload page bubble";
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&ExtensionActionRunner::OnReloadPageBubbleAccepted,
                     weak_factory_.GetWeakPtr()));
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)
}

void ExtensionActionRunner::OnReloadPageBubbleAccepted() {
  web_contents()->GetController().Reload(content::ReloadType::NORMAL, false);
}

void ExtensionActionRunner::RunBlockedActions(const Extension* extension) {
  DCHECK(base::Contains(pending_scripts_, extension->id()) ||
         web_request_blocked_.count(extension->id()) != 0);

  // Clicking to run the extension counts as granting it permission to run on
  // the given tab.
  // The extension may already have active tab at this point, but granting
  // it twice is essentially a no-op.
  ActiveTabPermissionGranter::FromWebContents(web_contents())
      ->GrantIfRequested(extension);

  RunPendingScriptsForExtension(extension);
  web_request_blocked_.erase(extension->id());
}

void ExtensionActionRunner::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  declarative_net_request::RulesMonitorService* rules_monitor_service =
      declarative_net_request::RulesMonitorService::Get(browser_context_);

  if (!navigation_handle->IsInPrimaryMainFrame() ||
      !navigation_handle->HasCommitted() ||
      navigation_handle->IsSameDocument()) {
    if (rules_monitor_service && !navigation_handle->IsSameDocument()) {
      // Clean up any pending actions recorded in the action tracker for this
      // navigation.
      rules_monitor_service->action_tracker().ClearPendingNavigation(
          navigation_handle->GetNavigationId());
    }
    return;
  }

  LogUMA();
  num_page_requests_ = 0;
  permitted_extensions_.clear();
  // Runs all pending callbacks before clearing them.
  for (auto& scripts : pending_scripts_) {
    RunCallbackOnPendingScript(scripts.second, false);
  }
  pending_scripts_.clear();
  web_request_blocked_.clear();
  was_used_on_page_ = false;
  weak_factory_.InvalidateWeakPtrs();

  // Note: This needs to be called *after* the maps have been updated, so that
  // when the UI updates, this object returns the proper result for "wants to
  // run".
  ExtensionActionDispatcher::Get(browser_context_)
      ->ClearAllValuesForTab(web_contents());
  // |rules_monitor_service| can be null for some unit tests.
  if (rules_monitor_service) {
    int tab_id = ExtensionTabUtil::GetTabId(web_contents());
    declarative_net_request::ActionTracker& action_tracker =
        rules_monitor_service->action_tracker();
    action_tracker.ResetTrackedInfoForTab(tab_id,
                                          navigation_handle->GetNavigationId());
  }
}

void ExtensionActionRunner::WebContentsDestroyed() {
  ExtensionActionDispatcher::Get(browser_context_)
      ->ClearAllValuesForTab(web_contents());

  declarative_net_request::RulesMonitorService* rules_monitor_service =
      declarative_net_request::RulesMonitorService::Get(browser_context_);

  // |rules_monitor_service| can be null for some unit tests.
  if (rules_monitor_service) {
    declarative_net_request::ActionTracker& action_tracker =
        rules_monitor_service->action_tracker();

    int tab_id = ExtensionTabUtil::GetTabId(web_contents());
    action_tracker.ClearTabData(tab_id);
  }
}

void ExtensionActionRunner::OnExtensionUnloaded(
    content::BrowserContext* browser_context,
    const Extension* extension,
    UnloadedExtensionReason reason) {
  auto iter = pending_scripts_.find(extension->id());
  if (iter != pending_scripts_.end()) {
    PendingScriptList scripts;
    iter->second.swap(scripts);
    pending_scripts_.erase(iter);
    NotifyChange(extension);

    RunCallbackOnPendingScript(scripts, false);
  }
}

void ExtensionActionRunner::RunCallbackOnPendingScript(
    const PendingScriptList& list,
    bool granted) {
  // Calls RequestScriptInjectionPermissionCallback stored in
  // |pending_scripts_|.
  for (const auto& pending_script : list) {
    std::move(pending_script->permit_script).Run(granted);
  }
}

}  // namespace extensions