script_injection.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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.
  4. #include "extensions/renderer/script_injection.h"
  5. #include <map>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/feature_list.h"
  9. #include "base/lazy_instance.h"
  10. #include "base/metrics/histogram_macros.h"
  11. #include "base/time/time.h"
  12. #include "base/timer/elapsed_timer.h"
  13. #include "base/trace_event/typed_macros.h"
  14. #include "base/tracing/protos/chrome_track_event.pbzero.h"
  15. #include "base/values.h"
  16. #include "content/public/renderer/render_frame.h"
  17. #include "content/public/renderer/render_thread.h"
  18. #include "content/public/renderer/v8_value_converter.h"
  19. #include "extensions/common/extension_features.h"
  20. #include "extensions/common/extension_messages.h"
  21. #include "extensions/common/identifiability_metrics.h"
  22. #include "extensions/common/mojom/host_id.mojom.h"
  23. #include "extensions/common/mojom/injection_type.mojom-shared.h"
  24. #include "extensions/renderer/dom_activity_logger.h"
  25. #include "extensions/renderer/extension_frame_helper.h"
  26. #include "extensions/renderer/extensions_renderer_client.h"
  27. #include "extensions/renderer/scripts_run_info.h"
  28. #include "extensions/renderer/trace_util.h"
  29. #include "services/metrics/public/cpp/ukm_source_id.h"
  30. #include "third_party/blink/public/platform/web_isolated_world_info.h"
  31. #include "third_party/blink/public/platform/web_security_origin.h"
  32. #include "third_party/blink/public/platform/web_string.h"
  33. #include "third_party/blink/public/web/web_document.h"
  34. #include "third_party/blink/public/web/web_local_frame.h"
  35. #include "third_party/blink/public/web/web_script_execution_callback.h"
  36. #include "third_party/blink/public/web/web_script_source.h"
  37. #include "url/gurl.h"
  38. using perfetto::protos::pbzero::ChromeTrackEvent;
  39. namespace extensions {
  40. namespace {
  41. using IsolatedWorldMap = std::map<std::string, int>;
  42. base::LazyInstance<IsolatedWorldMap>::DestructorAtExit g_isolated_worlds =
  43. LAZY_INSTANCE_INITIALIZER;
  44. const int64_t kInvalidRequestId = -1;
  45. // The id of the next pending injection.
  46. int64_t g_next_pending_id = 0;
  47. // Gets the isolated world ID to use for the given |injection_host|. If no
  48. // isolated world has been created for that |injection_host| one will be created
  49. // and initialized.
  50. int GetIsolatedWorldIdForInstance(const InjectionHost* injection_host) {
  51. static int g_next_isolated_world_id =
  52. ExtensionsRendererClient::Get()->GetLowestIsolatedWorldId();
  53. IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
  54. int id = 0;
  55. const std::string& key = injection_host->id().id;
  56. auto iter = isolated_worlds.find(key);
  57. if (iter != isolated_worlds.end()) {
  58. id = iter->second;
  59. } else {
  60. id = g_next_isolated_world_id++;
  61. // This map will tend to pile up over time, but realistically, you're never
  62. // going to have enough injection hosts for it to matter.
  63. isolated_worlds[key] = id;
  64. }
  65. blink::WebIsolatedWorldInfo info;
  66. info.security_origin =
  67. blink::WebSecurityOrigin::Create(injection_host->url());
  68. info.human_readable_name = blink::WebString::FromUTF8(injection_host->name());
  69. info.stable_id = blink::WebString::FromUTF8(key);
  70. const std::string* csp = injection_host->GetContentSecurityPolicy();
  71. if (csp)
  72. info.content_security_policy = blink::WebString::FromUTF8(*csp);
  73. // Even though there may be an existing world for this |injection_host|'s key,
  74. // the properties may have changed (e.g. due to an extension update).
  75. // Overwrite any existing entries.
  76. blink::SetIsolatedWorldInfo(id, info);
  77. return id;
  78. }
  79. } // namespace
  80. // Watches for the deletion of a RenderFrame, after which is_valid will return
  81. // false.
  82. class ScriptInjection::FrameWatcher : public content::RenderFrameObserver {
  83. public:
  84. FrameWatcher(content::RenderFrame* render_frame,
  85. ScriptInjection* injection)
  86. : content::RenderFrameObserver(render_frame),
  87. injection_(injection) {}
  88. FrameWatcher(const FrameWatcher&) = delete;
  89. FrameWatcher& operator=(const FrameWatcher&) = delete;
  90. ~FrameWatcher() override {}
  91. private:
  92. void WillDetach() override { injection_->invalidate_render_frame(); }
  93. void OnDestruct() override { injection_->invalidate_render_frame(); }
  94. ScriptInjection* injection_;
  95. };
  96. // static
  97. std::string ScriptInjection::GetHostIdForIsolatedWorld(int isolated_world_id) {
  98. const IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
  99. for (const auto& iter : isolated_worlds) {
  100. if (iter.second == isolated_world_id)
  101. return iter.first;
  102. }
  103. return std::string();
  104. }
  105. // static
  106. void ScriptInjection::RemoveIsolatedWorld(const std::string& host_id) {
  107. g_isolated_worlds.Get().erase(host_id);
  108. }
  109. ScriptInjection::ScriptInjection(
  110. std::unique_ptr<ScriptInjector> injector,
  111. content::RenderFrame* render_frame,
  112. std::unique_ptr<const InjectionHost> injection_host,
  113. mojom::RunLocation run_location,
  114. bool log_activity)
  115. : injector_(std::move(injector)),
  116. render_frame_(render_frame),
  117. injection_host_(std::move(injection_host)),
  118. run_location_(run_location),
  119. request_id_(kInvalidRequestId),
  120. ukm_source_id_(ukm::SourceIdObj::FromInt64(
  121. render_frame_->GetWebFrame()->GetDocument().GetUkmSourceId())),
  122. complete_(false),
  123. did_inject_js_(false),
  124. log_activity_(log_activity),
  125. frame_watcher_(new FrameWatcher(render_frame, this)) {
  126. CHECK(injection_host_.get());
  127. TRACE_EVENT_BEGIN(
  128. "extensions", "ScriptInjection", perfetto::Track::FromPointer(this),
  129. ChromeTrackEvent::kRenderProcessHost, *content::RenderThread::Get(),
  130. ChromeTrackEvent::kChromeExtensionId,
  131. ExtensionIdForTracing(host_id().id));
  132. }
  133. ScriptInjection::~ScriptInjection() {
  134. if (!complete_)
  135. NotifyWillNotInject(ScriptInjector::WONT_INJECT);
  136. TRACE_EVENT_END("extensions", perfetto::Track::FromPointer(this),
  137. ChromeTrackEvent::kRenderProcessHost,
  138. *content::RenderThread::Get(),
  139. ChromeTrackEvent::kChromeExtensionId,
  140. ExtensionIdForTracing(host_id().id));
  141. }
  142. ScriptInjection::InjectionResult ScriptInjection::TryToInject(
  143. mojom::RunLocation current_location,
  144. ScriptsRunInfo* scripts_run_info,
  145. StatusUpdatedCallback async_updated_callback) {
  146. if (current_location < run_location_)
  147. return INJECTION_WAITING; // Wait for the right location.
  148. if (request_id_ != kInvalidRequestId) {
  149. // We're waiting for permission right now, try again later.
  150. return INJECTION_WAITING;
  151. }
  152. if (!injection_host_) {
  153. NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
  154. return INJECTION_FINISHED; // We're done.
  155. }
  156. blink::WebLocalFrame* web_frame = render_frame_->GetWebFrame();
  157. switch (injector_->CanExecuteOnFrame(
  158. injection_host_.get(), web_frame,
  159. ExtensionFrameHelper::Get(render_frame_)->tab_id())) {
  160. case PermissionsData::PageAccess::kDenied:
  161. NotifyWillNotInject(ScriptInjector::NOT_ALLOWED);
  162. return INJECTION_FINISHED; // We're done.
  163. case PermissionsData::PageAccess::kWithheld:
  164. RequestPermissionFromBrowser(std::move(async_updated_callback));
  165. return INJECTION_WAITING; // Wait around for permission.
  166. case PermissionsData::PageAccess::kAllowed:
  167. InjectionResult result = Inject(scripts_run_info);
  168. // If the injection is blocked, we need to set the manager so we can
  169. // notify it upon completion.
  170. if (result == INJECTION_BLOCKED)
  171. async_completion_callback_ = std::move(async_updated_callback);
  172. return result;
  173. }
  174. NOTREACHED();
  175. return INJECTION_FINISHED;
  176. }
  177. ScriptInjection::InjectionResult ScriptInjection::OnPermissionGranted(
  178. ScriptsRunInfo* scripts_run_info) {
  179. if (!injection_host_) {
  180. NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
  181. return INJECTION_FINISHED;
  182. }
  183. return Inject(scripts_run_info);
  184. }
  185. void ScriptInjection::OnHostRemoved() {
  186. injection_host_.reset(nullptr);
  187. }
  188. void ScriptInjection::RequestPermissionFromBrowser(
  189. StatusUpdatedCallback async_updated_callback) {
  190. // If we are just notifying the browser of the injection, then send an
  191. // invalid request (which is treated like a notification).
  192. request_id_ = g_next_pending_id++;
  193. ExtensionFrameHelper::Get(render_frame_)
  194. ->GetLocalFrameHost()
  195. ->RequestScriptInjectionPermission(
  196. host_id().id, injector_->script_type(), run_location_,
  197. base::BindOnce(&ScriptInjection::HandlePermission,
  198. weak_ptr_factory_.GetWeakPtr(),
  199. std::move(async_updated_callback)));
  200. }
  201. void ScriptInjection::NotifyWillNotInject(
  202. ScriptInjector::InjectFailureReason reason) {
  203. complete_ = true;
  204. injector_->OnWillNotInject(reason);
  205. }
  206. void ScriptInjection::HandlePermission(
  207. StatusUpdatedCallback async_updated_callback,
  208. bool granted) {
  209. if (!granted)
  210. return;
  211. std::move(async_updated_callback).Run(InjectionStatus::kPermitted, this);
  212. }
  213. ScriptInjection::InjectionResult ScriptInjection::Inject(
  214. ScriptsRunInfo* scripts_run_info) {
  215. DCHECK(injection_host_);
  216. DCHECK(scripts_run_info);
  217. DCHECK(!complete_);
  218. bool should_inject_js = injector_->ShouldInjectJs(
  219. run_location_, scripts_run_info->executing_scripts[host_id().id]);
  220. bool should_inject_or_remove_css = injector_->ShouldInjectOrRemoveCss(
  221. run_location_, scripts_run_info->injected_stylesheets[host_id().id]);
  222. // This can happen if the extension specified a script to
  223. // be run in multiple rules, and the script has already run.
  224. // See crbug.com/631247.
  225. if (!should_inject_js && !should_inject_or_remove_css) {
  226. return INJECTION_FINISHED;
  227. }
  228. if (should_inject_js)
  229. InjectJs(&(scripts_run_info->executing_scripts[host_id().id]),
  230. &(scripts_run_info->num_js));
  231. if (should_inject_or_remove_css)
  232. InjectOrRemoveCss(&(scripts_run_info->injected_stylesheets[host_id().id]),
  233. &(scripts_run_info->num_css));
  234. complete_ = did_inject_js_ || !should_inject_js;
  235. if (complete_) {
  236. if (host_id().type == mojom::HostID::HostType::kExtensions)
  237. RecordContentScriptInjection(ukm_source_id_, host_id().id);
  238. injector_->OnInjectionComplete(std::move(execution_result_), run_location_);
  239. } else {
  240. ++scripts_run_info->num_blocking_js;
  241. }
  242. return complete_ ? INJECTION_FINISHED : INJECTION_BLOCKED;
  243. }
  244. void ScriptInjection::InjectJs(std::set<std::string>* executing_scripts,
  245. size_t* num_injected_js_scripts) {
  246. TRACE_RENDERER_EXTENSION_EVENT("ScriptInjection::InjectJs", host_id().id);
  247. DCHECK(!did_inject_js_);
  248. std::vector<blink::WebScriptSource> sources = injector_->GetJsSources(
  249. run_location_, executing_scripts, num_injected_js_scripts);
  250. DCHECK(!sources.empty());
  251. base::ElapsedTimer exec_timer;
  252. // For content scripts executing during page load, we run them asynchronously
  253. // in order to reduce UI jank experienced by the user. (We don't do this for
  254. // kDocumentStart scripts, because there's no UI to jank until after those
  255. // run, so we run them as soon as we can.)
  256. // Note: We could potentially also run deferred and browser-driven scripts
  257. // asynchronously; however, these are rare enough that there probably isn't
  258. // UI jank. If this changes, we can update this.
  259. bool should_execute_asynchronously =
  260. injector_->script_type() == mojom::InjectionType::kContentScript &&
  261. (run_location_ == mojom::RunLocation::kDocumentEnd ||
  262. run_location_ == mojom::RunLocation::kDocumentIdle);
  263. blink::mojom::EvaluationTiming execution_option =
  264. should_execute_asynchronously
  265. ? blink::mojom::EvaluationTiming::kAsynchronous
  266. : blink::mojom::EvaluationTiming::kSynchronous;
  267. int32_t world_id = blink::kMainDOMWorldId;
  268. switch (injector_->GetExecutionWorld()) {
  269. case mojom::ExecutionWorld::kIsolated:
  270. world_id = GetIsolatedWorldIdForInstance(injection_host_.get());
  271. if (injection_host_->id().type == mojom::HostID::HostType::kExtensions &&
  272. log_activity_) {
  273. DOMActivityLogger::AttachToWorld(world_id, injection_host_->id().id);
  274. }
  275. break;
  276. case mojom::ExecutionWorld::kMain:
  277. world_id = blink::kMainDOMWorldId;
  278. break;
  279. }
  280. render_frame_->GetWebFrame()->RequestExecuteScript(
  281. world_id, sources, injector_->IsUserGesture(), execution_option,
  282. blink::mojom::LoadEventBlockingOption::kBlock,
  283. base::BindOnce(&ScriptInjection::OnJsInjectionCompleted,
  284. weak_ptr_factory_.GetWeakPtr()),
  285. blink::BackForwardCacheAware::kPossiblyDisallow,
  286. injector_->ShouldWaitForPromise());
  287. }
  288. void ScriptInjection::OnJsInjectionCompleted(
  289. const blink::WebVector<v8::Local<v8::Value>>& results,
  290. base::TimeTicks start_time) {
  291. DCHECK(!did_inject_js_);
  292. base::TimeTicks timestamp(base::TimeTicks::Now());
  293. absl::optional<base::TimeDelta> elapsed;
  294. // If the script will never execute (such as if the context is destroyed),
  295. // `start_time` is null. Only log a time for execution if the script, in fact,
  296. // executed.
  297. if (!start_time.is_null())
  298. elapsed = timestamp - start_time;
  299. if (injection_host_->id().type == mojom::HostID::HostType::kExtensions &&
  300. elapsed) {
  301. UMA_HISTOGRAM_TIMES("Extensions.InjectedScriptExecutionTime", *elapsed);
  302. switch (run_location_) {
  303. case mojom::RunLocation::kDocumentStart:
  304. UMA_HISTOGRAM_TIMES(
  305. "Extensions.InjectedScriptExecutionTime.DocumentStart", *elapsed);
  306. break;
  307. case mojom::RunLocation::kDocumentEnd:
  308. UMA_HISTOGRAM_TIMES(
  309. "Extensions.InjectedScriptExecutionTime.DocumentEnd", *elapsed);
  310. break;
  311. case mojom::RunLocation::kDocumentIdle:
  312. UMA_HISTOGRAM_TIMES(
  313. "Extensions.InjectedScriptExecutionTime.DocumentIdle", *elapsed);
  314. break;
  315. default:
  316. break;
  317. }
  318. }
  319. if (injector_->ExpectsResults() ==
  320. blink::mojom::WantResultOption::kWantResult) {
  321. if (!results.empty() && !results.back().IsEmpty()) {
  322. // Right now, we only support returning single results (per frame).
  323. // It's safe to always use the main world context when converting
  324. // here. V8ValueConverterImpl shouldn't actually care about the
  325. // context scope, and it switches to v8::Object's creation context
  326. // when encountered.
  327. v8::Local<v8::Context> context =
  328. render_frame_->GetWebFrame()->MainWorldScriptContext();
  329. // We use the final result, since it is the most meaningful (the result
  330. // after running all scripts). Additionally, the final script can
  331. // reference values from the previous scripts, so could return them if
  332. // desired.
  333. execution_result_ = content::V8ValueConverter::Create()->FromV8Value(
  334. results.back(), context);
  335. }
  336. if (!execution_result_.get())
  337. execution_result_ = std::make_unique<base::Value>();
  338. }
  339. did_inject_js_ = true;
  340. if (host_id().type == mojom::HostID::HostType::kExtensions)
  341. RecordContentScriptInjection(ukm_source_id_, host_id().id);
  342. // If |async_completion_callback_| is set, it means the script finished
  343. // asynchronously, and we should run it.
  344. if (!async_completion_callback_.is_null()) {
  345. complete_ = true;
  346. injector_->OnInjectionComplete(std::move(execution_result_), run_location_);
  347. // Warning: this object can be destroyed after this line!
  348. std::move(async_completion_callback_).Run(InjectionStatus::kFinished, this);
  349. }
  350. }
  351. void ScriptInjection::InjectOrRemoveCss(
  352. std::set<std::string>* injected_stylesheets,
  353. size_t* num_injected_stylesheets) {
  354. std::vector<ScriptInjector::CSSSource> css_sources = injector_->GetCssSources(
  355. run_location_, injected_stylesheets, num_injected_stylesheets);
  356. blink::WebLocalFrame* web_frame = render_frame_->GetWebFrame();
  357. auto blink_css_origin = blink::WebCssOrigin::kAuthor;
  358. switch (injector_->GetCssOrigin()) {
  359. case mojom::CSSOrigin::kUser:
  360. blink_css_origin = blink::WebCssOrigin::kUser;
  361. break;
  362. case mojom::CSSOrigin::kAuthor:
  363. blink_css_origin = blink::WebCssOrigin::kAuthor;
  364. break;
  365. }
  366. mojom::CSSInjection::Operation operation =
  367. injector_->GetCSSInjectionOperation();
  368. for (const auto& source : css_sources) {
  369. switch (operation) {
  370. case mojom::CSSInjection::Operation::kRemove:
  371. DCHECK(!source.key.IsEmpty())
  372. << "An injection key is required to remove CSS.";
  373. // CSS deletion can be thought of as the inverse of CSS injection
  374. // (i.e. x - y = x + -y and x | y = ~(~x & ~y)), so it is handled here
  375. // in the injection function.
  376. //
  377. // TODO(https://crbug.com/1116061): Extend this API's capabilities to
  378. // also remove CSS added by content scripts?
  379. web_frame->GetDocument().RemoveInsertedStyleSheet(source.key,
  380. blink_css_origin);
  381. break;
  382. case mojom::CSSInjection::Operation::kAdd:
  383. web_frame->GetDocument().InsertStyleSheet(
  384. source.code, &source.key, blink_css_origin,
  385. blink::BackForwardCacheAware::kPossiblyDisallow);
  386. break;
  387. }
  388. }
  389. }
  390. } // namespace extensions