blob: 91b5b2719daf9773e3727b757d3e0593bb91ad31 [file] [log] [blame]
Devlin Cronin0b875672017-10-06 00:49:211// Copyright 2017 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
5#include "extensions/renderer/messaging_util.h"
6
7#include <string>
8
Hans Wennborg09979592020-04-27 12:34:309#include "base/check.h"
Devlin Croninfe7aae62017-11-16 03:49:5510#include "base/metrics/histogram_macros.h"
Hans Wennborg09979592020-04-27 12:34:3011#include "base/notreached.h"
Devlin Croninc4b07fb2017-11-14 20:26:3412#include "base/strings/stringprintf.h"
Devlin Croninb15f7f02018-01-31 19:37:3213#include "components/crx_file/id_util.h"
Devlin Cronin0b875672017-10-06 00:49:2114#include "extensions/common/api/messaging/message.h"
Devlin Croninc4b07fb2017-11-14 20:26:3415#include "extensions/common/extension.h"
Devlin Croninb1344722017-11-29 02:04:1716#include "extensions/common/manifest.h"
17#include "extensions/common/manifest_handlers/background_info.h"
Mustaq Ahmed4cd69a22018-11-15 16:34:5318#include "extensions/renderer/get_script_context.h"
Devlin Croninc4b07fb2017-11-14 20:26:3419#include "extensions/renderer/script_context.h"
Devlin Cronin0b875672017-10-06 00:49:2120#include "gin/converter.h"
Devlin Cronin37198932017-11-07 20:15:2321#include "gin/dictionary.h"
Mustaq Ahmed4baa9a6e82019-12-20 23:43:4622#include "third_party/blink/public/web/web_local_frame.h"
Devlin Cronin0b875672017-10-06 00:49:2123
24namespace extensions {
25namespace messaging_util {
26
Devlin Croninc4b07fb2017-11-14 20:26:3427namespace {
28
29constexpr char kExtensionIdRequiredErrorTemplate[] =
30 "chrome.%s() called from a webpage must specify an "
31 "Extension ID (string) for its first argument.";
32
Devlin Croninfe7aae62017-11-16 03:49:5533constexpr char kErrorCouldNotSerialize[] = "Could not serialize message.";
34
Devlin Croninc4b07fb2017-11-14 20:26:3435} // namespace
36
Devlin Cronin37198932017-11-07 20:15:2337const char kSendMessageChannel[] = "chrome.runtime.sendMessage";
38const char kSendRequestChannel[] = "chrome.extension.sendRequest";
39
Devlin Cronin182b0892017-11-10 22:22:1640const char kOnMessageEvent[] = "runtime.onMessage";
41const char kOnMessageExternalEvent[] = "runtime.onMessageExternal";
42const char kOnRequestEvent[] = "extension.onRequest";
43const char kOnRequestExternalEvent[] = "extension.onRequestExternal";
44const char kOnConnectEvent[] = "runtime.onConnect";
45const char kOnConnectExternalEvent[] = "runtime.onConnectExternal";
Maksim Ivanov1dd8391e2019-02-26 01:08:1946const char kOnConnectNativeEvent[] = "runtime.onConnectNative";
Devlin Cronin182b0892017-11-10 22:22:1647
Devlin Cronin37198932017-11-07 20:15:2348const int kNoFrameId = -1;
49
Devlin Cronin0b875672017-10-06 00:49:2150std::unique_ptr<Message> MessageFromV8(v8::Local<v8::Context> context,
Devlin Croninfe7aae62017-11-16 03:49:5551 v8::Local<v8::Value> value,
52 std::string* error_out) {
Devlin Cronin0b875672017-10-06 00:49:2153 DCHECK(!value.IsEmpty());
54 v8::Isolate* isolate = context->GetIsolate();
55 v8::Context::Scope context_scope(context);
56
57 // TODO(devlin): For some reason, we don't use the signature for
58 // Port.postMessage when evaluating the parameters. We probably should, but
59 // we don't know how many extensions that may break. It would be good to
60 // investigate, and, ideally, use the signature.
61
62 if (value->IsUndefined()) {
63 // JSON.stringify won't serialized undefined (it returns undefined), but it
64 // will serialized null. We've always converted undefined to null in JS
65 // bindings, so preserve this behavior for now.
66 value = v8::Null(isolate);
67 }
68
69 bool success = false;
70 v8::Local<v8::String> stringified;
71 {
72 v8::TryCatch try_catch(isolate);
73 success = v8::JSON::Stringify(context, value).ToLocal(&stringified);
74 }
75
Devlin Croninfe7aae62017-11-16 03:49:5576 if (!success) {
77 *error_out = kErrorCouldNotSerialize;
78 return nullptr;
Devlin Cronin0b875672017-10-06 00:49:2179 }
80
Mustaq Ahmed4cd69a22018-11-15 16:34:5381 ScriptContext* script_context = GetScriptContextFromV8Context(context);
82 blink::WebLocalFrame* web_frame =
83 script_context ? script_context->web_frame() : nullptr;
84 return MessageFromJSONString(isolate, stringified, error_out, web_frame);
Devlin Croninfe7aae62017-11-16 03:49:5585}
86
Mustaq Ahmed7b61d032018-02-14 21:59:0887std::unique_ptr<Message> MessageFromJSONString(
Dan Elphick38a508052018-07-23 22:19:5388 v8::Isolate* isolate,
Mustaq Ahmed7b61d032018-02-14 21:59:0889 v8::Local<v8::String> json,
90 std::string* error_out,
91 blink::WebLocalFrame* web_frame) {
Devlin Croninfe7aae62017-11-16 03:49:5592 std::string message;
Dan Elphick38a508052018-07-23 22:19:5393 message = gin::V8ToString(isolate, json);
Devlin Croninfe7aae62017-11-16 03:49:5594 // JSON.stringify can fail to produce a string value in one of two ways: it
95 // can throw an exception (as with unserializable objects), or it can return
96 // `undefined` (as with e.g. passing a function). If JSON.stringify returns
97 // `undefined`, the v8 API then coerces it to the string value "undefined".
98 // Check for this, and consider it a failure (since we didn't properly
99 // serialize a value).
100 if (message == "undefined") {
101 *error_out = kErrorCouldNotSerialize;
Devlin Cronin0b875672017-10-06 00:49:21102 return nullptr;
Devlin Croninfe7aae62017-11-16 03:49:55103 }
104
105 size_t message_length = message.length();
106
107 // Max bucket at 512 MB - anything over that, and we don't care.
108 static constexpr int kMaxUmaLength = 1024 * 1024 * 512;
109 static constexpr int kMinUmaLength = 1;
110 static constexpr int kBucketCount = 50;
111 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.Messaging.MessageSize",
112 message_length, kMinUmaLength, kMaxUmaLength,
113 kBucketCount);
114
115 // IPC messages will fail at > 128 MB. Restrict extension messages to 64 MB.
116 // A 64 MB JSON-ifiable object is scary enough as is.
117 static constexpr size_t kMaxMessageLength = 1024 * 1024 * 64;
118 if (message_length > kMaxMessageLength) {
119 *error_out = "Message length exceeded maximum allowed length.";
120 return nullptr;
121 }
Devlin Cronin0b875672017-10-06 00:49:21122
Mustaq Ahmed4baa9a6e82019-12-20 23:43:46123 bool has_transient_user_activation =
124 web_frame ? web_frame->HasTransientUserActivation() : false;
125 return std::make_unique<Message>(message, has_transient_user_activation);
Devlin Cronin0b875672017-10-06 00:49:21126}
127
128v8::Local<v8::Value> MessageToV8(v8::Local<v8::Context> context,
129 const Message& message) {
130 v8::Isolate* isolate = context->GetIsolate();
131 v8::Context::Scope context_scope(context);
132
133 v8::Local<v8::String> v8_message_string =
134 gin::StringToV8(isolate, message.data);
135 v8::Local<v8::Value> parsed_message;
136 v8::TryCatch try_catch(isolate);
137 if (!v8::JSON::Parse(context, v8_message_string).ToLocal(&parsed_message)) {
138 NOTREACHED();
139 return v8::Local<v8::Value>();
140 }
141 return parsed_message;
142}
143
Devlin Cronin37198932017-11-07 20:15:23144int ExtractIntegerId(v8::Local<v8::Value> value) {
Dan Elphickd010a85a2018-08-03 11:32:26145 if (value->IsInt32())
146 return value.As<v8::Int32>()->Value();
147
Devlin Cronin37198932017-11-07 20:15:23148 // Account for -0, which is a valid integer, but is stored as a number in v8.
Dan Elphickd010a85a2018-08-03 11:32:26149 DCHECK(value->IsNumber() && value.As<v8::Number>()->Value() == 0.0);
150 return 0;
Devlin Cronin37198932017-11-07 20:15:23151}
152
Devlin Cronin85efd622017-12-05 19:31:57153MessageOptions ParseMessageOptions(v8::Local<v8::Context> context,
154 v8::Local<v8::Object> v8_options,
155 int flags) {
Devlin Cronin37198932017-11-07 20:15:23156 DCHECK(!v8_options.IsEmpty());
157 DCHECK(!v8_options->IsNull());
158
159 v8::Isolate* isolate = context->GetIsolate();
160
161 MessageOptions options;
162
Devlin Cronin37198932017-11-07 20:15:23163 gin::Dictionary options_dict(isolate, v8_options);
164 if ((flags & PARSE_CHANNEL_NAME) != 0) {
165 v8::Local<v8::Value> v8_channel_name;
Devlin Cronin85efd622017-12-05 19:31:57166 bool success = options_dict.Get("name", &v8_channel_name);
167 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23168
169 if (!v8_channel_name->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57170 DCHECK(v8_channel_name->IsString());
Dan Elphick38a508052018-07-23 22:19:53171 options.channel_name = gin::V8ToString(isolate, v8_channel_name);
Devlin Cronin37198932017-11-07 20:15:23172 }
173 }
174
Devlin Cronin37198932017-11-07 20:15:23175 if ((flags & PARSE_FRAME_ID) != 0) {
176 v8::Local<v8::Value> v8_frame_id;
Devlin Cronin85efd622017-12-05 19:31:57177 bool success = options_dict.Get("frameId", &v8_frame_id);
178 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23179
180 if (!v8_frame_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57181 DCHECK(v8_frame_id->IsInt32());
Devlin Croninf054d0e2018-04-21 00:25:33182 int frame_id = v8_frame_id.As<v8::Int32>()->Value();
183 // NOTE(devlin): JS bindings coerce any negative value to -1. For
184 // backwards compatibility, we do the same here.
185 options.frame_id = frame_id < 0 ? -1 : frame_id;
Devlin Cronin37198932017-11-07 20:15:23186 }
187 }
188
Nick Harper41374d52020-01-30 22:36:47189 // Note: the options object may also include an includeTlsChannelId property.
190 // That property has been a no-op since M72. See crbug.com/1045232.
Devlin Cronin85efd622017-12-05 19:31:57191 return options;
Devlin Cronin37198932017-11-07 20:15:23192}
193
Devlin Croninc4b07fb2017-11-14 20:26:34194bool GetTargetExtensionId(ScriptContext* script_context,
195 v8::Local<v8::Value> v8_target_id,
196 const char* method_name,
197 std::string* target_out,
198 std::string* error_out) {
199 DCHECK(!v8_target_id.IsEmpty());
Devlin Cronine4eb1d912018-03-23 14:55:30200 // Argument parsing should guarantee this is null or a string before we reach
201 // this point.
202 DCHECK(v8_target_id->IsNull() || v8_target_id->IsString());
Devlin Croninc4b07fb2017-11-14 20:26:34203
204 std::string target_id;
Devlin Cronine4eb1d912018-03-23 14:55:30205 // If omitted, we use the extension associated with the context.
206 // Note: we deliberately treat the empty string as omitting the id, even
207 // though it's not strictly correct. See https://crbug.com/823577.
208 if (v8_target_id->IsNull() ||
209 (v8_target_id->IsString() &&
210 v8_target_id.As<v8::String>()->Length() == 0)) {
Devlin Croninc4b07fb2017-11-14 20:26:34211 if (!script_context->extension()) {
212 *error_out =
213 base::StringPrintf(kExtensionIdRequiredErrorTemplate, method_name);
214 return false;
215 }
216
Devlin Croninb15f7f02018-01-31 19:37:32217 target_id = script_context->extension()->id();
218 // An extension should never have an invalid id.
219 DCHECK(crx_file::id_util::IdIsValid(target_id));
Devlin Croninc4b07fb2017-11-14 20:26:34220 } else {
221 DCHECK(v8_target_id->IsString());
Dan Elphick38a508052018-07-23 22:19:53222 target_id = gin::V8ToString(script_context->isolate(), v8_target_id);
Devlin Croninb15f7f02018-01-31 19:37:32223 // NOTE(devlin): JS bindings only validate that the extension id is present,
224 // rather than validating its content. This seems better. Let's see how this
225 // goes.
226 if (!crx_file::id_util::IdIsValid(target_id)) {
227 *error_out =
228 base::StringPrintf("Invalid extension id: '%s'", target_id.c_str());
229 return false;
230 }
Devlin Croninc4b07fb2017-11-14 20:26:34231 }
232
Devlin Croninb15f7f02018-01-31 19:37:32233 *target_out = std::move(target_id);
Devlin Croninc4b07fb2017-11-14 20:26:34234 return true;
235}
236
237void MassageSendMessageArguments(
238 v8::Isolate* isolate,
239 bool allow_options_argument,
240 std::vector<v8::Local<v8::Value>>* arguments_out) {
241 base::span<const v8::Local<v8::Value>> arguments = *arguments_out;
242 size_t max_size = allow_options_argument ? 4u : 3u;
243 if (arguments.empty() || arguments.size() > max_size)
244 return;
245
246 v8::Local<v8::Value> target_id = v8::Null(isolate);
247 v8::Local<v8::Value> message = v8::Null(isolate);
248 v8::Local<v8::Value> options;
249 if (allow_options_argument)
250 options = v8::Null(isolate);
251 v8::Local<v8::Value> response_callback = v8::Null(isolate);
252
253 // If the last argument is a function, it is the response callback.
254 // Ignore it for the purposes of further argument parsing.
255 if ((*arguments.rbegin())->IsFunction()) {
256 response_callback = *arguments.rbegin();
257 arguments = arguments.first(arguments.size() - 1);
258 }
259
260 // Re-check for too many arguments after looking for the callback. If there
261 // are, early-out and rely on normal signature parsing to report the error.
262 if (arguments.size() >= max_size)
263 return;
264
265 switch (arguments.size()) {
266 case 0:
267 // Required argument (message) is missing.
268 // Early-out and rely on normal signature parsing to report this error.
269 return;
270 case 1:
271 // Argument must be the message.
272 message = arguments[0];
273 break;
Devlin Cronin7c723eb62018-04-13 19:38:26274 case 2: {
275 // Assume the first argument is the ID if we don't expect options, or if
276 // the argument could match the ID parameter.
277 // ID could be either a string, or null/undefined (since it's optional).
278 bool could_match_id =
279 arguments[0]->IsString() || arguments[0]->IsNullOrUndefined();
280 if (!allow_options_argument || could_match_id) {
Devlin Croninc4b07fb2017-11-14 20:26:34281 target_id = arguments[0];
282 message = arguments[1];
Devlin Cronin7c723eb62018-04-13 19:38:26283 } else { // Otherwise, the meaning is (message, options).
Devlin Croninc4b07fb2017-11-14 20:26:34284 message = arguments[0];
285 options = arguments[1];
286 }
287 break;
Devlin Cronin7c723eb62018-04-13 19:38:26288 }
Devlin Croninc4b07fb2017-11-14 20:26:34289 case 3:
290 DCHECK(allow_options_argument);
291 // The meaning in this case is unambiguous.
292 target_id = arguments[0];
293 message = arguments[1];
294 options = arguments[2];
295 break;
296 default:
297 NOTREACHED();
298 }
299
300 if (allow_options_argument)
301 *arguments_out = {target_id, message, options, response_callback};
302 else
303 *arguments_out = {target_id, message, response_callback};
304}
305
Devlin Croninb1344722017-11-29 02:04:17306bool IsSendRequestDisabled(ScriptContext* script_context) {
307 const Extension* extension = script_context->extension();
308 return extension && Manifest::IsUnpackedLocation(extension->location()) &&
309 BackgroundInfo::HasLazyBackgroundPage(extension);
310}
311
Devlin Cronin0b875672017-10-06 00:49:21312} // namespace messaging_util
313} // namespace extensions