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_urls.h"
20 #include "extensions/common/features/base_feature_provider.h"
21 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
22 #include "extensions/common/permissions/permissions_data.h"
23 #include "extensions/renderer/renderer_extension_registry.h"
24 #include "extensions/renderer/v8_helpers.h"
25 #include "gin/per_context_data.h"
26 #include "third_party/WebKit/public/web/WebDataSource.h"
27 #include "third_party/WebKit/public/web/WebDocument.h"
28 #include "third_party/WebKit/public/web/WebFrame.h"
29 #include "third_party/WebKit/public/web/WebLocalFrame.h"
30 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
31 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
32 #include "third_party/WebKit/public/web/WebView.h"
33 #include "v8/include/v8.h"
35 using content::V8ValueConverter
;
37 namespace extensions
{
41 std::string
GetContextTypeDescriptionString(Feature::Context context_type
) {
42 switch (context_type
) {
43 case Feature::UNSPECIFIED_CONTEXT
:
45 case Feature::BLESSED_EXTENSION_CONTEXT
:
46 return "BLESSED_EXTENSION";
47 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
48 return "UNBLESSED_EXTENSION";
49 case Feature::CONTENT_SCRIPT_CONTEXT
:
50 return "CONTENT_SCRIPT";
51 case Feature::WEB_PAGE_CONTEXT
:
53 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
54 return "BLESSED_WEB_PAGE";
55 case Feature::WEBUI_CONTEXT
:
57 case Feature::SERVICE_WORKER_CONTEXT
:
58 return "SERVICE_WORKER";
64 static std::string
ToStringOrDefault(
65 const v8::Local
<v8::String
>& v8_string
,
66 const std::string
& dflt
) {
67 if (v8_string
.IsEmpty())
69 std::string ascii_value
= *v8::String::Utf8Value(v8_string
);
70 return ascii_value
.empty() ? dflt
: ascii_value
;
75 // A gin::Runner that delegates to its ScriptContext.
76 class ScriptContext::Runner
: public gin::Runner
{
78 explicit Runner(ScriptContext
* context
);
80 // gin::Runner overrides.
81 void Run(const std::string
& source
,
82 const std::string
& resource_name
) override
;
83 v8::Local
<v8::Value
> Call(v8::Local
<v8::Function
> function
,
84 v8::Local
<v8::Value
> receiver
,
86 v8::Local
<v8::Value
> argv
[]) override
;
87 gin::ContextHolder
* GetContextHolder() override
;
90 ScriptContext
* context_
;
93 ScriptContext::ScriptContext(const v8::Local
<v8::Context
>& v8_context
,
94 blink::WebLocalFrame
* web_frame
,
95 const Extension
* extension
,
96 Feature::Context context_type
,
97 const Extension
* effective_extension
,
98 Feature::Context effective_context_type
)
100 v8_context_(v8_context
->GetIsolate(), v8_context
),
101 web_frame_(web_frame
),
102 extension_(extension
),
103 context_type_(context_type
),
104 effective_extension_(effective_extension
),
105 effective_context_type_(effective_context_type
),
106 safe_builtins_(this),
107 isolate_(v8_context
->GetIsolate()),
108 url_(web_frame_
? GetDataSourceURLForFrame(web_frame_
) : GURL()),
109 runner_(new Runner(this)) {
110 VLOG(1) << "Created context:\n" << GetDebugString();
111 gin::PerContextData
* gin_data
= gin::PerContextData::From(v8_context
);
113 gin_data
->set_runner(runner_
.get());
116 ScriptContext::~ScriptContext() {
117 VLOG(1) << "Destroyed context for extension\n"
118 << " extension id: " << GetExtensionID() << "\n"
119 << " effective extension id: "
120 << (effective_extension_
.get() ? effective_extension_
->id() : "");
121 CHECK(!is_valid_
) << "ScriptContexts must be invalidated before destruction";
125 bool ScriptContext::IsSandboxedPage(const GURL
& url
) {
126 // TODO(kalman): This is checking the wrong thing. See comment in
127 // HasAccessOrThrowError.
128 if (url
.SchemeIs(kExtensionScheme
)) {
129 const Extension
* extension
=
130 RendererExtensionRegistry::Get()->GetByID(url
.host());
132 return SandboxedPageInfo::IsSandboxedPage(extension
, url
.path());
138 void ScriptContext::Invalidate() {
139 DCHECK(thread_checker_
.CalledOnValidThread());
143 // TODO(kalman): Make ModuleSystem use AddInvalidationObserver.
144 // Ownership graph is a bit weird here.
146 module_system_
->Invalidate();
148 // Swap |invalidate_observers_| to a local variable to clear it, and to make
149 // sure it's not mutated as we iterate.
150 std::vector
<base::Closure
> observers
;
151 observers
.swap(invalidate_observers_
);
152 for (const base::Closure
& observer
: observers
) {
155 DCHECK(invalidate_observers_
.empty())
156 << "Invalidation observers cannot be added during invalidation";
162 void ScriptContext::AddInvalidationObserver(const base::Closure
& observer
) {
163 DCHECK(thread_checker_
.CalledOnValidThread());
164 invalidate_observers_
.push_back(observer
);
167 const std::string
& ScriptContext::GetExtensionID() const {
168 DCHECK(thread_checker_
.CalledOnValidThread());
169 return extension_
.get() ? extension_
->id() : base::EmptyString();
172 content::RenderFrame
* ScriptContext::GetRenderFrame() const {
173 DCHECK(thread_checker_
.CalledOnValidThread());
175 return content::RenderFrame::FromWebFrame(web_frame_
);
179 v8::Local
<v8::Value
> ScriptContext::CallFunction(
180 const v8::Local
<v8::Function
>& function
,
182 v8::Local
<v8::Value
> argv
[]) const {
183 DCHECK(thread_checker_
.CalledOnValidThread());
184 v8::EscapableHandleScope
handle_scope(isolate());
185 v8::Context::Scope
scope(v8_context());
187 blink::WebScopedMicrotaskSuppression suppression
;
189 return handle_scope
.Escape(
190 v8::Local
<v8::Primitive
>(v8::Undefined(isolate())));
193 v8::Local
<v8::Object
> global
= v8_context()->Global();
195 return handle_scope
.Escape(function
->Call(global
, argc
, argv
));
196 return handle_scope
.Escape(
197 v8::Local
<v8::Value
>(web_frame_
->callFunctionEvenIfScriptDisabled(
198 function
, global
, argc
, argv
)));
201 v8::Local
<v8::Value
> ScriptContext::CallFunction(
202 const v8::Local
<v8::Function
>& function
) const {
203 DCHECK(thread_checker_
.CalledOnValidThread());
204 return CallFunction(function
, 0, nullptr);
207 Feature::Availability
ScriptContext::GetAvailability(
208 const std::string
& api_name
) {
209 DCHECK(thread_checker_
.CalledOnValidThread());
210 // Hack: Hosted apps should have the availability of messaging APIs based on
211 // the URL of the page (which might have access depending on some extension
212 // with externally_connectable), not whether the app has access to messaging
214 const Extension
* extension
= extension_
.get();
215 if (extension
&& extension
->is_hosted_app() &&
216 (api_name
== "runtime.connect" || api_name
== "runtime.sendMessage")) {
219 return ExtensionAPI::GetSharedInstance()->IsAvailable(api_name
, extension
,
220 context_type_
, url());
223 void ScriptContext::DispatchEvent(const char* event_name
,
224 v8::Local
<v8::Array
> args
) const {
225 DCHECK(thread_checker_
.CalledOnValidThread());
226 v8::HandleScope
handle_scope(isolate());
227 v8::Context::Scope
context_scope(v8_context());
229 v8::Local
<v8::Value
> argv
[] = {v8::String::NewFromUtf8(isolate(), event_name
),
231 module_system_
->CallModuleMethod(
232 kEventBindings
, "dispatchEvent", arraysize(argv
), argv
);
235 void ScriptContext::DispatchOnUnloadEvent() {
236 DCHECK(thread_checker_
.CalledOnValidThread());
237 v8::HandleScope
handle_scope(isolate());
238 v8::Context::Scope
context_scope(v8_context());
239 module_system_
->CallModuleMethod("unload_event", "dispatch");
242 std::string
ScriptContext::GetContextTypeDescription() const {
243 DCHECK(thread_checker_
.CalledOnValidThread());
244 return GetContextTypeDescriptionString(context_type_
);
247 std::string
ScriptContext::GetEffectiveContextTypeDescription() const {
248 DCHECK(thread_checker_
.CalledOnValidThread());
249 return GetContextTypeDescriptionString(effective_context_type_
);
252 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature
& api
) {
253 DCHECK(thread_checker_
.CalledOnValidThread());
254 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
255 api
, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
259 GURL
ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame
* frame
) {
260 // Normally we would use frame->document().url() to determine the document's
261 // URL, but to decide whether to inject a content script, we use the URL from
262 // the data source. This "quirk" helps prevents content scripts from
263 // inadvertently adding DOM elements to the compose iframe in Gmail because
264 // the compose iframe's dataSource URL is about:blank, but the document URL
265 // changes to match the parent document after Gmail document.writes into
266 // it to create the editor.
267 // http://code.google.com/p/chromium/issues/detail?id=86742
268 blink::WebDataSource
* data_source
= frame
->provisionalDataSource()
269 ? frame
->provisionalDataSource()
270 : frame
->dataSource();
271 return data_source
? GURL(data_source
->request().url()) : GURL();
275 GURL
ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame
* frame
,
276 const GURL
& document_url
,
277 bool match_about_blank
) {
278 // Common scenario. If |match_about_blank| is false (as is the case in most
279 // extensions), or if the frame is not an about:-page, just return
280 // |document_url| (supposedly the URL of the frame).
281 if (!match_about_blank
|| !document_url
.SchemeIs(url::kAboutScheme
))
284 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
285 // origin from their parent frame/window. So, traverse the frame/window
286 // hierarchy to find the closest non-about:-page and return its URL.
287 const blink::WebFrame
* parent
= frame
;
289 parent
= parent
->parent() ? parent
->parent() : parent
->opener();
290 } while (parent
!= NULL
&& !parent
->document().isNull() &&
291 GURL(parent
->document().url()).SchemeIs(url::kAboutScheme
));
293 if (parent
&& !parent
->document().isNull()) {
294 // Only return the parent URL if the frame can access it.
295 const blink::WebDocument
& parent_document
= parent
->document();
296 if (frame
->document().securityOrigin().canAccess(
297 parent_document
.securityOrigin()))
298 return parent_document
.url();
303 ScriptContext
* ScriptContext::GetContext() {
304 DCHECK(thread_checker_
.CalledOnValidThread());
308 void ScriptContext::OnResponseReceived(const std::string
& name
,
311 const base::ListValue
& response
,
312 const std::string
& error
) {
313 DCHECK(thread_checker_
.CalledOnValidThread());
314 v8::HandleScope
handle_scope(isolate());
316 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
317 v8::Local
<v8::Value
> argv
[] = {
318 v8::Integer::New(isolate(), request_id
),
319 v8::String::NewFromUtf8(isolate(), name
.c_str()),
320 v8::Boolean::New(isolate(), success
),
321 converter
->ToV8Value(&response
,
322 v8::Local
<v8::Context
>::New(isolate(), v8_context_
)),
323 v8::String::NewFromUtf8(isolate(), error
.c_str())};
325 v8::Local
<v8::Value
> retval
= module_system()->CallModuleMethod(
326 "sendRequest", "handleResponse", arraysize(argv
), argv
);
328 // In debug, the js will validate the callback parameters and return a
329 // string if a validation error has occured.
330 DCHECK(retval
.IsEmpty() || retval
->IsUndefined())
331 << *v8::String::Utf8Value(retval
);
334 bool ScriptContext::HasAPIPermission(APIPermission::ID permission
) const {
335 DCHECK(thread_checker_
.CalledOnValidThread());
336 if (effective_extension_
.get()) {
337 return effective_extension_
->permissions_data()->HasAPIPermission(
340 if (context_type() == Feature::WEB_PAGE_CONTEXT
) {
341 // Only web page contexts may be granted content capabilities. Other
342 // contexts are either privileged WebUI or extensions with their own set of
344 if (content_capabilities_
.find(permission
) != content_capabilities_
.end())
350 bool ScriptContext::HasAccessOrThrowError(const std::string
& name
) {
351 DCHECK(thread_checker_
.CalledOnValidThread());
352 // Theoretically[1] we could end up with bindings being injected into
353 // sandboxed frames, for example content scripts. Don't let them execute API
356 // In any case, this check is silly. The frame's document's security origin
357 // already tells us if it's sandboxed. The only problem is that until
358 // crbug.com/466373 is fixed, we don't know the security origin up-front and
359 // may not know it here, either.
361 // [1] citation needed. This ScriptContext should already be in a state that
362 // doesn't allow this, from ScriptContextSet::ClassifyJavaScriptContext.
364 SandboxedPageInfo::IsSandboxedPage(extension(), url_
.path())) {
365 static const char kMessage
[] =
366 "%s cannot be used within a sandboxed frame.";
367 std::string error_msg
= base::StringPrintf(kMessage
, name
.c_str());
368 isolate()->ThrowException(v8::Exception::Error(
369 v8::String::NewFromUtf8(isolate(), error_msg
.c_str())));
373 Feature::Availability availability
= GetAvailability(name
);
374 if (!availability
.is_available()) {
375 isolate()->ThrowException(v8::Exception::Error(
376 v8::String::NewFromUtf8(isolate(), availability
.message().c_str())));
383 std::string
ScriptContext::GetDebugString() const {
384 DCHECK(thread_checker_
.CalledOnValidThread());
385 return base::StringPrintf(
386 " extension id: %s\n"
389 " context_type: %s\n"
390 " effective extension id: %s\n"
391 " effective context type: %s",
392 extension_
.get() ? extension_
->id().c_str() : "(none)", web_frame_
,
393 url_
.spec().c_str(), GetContextTypeDescription().c_str(),
394 effective_extension_
.get() ? effective_extension_
->id().c_str()
396 GetEffectiveContextTypeDescription().c_str());
399 std::string
ScriptContext::GetStackTraceAsString() const {
400 DCHECK(thread_checker_
.CalledOnValidThread());
401 v8::Local
<v8::StackTrace
> stack_trace
=
402 v8::StackTrace::CurrentStackTrace(isolate(), 10);
403 if (stack_trace
.IsEmpty() || stack_trace
->GetFrameCount() <= 0) {
404 return " <no stack trace>";
407 for (int i
= 0; i
< stack_trace
->GetFrameCount(); ++i
) {
408 v8::Local
<v8::StackFrame
> frame
= stack_trace
->GetFrame(i
);
409 CHECK(!frame
.IsEmpty());
410 result
+= base::StringPrintf(
411 "\n at %s (%s:%d:%d)",
412 ToStringOrDefault(frame
->GetFunctionName(), "<anonymous>").c_str(),
413 ToStringOrDefault(frame
->GetScriptName(), "<anonymous>").c_str(),
414 frame
->GetLineNumber(), frame
->GetColumn());
419 v8::Local
<v8::Value
> ScriptContext::RunScript(
420 v8::Local
<v8::String
> name
,
421 v8::Local
<v8::String
> code
,
422 const RunScriptExceptionHandler
& exception_handler
) {
423 DCHECK(thread_checker_
.CalledOnValidThread());
424 v8::EscapableHandleScope
handle_scope(isolate());
425 v8::Context::Scope
context_scope(v8_context());
427 // Prepend extensions:: to |name| so that internal code can be differentiated
428 // from external code in stack traces. This has no effect on behaviour.
429 std::string internal_name
=
430 base::StringPrintf("extensions::%s", *v8::String::Utf8Value(name
));
432 if (internal_name
.size() >= v8::String::kMaxLength
) {
433 NOTREACHED() << "internal_name is too long.";
434 return v8::Undefined(isolate());
437 blink::WebScopedMicrotaskSuppression suppression
;
438 v8::TryCatch
try_catch(isolate());
439 try_catch
.SetCaptureMessage(true);
440 v8::ScriptOrigin
origin(
441 v8_helpers::ToV8StringUnsafe(isolate(), internal_name
.c_str()));
442 v8::Local
<v8::Script
> script
;
443 if (!v8::Script::Compile(v8_context(), code
, &origin
).ToLocal(&script
)) {
444 exception_handler
.Run(try_catch
);
445 return v8::Undefined(isolate());
448 v8::Local
<v8::Value
> result
;
449 if (!script
->Run(v8_context()).ToLocal(&result
)) {
450 exception_handler
.Run(try_catch
);
451 return v8::Undefined(isolate());
454 return handle_scope
.Escape(result
);
457 ScriptContext::Runner::Runner(ScriptContext
* context
) : context_(context
) {
460 void ScriptContext::Runner::Run(const std::string
& source
,
461 const std::string
& resource_name
) {
462 context_
->module_system()->RunString(source
, resource_name
);
465 v8::Local
<v8::Value
> ScriptContext::Runner::Call(
466 v8::Local
<v8::Function
> function
,
467 v8::Local
<v8::Value
> receiver
,
469 v8::Local
<v8::Value
> argv
[]) {
470 return context_
->CallFunction(function
, argc
, argv
);
473 gin::ContextHolder
* ScriptContext::Runner::GetContextHolder() {
474 v8::HandleScope
handle_scope(context_
->isolate());
475 return gin::PerContextData::From(context_
->v8_context())->context_holder();
478 } // namespace extensions