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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_EXTENSIONS_BROWSER_CLIENT_H_
#define EXTENSIONS_BROWSER_EXTENSIONS_BROWSER_CLIENT_H_
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "base/functional/callback_forward.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_memory.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "content/public/browser/bluetooth_chooser.h"
#include "content/public/browser/frame_tree_node_id.h"
#include "extensions/browser/extension_event_histogram_value.h"
#include "extensions/browser/extension_prefs_observer.h"
#include "extensions/browser/extensions_browser_api_provider.h"
#include "extensions/browser/script_executor.h"
#include "extensions/common/api/declarative_net_request.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "mojo/public/cpp/bindings/binder_map.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "services/network/public/mojom/url_loader.mojom-forward.h"
#include "services/network/public/mojom/url_loader_factory.mojom-forward.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
class ExtensionFunctionRegistry;
class PrefService;
namespace base {
class CommandLine;
class FilePath;
} // namespace base
namespace content {
class BrowserContext;
class RenderFrameHost;
class SiteInstance;
class StoragePartitionConfig;
class WebContents;
} // namespace content
namespace net {
class HttpResponseHeaders;
} // namespace net
namespace network {
struct ResourceRequest;
namespace mojom {
class NetworkContext;
}
} // namespace network
namespace update_client {
class UpdateClient;
} // namespace update_client
namespace url {
class Origin;
} // namespace url
namespace base {
class CancelableTaskTracker;
} // namespace base
namespace media_device_salt {
class MediaDeviceSaltService;
} // namespace media_device_salt
namespace extensions {
class ComponentExtensionResourceManager;
class Extension;
class ExtensionCache;
class ExtensionError;
class ExtensionHostDelegate;
class ExtensionSet;
class ExtensionSystem;
class ExtensionSystemProvider;
class ExtensionWebContentsObserver;
class KioskDelegate;
class PermissionSet;
class ProcessManagerDelegate;
class ProcessMap;
class RuntimeAPIDelegate;
class ScopedExtensionUpdaterKeepAlive;
class UserScriptListener;
// Interface to allow the extensions module to make browser-process-specific
// queries of the embedder. Should be Set() once in the browser process.
//
// NOTE: Methods that do not require knowledge of browser concepts should be
// added in ExtensionsClient (extensions/common/extensions_client.h) even if
// they are only used in the browser process.
class ExtensionsBrowserClient {
public:
ExtensionsBrowserClient();
ExtensionsBrowserClient(const ExtensionsBrowserClient&) = delete;
ExtensionsBrowserClient& operator=(const ExtensionsBrowserClient&) = delete;
virtual ~ExtensionsBrowserClient();
// Returns the single instance of `this`.
static ExtensionsBrowserClient* Get();
// Sets and initializes the single instance.
static void Set(ExtensionsBrowserClient* client);
// Registers all extension functions.
void RegisterExtensionFunctions(ExtensionFunctionRegistry* registry);
// Adds a new API provider to the client.
void AddAPIProvider(std::unique_ptr<ExtensionsBrowserAPIProvider> provider);
/////////////////////////////////////////////////////////////////////////////
// Virtual Methods
// Initializes the client. For Chrome, must be called after g_browser_process
// is constructed, due to dependencies of UserScriptLoader.
virtual void Init() = 0;
// Alerts the ExtensionsBrowserClient that the browser is shutting down,
// indicating that we should perform any teardown necessary before being
// destroyed (e.g. unsubscribing observers, or any other pre-emptive freeing
// of resources. Note that we may still receive calls from other shutting
// down objects after this call, so this should primarily be used for things
// that may need to be cleaned up before other parts of the browser).
virtual void StartTearDown();
// Returns true if the embedder has started shutting down.
virtual bool IsShuttingDown() = 0;
// Returns true if extensions have been disabled (e.g. via a command-line flag
// or preference).
virtual bool AreExtensionsDisabled(const base::CommandLine& command_line,
content::BrowserContext* context) = 0;
// Returns true if the `context` is known to the embedder.
// Note: This is a `void*` to ensure downstream uses do not use the `context`
// in case it is *not* valid.
virtual bool IsValidContext(void* context) = 0;
// Returns true if the BrowserContexts could be considered equivalent, for
// example, if one is an off-the-record context owned by the other.
virtual bool IsSameContext(content::BrowserContext* first,
content::BrowserContext* second) = 0;
// Returns true if `context` has an off-the-record context associated with it.
virtual bool HasOffTheRecordContext(content::BrowserContext* context) = 0;
// Returns the off-the-record context associated with `context`. If `context`
// is already off-the-record, returns `context`.
// WARNING: This may create a new off-the-record context. To avoid creating
// another context, check HasOffTheRecordContext() first.
virtual content::BrowserContext* GetOffTheRecordContext(
content::BrowserContext* context) = 0;
// Returns the original "recording" context. This method returns `context` if
// `context` is not incognito.
virtual content::BrowserContext* GetOriginalContext(
content::BrowserContext* context) = 0;
// The below methods are modeled off `Profile` and `ProfileSelections` in
// //chrome where their implementation filters out Profiles based on their
// types (Regular, Guest, System, etc..) and sub-implementation (Original vs
// OTR).
// - if `context` is a System Profile: returns null.
// - if `context` is Original: returns itself.
// - if `context` is OTR: returns the associated parent context.
virtual content::BrowserContext* GetContextRedirectedToOriginal(
content::BrowserContext* context) = 0;
// - if `context` is a System Profile: returns null.
// - if `context` is Original: returns itself.
// - if `context` is OTR: returns itself.
virtual content::BrowserContext* GetContextOwnInstance(
content::BrowserContext* context) = 0;
// - if `context` is a System Profile: returns null.
// - if `context` is Original: returns itself.
// - if `context` is OTR: returns null.
virtual content::BrowserContext* GetContextForOriginalOnly(
content::BrowserContext* context) = 0;
// Returns whether the `context` has extensions disabled.
// An example of an implementation of `BrowserContext` that has extensions
// disabled is `Profile` of type System Profile.
virtual bool AreExtensionsDisabledForContext(
content::BrowserContext* context) = 0;
#if BUILDFLAG(IS_CHROMEOS)
// Returns true if `browser_context` is the active one.
virtual bool IsActiveContext(
content::BrowserContext* browser_context) const = 0;
// Returns a user id hash from `context` or an empty string if no hash could
// be extracted.
virtual std::string GetUserIdHashFromContext(
content::BrowserContext* context) = 0;
#endif
// Returns true if `context` corresponds to a guest session.
virtual bool IsGuestSession(content::BrowserContext* context) const = 0;
// Returns true if `extension_id` can run in an incognito window.
virtual bool IsExtensionIncognitoEnabled(
const ExtensionId& extension_id,
content::BrowserContext* context) const = 0;
// Returns true if `extension` can see events and data from another
// sub-profile (incognito to original profile, or vice versa).
virtual bool CanExtensionCrossIncognito(
const extensions::Extension* extension,
content::BrowserContext* context) const = 0;
// Return the resource relative path and id for the given request.
virtual base::FilePath GetBundleResourcePath(
const network::ResourceRequest& request,
const base::FilePath& extension_resources_path,
int* resource_id) const = 0;
// Creates and starts a URLLoader to load an extension resource from the
// embedder's resource bundle (.pak) files. Used for component extensions.
virtual void LoadResourceFromResourceBundle(
const network::ResourceRequest& request,
mojo::PendingReceiver<network::mojom::URLLoader> loader,
const base::FilePath& resource_relative_path,
int resource_id,
scoped_refptr<net::HttpResponseHeaders> headers,
mojo::PendingRemote<network::mojom::URLLoaderClient> client) = 0;
// Returns true if the embedder wants to allow a chrome-extension:// resource
// request coming from renderer A to access a resource in an extension running
// in renderer B. For example, Chrome overrides this to provide support for
// webview and dev tools. May be called on either the UI or IO thread.
virtual bool AllowCrossRendererResourceLoad(
const network::ResourceRequest& request,
network::mojom::RequestDestination destination,
ui::PageTransition page_transition,
int child_id,
bool is_incognito,
const Extension* extension,
const ExtensionSet& extensions,
const ProcessMap& process_map,
const GURL& upstream_url) = 0;
// Returns the PrefService associated with `context`.
virtual PrefService* GetPrefServiceForContext(
content::BrowserContext* context) = 0;
// Populates a list of ExtensionPrefs observers to be attached to each
// BrowserContext's ExtensionPrefs upon construction. These observers
// are not owned by ExtensionPrefs.
virtual void GetEarlyExtensionPrefsObservers(
content::BrowserContext* context,
std::vector<EarlyExtensionPrefsObserver*>* observers) const = 0;
// Returns the ProcessManagerDelegate shared across all BrowserContexts. May
// return NULL in tests or for simple embedders.
virtual ProcessManagerDelegate* GetProcessManagerDelegate() const = 0;
virtual mojo::PendingRemote<network::mojom::URLLoaderFactory>
GetControlledFrameEmbedderURLLoader(
const url::Origin& app_origin,
content::FrameTreeNodeId frame_tree_node_id,
content::BrowserContext* browser_context) = 0;
// Creates a new ExtensionHostDelegate instance.
virtual std::unique_ptr<ExtensionHostDelegate>
CreateExtensionHostDelegate() = 0;
// Returns true if the client version has updated since the last run. Called
// once each time the extensions system is loaded per browser_context. The
// implementation may wish to use the BrowserContext to record the current
// version for later comparison.
virtual bool DidVersionUpdate(content::BrowserContext* context) = 0;
// Permits an external protocol handler to be launched. See
// ExternalProtocolHandler::PermitLaunchUrl() in Chrome.
virtual void PermitExternalProtocolHandler() = 0;
// Return true if the device is enrolled in Demo Mode.
virtual bool IsInDemoMode() = 0;
// Return true if `app_id` matches the screensaver and the device is enrolled
// in Demo Mode.
virtual bool IsScreensaverInDemoMode(const std::string& app_id) = 0;
// Return true if the system is run in forced app mode.
virtual bool IsRunningInForcedAppMode() = 0;
// Returns whether the system is run in forced app mode for app with the
// provided extension ID.
virtual bool IsAppModeForcedForApp(const ExtensionId& id) = 0;
// Return true if the user is logged in as a public session.
virtual bool IsLoggedInAsPublicAccount() = 0;
// Returns the factory that provides an ExtensionSystem to be returned from
// ExtensionSystem::Get.
virtual ExtensionSystemProvider* GetExtensionSystemFactory() = 0;
// Registers additional interfaces to a binder map for a browser interface
// broker.
virtual void RegisterBrowserInterfaceBindersForFrame(
mojo::BinderMapWithContext<content::RenderFrameHost*>* binder_map,
content::RenderFrameHost* render_frame_host,
const Extension* extension) const = 0;
// Creates a RuntimeAPIDelegate responsible for handling extensions
// management-related events such as update and installation on behalf of the
// core runtime API implementation.
virtual std::unique_ptr<RuntimeAPIDelegate> CreateRuntimeAPIDelegate(
content::BrowserContext* context) const = 0;
// Returns the manager of resource bundles used in extensions. Returns NULL if
// the manager doesn't exist.
virtual const ComponentExtensionResourceManager*
GetComponentExtensionResourceManager() = 0;
// Propagate a event to all the renderers in every browser context. The
// implementation must be safe to call from any thread.
virtual void BroadcastEventToRenderers(
events::HistogramValue histogram_value,
const std::string& event_name,
base::Value::List args,
bool dispatch_to_off_the_record_profiles) = 0;
// Gets the single ExtensionCache instance shared across the browser process.
virtual ExtensionCache* GetExtensionCache() = 0;
// Indicates whether extension update checks should be allowed.
virtual bool IsBackgroundUpdateAllowed() = 0;
// Indicates whether an extension update which specifies its minimum browser
// version as `min_version` can be installed by the client. Not all extensions
// embedders share the same versioning model, so interpretation of the string
// is left up to the embedder.
virtual bool IsMinBrowserVersionSupported(const std::string& min_version) = 0;
// Embedders can override this function to handle extension errors.
virtual void ReportError(content::BrowserContext* context,
std::unique_ptr<ExtensionError> error);
// Creates a new instance of an ExtensionWebContentsObserver and attaches it
// to the given `web_contents`.
virtual void CreateExtensionWebContentsObserver(
content::WebContents* web_contents) = 0;
// Returns the ExtensionWebContentsObserver for the given `web_contents`.
virtual ExtensionWebContentsObserver* GetExtensionWebContentsObserver(
content::WebContents* web_contents) = 0;
// Cleans up browser-side state associated with a WebView that is being
// destroyed.
virtual void CleanUpWebView(content::BrowserContext* browser_context,
int embedder_process_id,
int view_instance_id) {}
// Clears the back-forward cache for all active tabs across all browser
// contexts.
virtual void ClearBackForwardCache() {}
// Attaches the task manager extension tag to `web_contents`, if needed based
// on `view_type`, so that its corresponding task shows up in the task
// manager.
virtual void AttachExtensionTaskManagerTag(content::WebContents* web_contents,
mojom::ViewType view_type) {}
// Returns a new UpdateClient.
virtual scoped_refptr<update_client::UpdateClient> CreateUpdateClient(
content::BrowserContext* context);
// Returns a new ScopedExtensionUpdaterKeepAlive, or nullptr if the embedder
// does not support keeping the context alive while the updater is running.
virtual std::unique_ptr<ScopedExtensionUpdaterKeepAlive>
CreateUpdaterKeepAlive(content::BrowserContext* context);
// Returns true if activity logging is enabled for the given `context`.
virtual bool IsActivityLoggingEnabled(content::BrowserContext* context);
// Retrives the embedder's notion of tab and window ID for a given
// WebContents. May return -1 for either or both values if the embedder does
// not implement any such concepts. This is used to support the WebRequest API
// exposing such numbers to callers.
virtual void GetTabAndWindowIdForWebContents(
content::WebContents* web_contents,
int* tab_id,
int* window_id);
// Returns a delegate that provides kiosk mode functionality.
virtual KioskDelegate* GetKioskDelegate() = 0;
// Returns the locale used by the application.
virtual std::string GetApplicationLocale() = 0;
// Returns whether `extension_id` is currently enabled.
// This will only return a valid answer for installed extensions (regardless
// of whether it is currently loaded or not) under the provided `context`.
// Loaded extensions return true if they are currently loaded or terminated.
// Unloaded extensions will return true if they are not blocked, disabled,
// blocklisted or uninstalled (for external extensions). The default return
// value of this function is false.
virtual bool IsExtensionEnabled(const ExtensionId& extension_id,
content::BrowserContext* context) const;
// http://crbug.com/829412
// Renderers with WebUI bindings shouldn't make http(s) requests for security
// reasons (e.g. to avoid malicious responses being able to run code in
// priviliged renderers). Fix these webui's to make requests through C++
// code instead.
virtual bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin);
virtual network::mojom::NetworkContext* GetSystemNetworkContext();
virtual UserScriptListener* GetUserScriptListener();
// Called when all initial script loads from extensions have been completed
// for the given BrowserContext.
virtual void SignalContentScriptsLoaded(content::BrowserContext* context);
// Returns whether `scheme` should bypass extension-specific navigation checks
// (e.g. whether the `scheme` is allowed to initiate navigations to extension
// resources that are not declared as web accessible).
virtual bool ShouldSchemeBypassNavigationChecks(
const std::string& scheme) const;
// Gets and sets the last save (download) path for a given context.
virtual base::FilePath GetSaveFilePath(content::BrowserContext* context);
virtual void SetLastSaveFilePath(content::BrowserContext* context,
const base::FilePath& path);
// Returns true if the `extension_id` requires its own isolated storage
// partition.
virtual bool HasIsolatedStorage(const ExtensionId& extension_id,
content::BrowserContext* context);
// Returns whether screenshot of `web_contents` is restricted due to Data Leak
// Protection policy.
virtual bool IsScreenshotRestricted(content::WebContents* web_contents) const;
// Returns true if `tab_id` exists on `browser_context`.
virtual bool IsValidTabId(content::BrowserContext* browser_context,
int tab_id,
bool include_incognito,
content::WebContents** web_contents) const;
// Returns true if chrome extension telemetry service is enabled.
virtual bool IsExtensionTelemetryServiceEnabled(
content::BrowserContext* context) const;
// Returns the script executor for `web_contents`.
virtual ScriptExecutor* GetScriptExecutorForTab(
content::WebContents& web_contents);
// TODO(anunoy): This is a temporary implementation of notifying the
// extension telemetry service of the tabs.executeScript API invocation
// while its usefulness is evaluated.
virtual void NotifyExtensionApiTabExecuteScript(
content::BrowserContext* context,
const ExtensionId& extension_id,
const std::string& code) const;
// Notifies the extension telemetry service when declarativeNetRequest API
// rules are added.
virtual void NotifyExtensionApiDeclarativeNetRequest(
content::BrowserContext* context,
const ExtensionId& extension_id,
const std::vector<api::declarative_net_request::Rule>& rules) const;
// Notifies the extension telemetry service when declarativeNetRequest
// redirect action is invoked.
virtual void NotifyExtensionDeclarativeNetRequestRedirectAction(
content::BrowserContext* context,
const ExtensionId& extension_id,
const GURL& request_url,
const GURL& redirect_url) const;
// Return true if the USB device is allowed by policy.
virtual bool IsUsbDeviceAllowedByPolicy(content::BrowserContext* context,
const ExtensionId& extension_id,
int vendor_id,
int product_id) const;
// Populate callback with the asynchronously retrieved cached favicon image.
virtual void GetFavicon(
content::BrowserContext* browser_context,
const Extension* extension,
const GURL& url,
base::CancelableTaskTracker* tracker,
base::OnceCallback<void(
scoped_refptr<base::RefCountedMemory> bitmap_data)> callback) const;
// Returns all BrowserContexts related to the given extension. For an
// extension limited to a signal context, this will be a vector of the single
// passed-in context. For extensions allowed to run in incognito contexts
// associated with `browser_context`, this will include all those contexts.
// Note: It may not be appropriate to treat these the same depending on
// whether the extension runs in "split" or "spanning" mode.
virtual std::vector<content::BrowserContext*> GetRelatedContextsForExtension(
content::BrowserContext* browser_context,
const Extension& extension) const;
// Adds any hosts that should be automatically considered "granted" if
// requested to `granted_permissions`.
virtual void AddAdditionalAllowedHosts(
const PermissionSet& desired_permissions,
PermissionSet* granted_permissions) const;
virtual void AddAPIActionToActivityLog(
content::BrowserContext* browser_context,
const ExtensionId& extension_id,
const std::string& call_name,
base::Value::List args,
const std::string& extra);
virtual void AddEventToActivityLog(content::BrowserContext* context,
const ExtensionId& extension_id,
const std::string& call_name,
base::Value::List args,
const std::string& extra);
virtual void AddDOMActionToActivityLog(
content::BrowserContext* browser_context,
const ExtensionId& extension_id,
const std::string& call_name,
base::Value::List args,
const GURL& url,
const std::u16string& url_title,
int call_type);
// Invokes `callback` with the StoragePartitionConfig that should be used for
// a <webview> or <controlledframe> with the given `partition_name` that is
// owned by a frame within `owner_site_instance`.
virtual void GetWebViewStoragePartitionConfig(
content::BrowserContext* browser_context,
content::SiteInstance* owner_site_instance,
const std::string& partition_name,
bool in_memory,
base::OnceCallback<void(std::optional<content::StoragePartitionConfig>)>
callback);
// Creates password reuse detection manager when new extension web contents
// are created.
virtual void CreatePasswordReuseDetectionManager(
content::WebContents* web_contents) const;
// Returns a service that provides persistent salts for generating media
// device IDs. Can be null if the embedder does not support persistent salts.
virtual media_device_salt::MediaDeviceSaltService* GetMediaDeviceSaltService(
content::BrowserContext* context);
// TODO(crbug.com/399198255): as per rdcronin@: this doesn't belong here,
// since extensions shouldn't have knowledge of Controlled Frame.
virtual bool HasControlledFrameCapability(content::BrowserContext* context,
const GURL& url);
private:
std::vector<std::unique_ptr<ExtensionsBrowserAPIProvider>> providers_;
};
} // namespace extensions
#endif // EXTENSIONS_BROWSER_EXTENSIONS_BROWSER_CLIENT_H_
|