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/extension_action.h"
14 #include "chrome/browser/extensions/extension_util.h"
15 #include "chrome/browser/extensions/location_bar_controller.h"
16 #include "chrome/browser/extensions/tab_helper.h"
17 #include "chrome/browser/sessions/session_id.h"
18 #include "chrome/common/extensions/api/extension_action/action_info.h"
19 #include "content/public/browser/navigation_controller.h"
20 #include "content/public/browser/navigation_entry.h"
21 #include "content/public/browser/render_view_host.h"
22 #include "content/public/browser/web_contents.h"
23 #include "extensions/browser/extension_registry.h"
24 #include "extensions/common/extension.h"
25 #include "extensions/common/extension_messages.h"
26 #include "extensions/common/extension_set.h"
27 #include "extensions/common/feature_switch.h"
28 #include "extensions/common/manifest.h"
29 #include "extensions/common/permissions/permissions_data.h"
30 #include "ipc/ipc_message_macros.h"
32 namespace extensions
{
36 // Returns true if the extension should be regarded as a "permitted" extension
37 // for the case of metrics. We need this because we only actually withhold
38 // permissions if the switch is enabled, but want to record metrics in all
40 // "ExtensionWouldHaveHadHostPermissionsWithheldIfSwitchWasOn()" would be
41 // more accurate, but too long.
42 bool ShouldRecordExtension(const Extension
* extension
) {
43 return extension
->ShouldDisplayInExtensionSettings() &&
44 !Manifest::IsPolicyLocation(extension
->location()) &&
45 !Manifest::IsComponentLocation(extension
->location()) &&
46 !PermissionsData::CanExecuteScriptEverywhere(extension
) &&
47 extension
->permissions_data()
48 ->active_permissions()
49 ->ShouldWarnAllHosts();
54 ActiveScriptController::ActiveScriptController(
55 content::WebContents
* web_contents
)
56 : content::WebContentsObserver(web_contents
),
57 enabled_(FeatureSwitch::scripts_require_action()->IsEnabled()) {
61 ActiveScriptController::~ActiveScriptController() {
66 ActiveScriptController
* ActiveScriptController::GetForWebContents(
67 content::WebContents
* web_contents
) {
70 TabHelper
* tab_helper
= TabHelper::FromWebContents(web_contents
);
73 LocationBarController
* location_bar_controller
=
74 tab_helper
->location_bar_controller();
75 // This should never be NULL.
76 DCHECK(location_bar_controller
);
77 return location_bar_controller
->active_script_controller();
80 void ActiveScriptController::OnActiveTabPermissionGranted(
81 const Extension
* extension
) {
82 RunPendingForExtension(extension
);
85 void ActiveScriptController::OnAdInjectionDetected(
86 const std::set
<std::string
>& ad_injectors
) {
87 // We're only interested in data if there are ad injectors detected.
88 if (ad_injectors
.empty())
91 size_t num_preventable_ad_injectors
=
92 base::STLSetIntersection
<std::set
<std::string
> >(
93 ad_injectors
, permitted_extensions_
).size();
95 UMA_HISTOGRAM_COUNTS_100(
96 "Extensions.ActiveScriptController.PreventableAdInjectors",
97 num_preventable_ad_injectors
);
98 UMA_HISTOGRAM_COUNTS_100(
99 "Extensions.ActiveScriptController.UnpreventableAdInjectors",
100 ad_injectors
.size() - num_preventable_ad_injectors
);
103 ExtensionAction
* ActiveScriptController::GetActionForExtension(
104 const Extension
* extension
) {
105 if (!enabled_
|| pending_requests_
.count(extension
->id()) == 0)
106 return NULL
; // No action for this extension.
108 ActiveScriptMap::iterator existing
=
109 active_script_actions_
.find(extension
->id());
110 if (existing
!= active_script_actions_
.end())
111 return existing
->second
.get();
113 linked_ptr
<ExtensionAction
> action(new ExtensionAction(
114 extension
->id(), ActionInfo::TYPE_PAGE
, ActionInfo()));
115 action
->SetTitle(ExtensionAction::kDefaultTabId
, extension
->name());
116 action
->SetIsVisible(ExtensionAction::kDefaultTabId
, true);
118 const ActionInfo
* action_info
= ActionInfo::GetPageActionInfo(extension
);
120 action_info
= ActionInfo::GetBrowserActionInfo(extension
);
122 if (action_info
&& !action_info
->default_icon
.empty()) {
123 action
->set_default_icon(
124 make_scoped_ptr(new ExtensionIconSet(action_info
->default_icon
)));
127 active_script_actions_
[extension
->id()] = action
;
131 LocationBarController::Action
ActiveScriptController::OnClicked(
132 const Extension
* extension
) {
133 DCHECK(ContainsKey(pending_requests_
, extension
->id()));
134 RunPendingForExtension(extension
);
135 return LocationBarController::ACTION_NONE
;
138 void ActiveScriptController::OnNavigated() {
140 permitted_extensions_
.clear();
141 pending_requests_
.clear();
144 void ActiveScriptController::OnExtensionUnloaded(const Extension
* extension
) {
145 PendingRequestMap::iterator iter
= pending_requests_
.find(extension
->id());
146 if (iter
!= pending_requests_
.end())
147 pending_requests_
.erase(iter
);
150 PermissionsData::AccessType
151 ActiveScriptController::RequiresUserConsentForScriptInjection(
152 const Extension
* extension
,
153 UserScript::InjectionType type
) {
156 // If the feature is not enabled, we automatically allow all extensions to
159 permitted_extensions_
.insert(extension
->id());
161 // Allow the extension if it's been explicitly granted permission.
162 if (permitted_extensions_
.count(extension
->id()) > 0)
163 return PermissionsData::ACCESS_ALLOWED
;
165 GURL url
= web_contents()->GetVisibleURL();
166 int tab_id
= SessionID::IdForTab(web_contents());
168 case UserScript::CONTENT_SCRIPT
:
169 return extension
->permissions_data()->GetContentScriptAccess(
170 extension
, url
, url
, tab_id
, -1, NULL
);
171 case UserScript::PROGRAMMATIC_SCRIPT
:
172 return extension
->permissions_data()->GetPageAccess(
173 extension
, url
, url
, tab_id
, -1, NULL
);
177 return PermissionsData::ACCESS_DENIED
;
180 void ActiveScriptController::RequestScriptInjection(
181 const Extension
* extension
,
182 const base::Closure
& callback
) {
184 PendingRequestList
& list
= pending_requests_
[extension
->id()];
185 list
.push_back(callback
);
187 // If this was the first entry, notify the location bar that there's a new
189 if (list
.size() == 1u)
190 LocationBarController::NotifyChange(web_contents());
193 void ActiveScriptController::RunPendingForExtension(
194 const Extension
* extension
) {
197 content::NavigationEntry
* visible_entry
=
198 web_contents()->GetController().GetVisibleEntry();
199 // Refuse to run if there's no visible entry, because we have no idea of
200 // determining if it's the proper page. This should rarely, if ever, happen.
204 // We add this to the list of permitted extensions and erase pending entries
205 // *before* running them to guard against the crazy case where running the
206 // callbacks adds more entries.
207 permitted_extensions_
.insert(extension
->id());
209 PendingRequestMap::iterator iter
= pending_requests_
.find(extension
->id());
210 if (iter
== pending_requests_
.end())
213 PendingRequestList requests
;
214 iter
->second
.swap(requests
);
215 pending_requests_
.erase(extension
->id());
217 // Clicking to run the extension counts as granting it permission to run on
219 // The extension may already have active tab at this point, but granting
220 // it twice is essentially a no-op.
221 TabHelper::FromWebContents(web_contents())->
222 active_tab_permission_granter()->GrantIfRequested(extension
);
224 // Run all pending injections for the given extension.
225 for (PendingRequestList::iterator request
= requests
.begin();
226 request
!= requests
.end();
231 // Inform the location bar that the action is now gone.
232 LocationBarController::NotifyChange(web_contents());
235 void ActiveScriptController::OnRequestScriptInjectionPermission(
236 const std::string
& extension_id
,
237 UserScript::InjectionType script_type
,
239 if (!Extension::IdIsValid(extension_id
)) {
240 NOTREACHED() << "'" << extension_id
<< "' is not a valid id.";
244 const Extension
* extension
=
245 ExtensionRegistry::Get(web_contents()->GetBrowserContext())
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 bool ActiveScriptController::OnMessageReceived(const IPC::Message
& message
) {
297 IPC_BEGIN_MESSAGE_MAP(ActiveScriptController
, message
)
298 IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestScriptInjectionPermission
,
299 OnRequestScriptInjectionPermission
)
300 IPC_MESSAGE_UNHANDLED(handled
= false)
301 IPC_END_MESSAGE_MAP()
305 void ActiveScriptController::LogUMA() const {
306 UMA_HISTOGRAM_COUNTS_100(
307 "Extensions.ActiveScriptController.ShownActiveScriptsOnPage",
308 pending_requests_
.size());
310 // We only log the permitted extensions metric if the feature is enabled,
311 // because otherwise the data will be boring (100% allowed).
313 UMA_HISTOGRAM_COUNTS_100(
314 "Extensions.ActiveScriptController.PermittedExtensions",
315 permitted_extensions_
.size());
316 UMA_HISTOGRAM_COUNTS_100(
317 "Extensions.ActiveScriptController.DeniedExtensions",
318 pending_requests_
.size());
322 } // namespace extensions