1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/active_script_controller.h"
8 #include "base/bind_helpers.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/metrics/histogram.h"
11 #include "base/stl_util.h"
12 #include "chrome/browser/extensions/active_tab_permission_granter.h"
13 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
14 #include "chrome/browser/extensions/extension_action.h"
15 #include "chrome/browser/extensions/extension_action_manager.h"
16 #include "chrome/browser/extensions/extension_util.h"
17 #include "chrome/browser/extensions/permissions_updater.h"
18 #include "chrome/browser/extensions/tab_helper.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/sessions/session_tab_helper.h"
21 #include "chrome/common/extensions/api/extension_action/action_info.h"
22 #include "components/crx_file/id_util.h"
23 #include "content/public/browser/navigation_controller.h"
24 #include "content/public/browser/navigation_details.h"
25 #include "content/public/browser/navigation_entry.h"
26 #include "content/public/browser/render_view_host.h"
27 #include "content/public/browser/web_contents.h"
28 #include "extensions/browser/extension_registry.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/extension_set.h"
32 #include "extensions/common/feature_switch.h"
33 #include "extensions/common/manifest.h"
34 #include "extensions/common/permissions/permission_set.h"
35 #include "extensions/common/permissions/permissions_data.h"
36 #include "ipc/ipc_message_macros.h"
38 namespace extensions
{
42 // Returns true if the extension should be regarded as a "permitted" extension
43 // for the case of metrics. We need this because we only actually withhold
44 // permissions if the switch is enabled, but want to record metrics in all
46 // "ExtensionWouldHaveHadHostPermissionsWithheldIfSwitchWasOn()" would be
47 // more accurate, but too long.
48 bool ShouldRecordExtension(const Extension
* extension
) {
49 return extension
->ShouldDisplayInExtensionSettings() &&
50 !Manifest::IsPolicyLocation(extension
->location()) &&
51 !Manifest::IsComponentLocation(extension
->location()) &&
52 !PermissionsData::CanExecuteScriptEverywhere(extension
) &&
53 extension
->permissions_data()
54 ->active_permissions()
55 ->ShouldWarnAllHosts();
60 ActiveScriptController::ActiveScriptController(
61 content::WebContents
* web_contents
)
62 : content::WebContentsObserver(web_contents
),
63 browser_context_(web_contents
->GetBrowserContext()),
64 enabled_(FeatureSwitch::scripts_require_action()->IsEnabled()),
65 extension_registry_observer_(this) {
67 extension_registry_observer_
.Add(ExtensionRegistry::Get(browser_context_
));
70 ActiveScriptController::~ActiveScriptController() {
75 ActiveScriptController
* ActiveScriptController::GetForWebContents(
76 content::WebContents
* web_contents
) {
79 TabHelper
* tab_helper
= TabHelper::FromWebContents(web_contents
);
80 return tab_helper
? tab_helper
->active_script_controller() : NULL
;
83 void ActiveScriptController::OnActiveTabPermissionGranted(
84 const Extension
* extension
) {
85 RunPendingForExtension(extension
);
88 void ActiveScriptController::OnAdInjectionDetected(
89 const std::set
<std::string
>& ad_injectors
) {
90 // We're only interested in data if there are ad injectors detected.
91 if (ad_injectors
.empty())
94 size_t num_preventable_ad_injectors
=
95 base::STLSetIntersection
<std::set
<std::string
> >(
96 ad_injectors
, permitted_extensions_
).size();
98 UMA_HISTOGRAM_COUNTS_100(
99 "Extensions.ActiveScriptController.PreventableAdInjectors",
100 num_preventable_ad_injectors
);
101 UMA_HISTOGRAM_COUNTS_100(
102 "Extensions.ActiveScriptController.UnpreventableAdInjectors",
103 ad_injectors
.size() - num_preventable_ad_injectors
);
106 void ActiveScriptController::AlwaysRunOnVisibleOrigin(
107 const Extension
* extension
) {
108 const GURL
& url
= web_contents()->GetVisibleURL();
109 URLPatternSet new_explicit_hosts
;
110 URLPatternSet new_scriptable_hosts
;
112 scoped_refptr
<const PermissionSet
> withheld_permissions
=
113 extension
->permissions_data()->withheld_permissions();
114 if (withheld_permissions
->explicit_hosts().MatchesURL(url
)) {
115 new_explicit_hosts
.AddOrigin(UserScript::ValidUserScriptSchemes(),
118 if (withheld_permissions
->scriptable_hosts().MatchesURL(url
)) {
119 new_scriptable_hosts
.AddOrigin(UserScript::ValidUserScriptSchemes(),
123 scoped_refptr
<PermissionSet
> new_permissions
=
124 new PermissionSet(APIPermissionSet(),
125 ManifestPermissionSet(),
127 new_scriptable_hosts
);
129 // Update permissions for the session. This adds |new_permissions| to active
130 // permissions and granted permissions.
131 // TODO(devlin): Make sure that the permission is removed from
132 // withheld_permissions if appropriate.
133 PermissionsUpdater(browser_context_
).AddPermissions(extension
,
134 new_permissions
.get());
136 // Allow current tab to run injection.
137 OnClicked(extension
);
140 void ActiveScriptController::OnClicked(const Extension
* extension
) {
141 DCHECK(ContainsKey(pending_requests_
, extension
->id()));
142 RunPendingForExtension(extension
);
145 bool ActiveScriptController::WantsToRun(const Extension
* extension
) {
146 return enabled_
&& pending_requests_
.count(extension
->id()) > 0;
149 PermissionsData::AccessType
150 ActiveScriptController::RequiresUserConsentForScriptInjection(
151 const Extension
* extension
,
152 UserScript::InjectionType type
) {
155 // If the feature is not enabled, we automatically allow all extensions to
158 permitted_extensions_
.insert(extension
->id());
160 // Allow the extension if it's been explicitly granted permission.
161 if (permitted_extensions_
.count(extension
->id()) > 0)
162 return PermissionsData::ACCESS_ALLOWED
;
164 GURL url
= web_contents()->GetVisibleURL();
165 int tab_id
= SessionTabHelper::IdForTab(web_contents());
167 case UserScript::CONTENT_SCRIPT
:
168 return extension
->permissions_data()->GetContentScriptAccess(
169 extension
, url
, url
, tab_id
, -1, NULL
);
170 case UserScript::PROGRAMMATIC_SCRIPT
:
171 return extension
->permissions_data()->GetPageAccess(
172 extension
, url
, url
, tab_id
, -1, NULL
);
176 return PermissionsData::ACCESS_DENIED
;
179 void ActiveScriptController::RequestScriptInjection(
180 const Extension
* extension
,
181 const base::Closure
& callback
) {
183 PendingRequestList
& list
= pending_requests_
[extension
->id()];
184 list
.push_back(callback
);
186 // If this was the first entry, we need to notify that a new extension wants
188 if (list
.size() == 1u)
189 NotifyChange(extension
);
192 void ActiveScriptController::RunPendingForExtension(
193 const Extension
* extension
) {
196 content::NavigationEntry
* visible_entry
=
197 web_contents()->GetController().GetVisibleEntry();
198 // Refuse to run if there's no visible entry, because we have no idea of
199 // determining if it's the proper page. This should rarely, if ever, happen.
203 // We add this to the list of permitted extensions and erase pending entries
204 // *before* running them to guard against the crazy case where running the
205 // callbacks adds more entries.
206 permitted_extensions_
.insert(extension
->id());
208 PendingRequestMap::iterator iter
= pending_requests_
.find(extension
->id());
209 if (iter
== pending_requests_
.end())
212 PendingRequestList requests
;
213 iter
->second
.swap(requests
);
214 pending_requests_
.erase(extension
->id());
216 // Clicking to run the extension counts as granting it permission to run on
218 // The extension may already have active tab at this point, but granting
219 // it twice is essentially a no-op.
220 TabHelper::FromWebContents(web_contents())->
221 active_tab_permission_granter()->GrantIfRequested(extension
);
223 // Run all pending injections for the given extension.
224 for (PendingRequestList::iterator request
= requests
.begin();
225 request
!= requests
.end();
230 // The extension ran, so we need to update the ExtensionActionAPI that we no
231 // longer want to act.
232 NotifyChange(extension
);
235 void ActiveScriptController::OnRequestScriptInjectionPermission(
236 const std::string
& extension_id
,
237 UserScript::InjectionType script_type
,
239 if (!crx_file::id_util::IdIsValid(extension_id
)) {
240 NOTREACHED() << "'" << extension_id
<< "' is not a valid id.";
244 const Extension
* extension
=
245 ExtensionRegistry::Get(browser_context_
)
246 ->enabled_extensions().GetByID(extension_id
);
247 // We shouldn't allow extensions which are no longer enabled to run any
248 // scripts. Ignore the request.
252 // If the request id is -1, that signals that the content script has already
253 // ran (because this feature is not enabled). Add the extension to the list of
254 // permitted extensions (for metrics), and return immediately.
255 if (request_id
== -1) {
256 if (ShouldRecordExtension(extension
)) {
258 permitted_extensions_
.insert(extension
->id());
263 switch (RequiresUserConsentForScriptInjection(extension
, script_type
)) {
264 case PermissionsData::ACCESS_ALLOWED
:
265 PermitScriptInjection(request_id
);
267 case PermissionsData::ACCESS_WITHHELD
:
268 // This base::Unretained() is safe, because the callback is only invoked
270 RequestScriptInjection(
272 base::Bind(&ActiveScriptController::PermitScriptInjection
,
273 base::Unretained(this),
276 case PermissionsData::ACCESS_DENIED
:
277 // We should usually only get a "deny access" if the page changed (as the
278 // renderer wouldn't have requested permission if the answer was always
279 // "no"). Just let the request fizzle and die.
284 void ActiveScriptController::PermitScriptInjection(int64 request_id
) {
285 // This only sends the response to the renderer - the process of adding the
286 // extension to the list of |permitted_extensions_| is done elsewhere.
287 content::RenderViewHost
* render_view_host
=
288 web_contents()->GetRenderViewHost();
289 if (render_view_host
) {
290 render_view_host
->Send(new ExtensionMsg_PermitScriptInjection(
291 render_view_host
->GetRoutingID(), request_id
));
295 void ActiveScriptController::NotifyChange(const Extension
* extension
) {
296 ExtensionActionAPI
* extension_action_api
=
297 ExtensionActionAPI::Get(browser_context_
);
298 ExtensionAction
* extension_action
=
299 ExtensionActionManager::Get(browser_context_
)->
300 GetExtensionAction(*extension
);
301 // If the extension has an action, we need to notify that it's updated.
302 if (extension_action
) {
303 extension_action_api
->NotifyChange(
304 extension_action
, web_contents(), browser_context_
);
307 // We also notify that page actions may have changed.
308 extension_action_api
->NotifyPageActionsChanged(web_contents());
311 void ActiveScriptController::LogUMA() const {
312 UMA_HISTOGRAM_COUNTS_100(
313 "Extensions.ActiveScriptController.ShownActiveScriptsOnPage",
314 pending_requests_
.size());
316 // We only log the permitted extensions metric if the feature is enabled,
317 // because otherwise the data will be boring (100% allowed).
319 UMA_HISTOGRAM_COUNTS_100(
320 "Extensions.ActiveScriptController.PermittedExtensions",
321 permitted_extensions_
.size());
322 UMA_HISTOGRAM_COUNTS_100(
323 "Extensions.ActiveScriptController.DeniedExtensions",
324 pending_requests_
.size());
328 bool ActiveScriptController::OnMessageReceived(const IPC::Message
& message
) {
330 IPC_BEGIN_MESSAGE_MAP(ActiveScriptController
, message
)
331 IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestScriptInjectionPermission
,
332 OnRequestScriptInjectionPermission
)
333 IPC_MESSAGE_UNHANDLED(handled
= false)
334 IPC_END_MESSAGE_MAP()
338 void ActiveScriptController::DidNavigateMainFrame(
339 const content::LoadCommittedDetails
& details
,
340 const content::FrameNavigateParams
& params
) {
341 if (details
.is_in_page
)
345 permitted_extensions_
.clear();
346 pending_requests_
.clear();
349 void ActiveScriptController::OnExtensionUnloaded(
350 content::BrowserContext
* browser_context
,
351 const Extension
* extension
,
352 UnloadedExtensionInfo::Reason reason
) {
353 PendingRequestMap::iterator iter
= pending_requests_
.find(extension
->id());
354 if (iter
!= pending_requests_
.end()) {
355 pending_requests_
.erase(iter
);
356 ExtensionActionAPI::Get(browser_context_
)->
357 NotifyPageActionsChanged(web_contents());
361 } // namespace extensions