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 "extensions/renderer/script_context.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/values.h"
13 #include "content/public/child/v8_value_converter.h"
14 #include "content/public/common/url_constants.h"
15 #include "content/public/renderer/render_frame.h"
16 #include "extensions/common/constants.h"
17 #include "extensions/common/extension.h"
18 #include "extensions/common/extension_api.h"
19 #include "extensions/common/extension_set.h"
20 #include "extensions/common/extension_urls.h"
21 #include "extensions/common/features/base_feature_provider.h"
22 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
23 #include "extensions/common/permissions/permissions_data.h"
24 #include "gin/per_context_data.h"
25 #include "third_party/WebKit/public/web/WebDataSource.h"
26 #include "third_party/WebKit/public/web/WebDocument.h"
27 #include "third_party/WebKit/public/web/WebFrame.h"
28 #include "third_party/WebKit/public/web/WebLocalFrame.h"
29 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
30 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
31 #include "third_party/WebKit/public/web/WebView.h"
32 #include "v8/include/v8.h"
34 using content::V8ValueConverter
;
36 namespace extensions
{
40 std::string
GetContextTypeDescriptionString(Feature::Context context_type
) {
41 switch (context_type
) {
42 case Feature::UNSPECIFIED_CONTEXT
:
44 case Feature::BLESSED_EXTENSION_CONTEXT
:
45 return "BLESSED_EXTENSION";
46 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
47 return "UNBLESSED_EXTENSION";
48 case Feature::CONTENT_SCRIPT_CONTEXT
:
49 return "CONTENT_SCRIPT";
50 case Feature::WEB_PAGE_CONTEXT
:
52 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
53 return "BLESSED_WEB_PAGE";
54 case Feature::WEBUI_CONTEXT
:
63 // A gin::Runner that delegates to its ScriptContext.
64 class ScriptContext::Runner
: public gin::Runner
{
66 explicit Runner(ScriptContext
* context
);
68 // gin::Runner overrides.
69 void Run(const std::string
& source
,
70 const std::string
& resource_name
) override
;
71 v8::Local
<v8::Value
> Call(v8::Local
<v8::Function
> function
,
72 v8::Local
<v8::Value
> receiver
,
74 v8::Local
<v8::Value
> argv
[]) override
;
75 gin::ContextHolder
* GetContextHolder() override
;
78 ScriptContext
* context_
;
81 ScriptContext::ScriptContext(const v8::Local
<v8::Context
>& v8_context
,
82 blink::WebLocalFrame
* web_frame
,
83 const Extension
* extension
,
84 Feature::Context context_type
,
85 const Extension
* effective_extension
,
86 Feature::Context effective_context_type
)
88 v8_context_(v8_context
->GetIsolate(), v8_context
),
89 web_frame_(web_frame
),
90 extension_(extension
),
91 context_type_(context_type
),
92 effective_extension_(effective_extension
),
93 effective_context_type_(effective_context_type
),
95 isolate_(v8_context
->GetIsolate()),
96 url_(web_frame_
? GetDataSourceURLForFrame(web_frame_
) : GURL()),
97 runner_(new Runner(this)) {
98 VLOG(1) << "Created context:\n" << GetDebugString();
99 gin::PerContextData
* gin_data
= gin::PerContextData::From(v8_context
);
100 CHECK(gin_data
); // may fail if the v8::Context hasn't been registered yet
101 gin_data
->set_runner(runner_
.get());
104 ScriptContext::~ScriptContext() {
105 VLOG(1) << "Destroyed context for extension\n"
106 << " extension id: " << GetExtensionID() << "\n"
107 << " effective extension id: "
108 << (effective_extension_
.get() ? effective_extension_
->id() : "");
109 CHECK(!is_valid_
) << "ScriptContexts must be invalidated before destruction";
113 bool ScriptContext::IsSandboxedPage(const ExtensionSet
& extensions
,
115 // TODO(kalman): This is checking the wrong thing. See comment in
116 // HasAccessOrThrowError.
117 if (url
.SchemeIs(kExtensionScheme
)) {
118 const Extension
* extension
= extensions
.GetByID(url
.host());
120 return SandboxedPageInfo::IsSandboxedPage(extension
, url
.path());
126 void ScriptContext::Invalidate() {
130 // TODO(kalman): Make ModuleSystem use AddInvalidationObserver.
131 // Ownership graph is a bit weird here.
133 module_system_
->Invalidate();
135 // Swap |invalidate_observers_| to a local variable to clear it, and to make
136 // sure it's not mutated as we iterate.
137 std::vector
<base::Closure
> observers
;
138 observers
.swap(invalidate_observers_
);
139 for (const base::Closure
& observer
: observers
) {
142 DCHECK(invalidate_observers_
.empty())
143 << "Invalidation observers cannot be added during invalidation";
149 void ScriptContext::AddInvalidationObserver(const base::Closure
& observer
) {
150 invalidate_observers_
.push_back(observer
);
153 const std::string
& ScriptContext::GetExtensionID() const {
154 return extension_
.get() ? extension_
->id() : base::EmptyString();
157 content::RenderFrame
* ScriptContext::GetRenderFrame() const {
159 return content::RenderFrame::FromWebFrame(web_frame_
);
163 v8::Local
<v8::Value
> ScriptContext::CallFunction(
164 const v8::Local
<v8::Function
>& function
,
166 v8::Local
<v8::Value
> argv
[]) const {
167 v8::EscapableHandleScope
handle_scope(isolate());
168 v8::Context::Scope
scope(v8_context());
170 blink::WebScopedMicrotaskSuppression suppression
;
172 return handle_scope
.Escape(
173 v8::Local
<v8::Primitive
>(v8::Undefined(isolate())));
176 v8::Local
<v8::Object
> global
= v8_context()->Global();
178 return handle_scope
.Escape(function
->Call(global
, argc
, argv
));
179 return handle_scope
.Escape(
180 v8::Local
<v8::Value
>(web_frame_
->callFunctionEvenIfScriptDisabled(
181 function
, global
, argc
, argv
)));
184 v8::Local
<v8::Value
> ScriptContext::CallFunction(
185 const v8::Local
<v8::Function
>& function
) const {
186 return CallFunction(function
, 0, nullptr);
189 Feature::Availability
ScriptContext::GetAvailability(
190 const std::string
& api_name
) {
191 // Hack: Hosted apps should have the availability of messaging APIs based on
192 // the URL of the page (which might have access depending on some extension
193 // with externally_connectable), not whether the app has access to messaging
195 const Extension
* extension
= extension_
.get();
196 if (extension
&& extension
->is_hosted_app() &&
197 (api_name
== "runtime.connect" || api_name
== "runtime.sendMessage")) {
200 return ExtensionAPI::GetSharedInstance()->IsAvailable(
201 api_name
, extension
, context_type_
, GetURL());
204 void ScriptContext::DispatchEvent(const char* event_name
,
205 v8::Local
<v8::Array
> args
) const {
206 v8::HandleScope
handle_scope(isolate());
207 v8::Context::Scope
context_scope(v8_context());
209 v8::Local
<v8::Value
> argv
[] = {v8::String::NewFromUtf8(isolate(), event_name
),
211 module_system_
->CallModuleMethod(
212 kEventBindings
, "dispatchEvent", arraysize(argv
), argv
);
215 void ScriptContext::DispatchOnUnloadEvent() {
216 v8::HandleScope
handle_scope(isolate());
217 v8::Context::Scope
context_scope(v8_context());
218 module_system_
->CallModuleMethod("unload_event", "dispatch");
221 std::string
ScriptContext::GetContextTypeDescription() const {
222 return GetContextTypeDescriptionString(context_type_
);
225 std::string
ScriptContext::GetEffectiveContextTypeDescription() const {
226 return GetContextTypeDescriptionString(effective_context_type_
);
229 GURL
ScriptContext::GetURL() const {
233 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature
& api
) {
234 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
235 api
, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
239 GURL
ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame
* frame
) {
240 // Normally we would use frame->document().url() to determine the document's
241 // URL, but to decide whether to inject a content script, we use the URL from
242 // the data source. This "quirk" helps prevents content scripts from
243 // inadvertently adding DOM elements to the compose iframe in Gmail because
244 // the compose iframe's dataSource URL is about:blank, but the document URL
245 // changes to match the parent document after Gmail document.writes into
246 // it to create the editor.
247 // http://code.google.com/p/chromium/issues/detail?id=86742
248 blink::WebDataSource
* data_source
= frame
->provisionalDataSource()
249 ? frame
->provisionalDataSource()
250 : frame
->dataSource();
251 return data_source
? GURL(data_source
->request().url()) : GURL();
255 GURL
ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame
* frame
,
256 const GURL
& document_url
,
257 bool match_about_blank
) {
258 // Common scenario. If |match_about_blank| is false (as is the case in most
259 // extensions), or if the frame is not an about:-page, just return
260 // |document_url| (supposedly the URL of the frame).
261 if (!match_about_blank
|| !document_url
.SchemeIs(url::kAboutScheme
))
264 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
265 // origin from their parent frame/window. So, traverse the frame/window
266 // hierarchy to find the closest non-about:-page and return its URL.
267 const blink::WebFrame
* parent
= frame
;
269 parent
= parent
->parent() ? parent
->parent() : parent
->opener();
270 } while (parent
!= NULL
&& !parent
->document().isNull() &&
271 GURL(parent
->document().url()).SchemeIs(url::kAboutScheme
));
273 if (parent
&& !parent
->document().isNull()) {
274 // Only return the parent URL if the frame can access it.
275 const blink::WebDocument
& parent_document
= parent
->document();
276 if (frame
->document().securityOrigin().canAccess(
277 parent_document
.securityOrigin()))
278 return parent_document
.url();
283 ScriptContext
* ScriptContext::GetContext() { return this; }
285 void ScriptContext::OnResponseReceived(const std::string
& name
,
288 const base::ListValue
& response
,
289 const std::string
& error
) {
290 v8::HandleScope
handle_scope(isolate());
292 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
293 v8::Local
<v8::Value
> argv
[] = {
294 v8::Integer::New(isolate(), request_id
),
295 v8::String::NewFromUtf8(isolate(), name
.c_str()),
296 v8::Boolean::New(isolate(), success
),
297 converter
->ToV8Value(&response
,
298 v8::Local
<v8::Context
>::New(isolate(), v8_context_
)),
299 v8::String::NewFromUtf8(isolate(), error
.c_str())};
301 v8::Local
<v8::Value
> retval
= module_system()->CallModuleMethod(
302 "sendRequest", "handleResponse", arraysize(argv
), argv
);
304 // In debug, the js will validate the callback parameters and return a
305 // string if a validation error has occured.
306 DCHECK(retval
.IsEmpty() || retval
->IsUndefined())
307 << *v8::String::Utf8Value(retval
);
310 void ScriptContext::SetContentCapabilities(
311 const APIPermissionSet
& permissions
) {
312 content_capabilities_
= permissions
;
315 bool ScriptContext::HasAPIPermission(APIPermission::ID permission
) const {
316 if (effective_extension_
.get()) {
317 return effective_extension_
->permissions_data()->HasAPIPermission(
319 } else if (context_type() == Feature::WEB_PAGE_CONTEXT
) {
320 // Only web page contexts may be granted content capabilities. Other
321 // contexts are either privileged WebUI or extensions with their own set of
323 if (content_capabilities_
.find(permission
) != content_capabilities_
.end())
329 bool ScriptContext::HasAccessOrThrowError(const std::string
& name
) {
330 // Theoretically[1] we could end up with bindings being injected into
331 // sandboxed frames, for example content scripts. Don't let them execute API
334 // In any case, this check is silly. The frame's document's security origin
335 // already tells us if it's sandboxed. The only problem is that until
336 // crbug.com/466373 is fixed, we don't know the security origin up-front and
337 // may not know it here, either.
339 // [1] citation needed. This ScriptContext should already be in a state that
340 // doesn't allow this, from ScriptContextSet::ClassifyJavaScriptContext.
342 SandboxedPageInfo::IsSandboxedPage(extension(), url_
.path())) {
343 static const char kMessage
[] =
344 "%s cannot be used within a sandboxed frame.";
345 std::string error_msg
= base::StringPrintf(kMessage
, name
.c_str());
346 isolate()->ThrowException(v8::Exception::Error(
347 v8::String::NewFromUtf8(isolate(), error_msg
.c_str())));
351 Feature::Availability availability
= GetAvailability(name
);
352 if (!availability
.is_available()) {
353 isolate()->ThrowException(v8::Exception::Error(
354 v8::String::NewFromUtf8(isolate(), availability
.message().c_str())));
361 std::string
ScriptContext::GetDebugString() const {
362 return base::StringPrintf(
363 " extension id: %s\n"
366 " context_type: %s\n"
367 " effective extension id: %s\n"
368 " effective context type: %s",
369 extension_
.get() ? extension_
->id().c_str() : "(none)", web_frame_
,
370 GetURL().spec().c_str(), GetContextTypeDescription().c_str(),
371 effective_extension_
.get() ? effective_extension_
->id().c_str()
373 GetEffectiveContextTypeDescription().c_str());
376 ScriptContext::Runner::Runner(ScriptContext
* context
) : context_(context
) {
379 void ScriptContext::Runner::Run(const std::string
& source
,
380 const std::string
& resource_name
) {
381 context_
->module_system()->RunString(source
, resource_name
);
384 v8::Local
<v8::Value
> ScriptContext::Runner::Call(
385 v8::Local
<v8::Function
> function
,
386 v8::Local
<v8::Value
> receiver
,
388 v8::Local
<v8::Value
> argv
[]) {
389 return context_
->CallFunction(function
, argc
, argv
);
392 gin::ContextHolder
* ScriptContext::Runner::GetContextHolder() {
393 v8::HandleScope
handle_scope(context_
->isolate());
394 return gin::PerContextData::From(context_
->v8_context())->context_holder();
397 } // namespace extensions