chore: clean up context bridge scopes and add specs for internal bridge (#23334)

* chore: clean up context bridge context scopes

* spec: add specs for internalContextBridge
This commit is contained in:
Samuel Attard 2020-05-11 13:41:42 -07:00 committed by GitHub
parent cf635c5fac
commit 7f9b7b2e95
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 269 additions and 121 deletions

View file

@ -7,13 +7,13 @@ const checkContextIsolationEnabled = () => {
if (!contextIsolationEnabled) throw new Error('contextBridge API can only be used when contextIsolation is enabled');
};
const contextBridge = {
const contextBridge: Electron.ContextBridge = {
exposeInMainWorld: (key: string, api: Record<string, any>) => {
checkContextIsolationEnabled();
return binding.exposeAPIInMainWorld(key, api);
},
debugGC: () => binding._debugGCMaps({})
};
} as any;
if (!binding._debugGCMaps) delete contextBridge.debugGC;
@ -32,3 +32,7 @@ export const internalContextBridge = {
},
isInMainWorld: () => binding._isCalledFromMainWorld() as boolean
};
if (binding._debugGCMaps) {
contextBridge.internalContextBridge = internalContextBridge;
}

View file

@ -151,14 +151,12 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
int recursion_depth) {
if (recursion_depth >= kMaxRecursion) {
v8::Context::Scope source_scope(source_context);
{
source_context->GetIsolate()->ThrowException(v8::Exception::TypeError(
gin::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
return v8::MaybeLocal<v8::Value>();
}
source_context->GetIsolate()->ThrowException(v8::Exception::TypeError(
gin::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
return v8::MaybeLocal<v8::Value>();
}
// Check Cache
auto cached_value = object_cache->GetCachedProxiedObject(value);
@ -177,8 +175,8 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
size_t func_id = store->take_func_id();
store->functions()[func_id] =
std::make_tuple(std::move(global_func), std::move(global_source));
v8::Context::Scope destination_scope(destination_context);
{
v8::Context::Scope destination_scope(destination_context);
v8::Local<v8::Value> proxy_func = gin_helper::CallbackToV8Leaked(
destination_context->GetIsolate(),
base::BindRepeating(&ProxyFunctionWrapper, store, func_id,
@ -194,85 +192,81 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
// Proxy promises as they have a safe and guaranteed memory lifecycle
if (value->IsPromise()) {
v8::Context::Scope destination_scope(destination_context);
{
auto source_promise = v8::Local<v8::Promise>::Cast(value);
// Make the promise a shared_ptr so that when the original promise is
// freed the proxy promise is correctly freed as well instead of being
// left dangling
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise(new gin_helper::Promise<v8::Local<v8::Value>>(
destination_context->GetIsolate()));
v8::Local<v8::Promise> proxied_promise_handle =
proxied_promise->GetHandle();
auto source_promise = v8::Local<v8::Promise>::Cast(value);
// Make the promise a shared_ptr so that when the original promise is
// freed the proxy promise is correctly freed as well instead of being
// left dangling
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> proxied_promise(
new gin_helper::Promise<v8::Local<v8::Value>>(
destination_context->GetIsolate()));
v8::Local<v8::Promise> proxied_promise_handle =
proxied_promise->GetHandle();
v8::Global<v8::Context> global_then_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_then_destination_context(
destination_context->GetIsolate(), destination_context);
global_then_source_context.SetWeak();
global_then_destination_context.SetWeak();
auto then_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate,
v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
context_bridge::RenderFrameFunctionStore* store,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
auto val =
PassValueToOtherContext(global_source_context.Get(isolate),
global_destination_context.Get(isolate),
result, store, &object_cache, false, 0);
if (!val.IsEmpty())
proxied_promise->Resolve(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_then_source_context),
std::move(global_then_destination_context), store);
v8::Global<v8::Context> global_then_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_then_destination_context(
destination_context->GetIsolate(), destination_context);
global_then_source_context.SetWeak();
global_then_destination_context.SetWeak();
auto then_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
context_bridge::RenderFrameFunctionStore* store,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
auto val =
PassValueToOtherContext(global_source_context.Get(isolate),
global_destination_context.Get(isolate),
result, store, &object_cache, false, 0);
if (!val.IsEmpty())
proxied_promise->Resolve(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_then_source_context),
std::move(global_then_destination_context), store);
v8::Global<v8::Context> global_catch_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_catch_destination_context(
destination_context->GetIsolate(), destination_context);
global_catch_source_context.SetWeak();
global_catch_destination_context.SetWeak();
auto catch_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate,
v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
context_bridge::RenderFrameFunctionStore* store,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
auto val =
PassValueToOtherContext(global_source_context.Get(isolate),
global_destination_context.Get(isolate),
result, store, &object_cache, false, 0);
if (!val.IsEmpty())
proxied_promise->Reject(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_catch_source_context),
std::move(global_catch_destination_context), store);
v8::Global<v8::Context> global_catch_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_catch_destination_context(
destination_context->GetIsolate(), destination_context);
global_catch_source_context.SetWeak();
global_catch_destination_context.SetWeak();
auto catch_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
context_bridge::RenderFrameFunctionStore* store,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
auto val =
PassValueToOtherContext(global_source_context.Get(isolate),
global_destination_context.Get(isolate),
result, store, &object_cache, false, 0);
if (!val.IsEmpty())
proxied_promise->Reject(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_catch_source_context),
std::move(global_catch_destination_context), store);
ignore_result(source_promise->Then(
source_context,
v8::Local<v8::Function>::Cast(
gin::ConvertToV8(destination_context->GetIsolate(), then_cb)),
v8::Local<v8::Function>::Cast(
gin::ConvertToV8(destination_context->GetIsolate(), catch_cb))));
ignore_result(source_promise->Then(
source_context,
v8::Local<v8::Function>::Cast(
gin::ConvertToV8(destination_context->GetIsolate(), then_cb)),
v8::Local<v8::Function>::Cast(
gin::ConvertToV8(destination_context->GetIsolate(), catch_cb))));
object_cache->CacheProxiedObject(value, proxied_promise_handle);
return v8::MaybeLocal<v8::Value>(proxied_promise_handle);
}
object_cache->CacheProxiedObject(value, proxied_promise_handle);
return v8::MaybeLocal<v8::Value>(proxied_promise_handle);
}
// Errors aren't serializable currently, we need to pull the message out and
@ -289,27 +283,25 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
// promises are proxied correctly.
if (IsPlainArray(value)) {
v8::Context::Scope destination_context_scope(destination_context);
{
v8::Local<v8::Array> arr = v8::Local<v8::Array>::Cast(value);
size_t length = arr->Length();
v8::Local<v8::Array> cloned_arr =
v8::Array::New(destination_context->GetIsolate(), length);
for (size_t i = 0; i < length; i++) {
auto value_for_array = PassValueToOtherContext(
source_context, destination_context,
arr->Get(source_context, i).ToLocalChecked(), store, object_cache,
support_dynamic_properties, recursion_depth + 1);
if (value_for_array.IsEmpty())
return v8::MaybeLocal<v8::Value>();
v8::Local<v8::Array> arr = v8::Local<v8::Array>::Cast(value);
size_t length = arr->Length();
v8::Local<v8::Array> cloned_arr =
v8::Array::New(destination_context->GetIsolate(), length);
for (size_t i = 0; i < length; i++) {
auto value_for_array = PassValueToOtherContext(
source_context, destination_context,
arr->Get(source_context, i).ToLocalChecked(), store, object_cache,
support_dynamic_properties, recursion_depth + 1);
if (value_for_array.IsEmpty())
return v8::MaybeLocal<v8::Value>();
if (!IsTrue(cloned_arr->Set(destination_context, static_cast<int>(i),
value_for_array.ToLocalChecked()))) {
return v8::MaybeLocal<v8::Value>();
}
if (!IsTrue(cloned_arr->Set(destination_context, static_cast<int>(i),
value_for_array.ToLocalChecked()))) {
return v8::MaybeLocal<v8::Value>();
}
object_cache->CacheProxiedObject(value, cloned_arr);
return v8::MaybeLocal<v8::Value>(cloned_arr);
}
object_cache->CacheProxiedObject(value, cloned_arr);
return v8::MaybeLocal<v8::Value>(cloned_arr);
}
// Proxy all objects
@ -327,15 +319,13 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
blink::CloneableMessage ret;
{
v8::Context::Scope source_context_scope(source_context);
{
// V8 serializer will throw an error if required
if (!gin::ConvertFromV8(source_context->GetIsolate(), value, &ret))
return v8::MaybeLocal<v8::Value>();
}
// V8 serializer will throw an error if required
if (!gin::ConvertFromV8(source_context->GetIsolate(), value, &ret))
return v8::MaybeLocal<v8::Value>();
}
v8::Context::Scope destination_context_scope(destination_context);
{
v8::Context::Scope destination_context_scope(destination_context);
v8::Local<v8::Value> cloned_value =
gin::ConvertToV8(destination_context->GetIsolate(), ret);
object_cache->CacheProxiedObject(value, cloned_value);
@ -354,9 +344,10 @@ v8::Local<v8::Value> ProxyFunctionWrapper(
v8::Local<v8::Context> func_owning_context =
std::get<1>(store->functions()[func_id]).Get(args->isolate());
v8::Context::Scope func_owning_context_scope(func_owning_context);
context_bridge::ObjectCache object_cache;
{
v8::Context::Scope func_owning_context_scope(func_owning_context);
context_bridge::ObjectCache object_cache;
v8::Local<v8::Function> func =
(std::get<0>(store->functions()[func_id])).Get(args->isolate());
@ -396,10 +387,8 @@ v8::Local<v8::Value> ProxyFunctionWrapper(
if (did_error) {
v8::Context::Scope calling_context_scope(calling_context);
{
args->ThrowError(error_message);
return v8::Local<v8::Object>();
}
args->ThrowError(error_message);
return v8::Local<v8::Object>();
}
if (maybe_return_value.IsEmpty())
@ -424,8 +413,9 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI(
bool support_dynamic_properties,
int recursion_depth) {
gin_helper::Dictionary api(source_context->GetIsolate(), api_object);
v8::Context::Scope destination_context_scope(destination_context);
{
v8::Context::Scope destination_context_scope(destination_context);
gin_helper::Dictionary proxy =
gin::Dictionary::CreateEmpty(destination_context->GetIsolate());
object_cache->CacheProxiedObject(api.GetHandle(), proxy.GetHandle());
@ -536,9 +526,10 @@ void ExposeAPIInMainWorld(const std::string& key,
v8::Local<v8::Context> isolated_context =
frame->WorldScriptContext(args->isolate(), WorldIDs::ISOLATED_WORLD_ID);
context_bridge::ObjectCache object_cache;
v8::Context::Scope main_context_scope(main_context);
{
context_bridge::ObjectCache object_cache;
v8::Context::Scope main_context_scope(main_context);
v8::MaybeLocal<v8::Object> maybe_proxy =
CreateProxyForAPI(api_object, isolated_context, main_context, store,
&object_cache, false, 0);

View file

@ -341,7 +341,7 @@ describe('contextBridge', () => {
if (!useSandbox) {
it('should release the global hold on methods sent across contexts', async () => {
await makeBindingWindow(() => {
require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', (contextBridge as any).debugGC()));
require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', contextBridge.debugGC()));
contextBridge.exposeInMainWorld('example', {
getFunction: () => () => 123
});
@ -365,7 +365,7 @@ describe('contextBridge', () => {
if (useSandbox) {
it('should not leak the global hold on methods sent across contexts when reloading a sandboxed renderer', async () => {
await makeBindingWindow(() => {
require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', (contextBridge as any).debugGC()));
require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', contextBridge.debugGC()));
contextBridge.exposeInMainWorld('example', {
getFunction: () => () => 123
});
@ -553,6 +553,148 @@ describe('contextBridge', () => {
// Every protomatch should be true
expect(result.protoMatches).to.deep.equal(result.protoMatches.map(() => true));
});
describe('internalContextBridge', () => {
describe('overrideGlobalValueFromIsolatedWorld', () => {
it('should override top level properties', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalValueFromIsolatedWorld(['open'], () => ({ you: 'are a wizard' }));
});
const result = await callWithBindings(async (root: any) => {
return root.open();
});
expect(result).to.deep.equal({ you: 'are a wizard' });
});
it('should override deep properties', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalValueFromIsolatedWorld(['document', 'foo'], () => 'I am foo');
});
const result = await callWithBindings(async (root: any) => {
return root.document.foo();
});
expect(result).to.equal('I am foo');
});
});
describe('overrideGlobalPropertyFromIsolatedWorld', () => {
it('should call the getter correctly', async () => {
await makeBindingWindow(() => {
let callCount = 0;
const getter = () => {
callCount++;
return true;
};
contextBridge.internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['isFun'], getter);
contextBridge.exposeInMainWorld('foo', {
callCount: () => callCount
});
});
const result = await callWithBindings(async (root: any) => {
return [root.isFun, root.foo.callCount()];
});
expect(result[0]).to.equal(true);
expect(result[1]).to.equal(1);
});
it('should not make a setter if none is provided', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['isFun'], () => true);
});
const result = await callWithBindings(async (root: any) => {
root.isFun = 123;
return root.isFun;
});
expect(result).to.equal(true);
});
it('should call the setter correctly', async () => {
await makeBindingWindow(() => {
const callArgs: any[] = [];
const setter = (...args: any[]) => {
callArgs.push(args);
return true;
};
contextBridge.internalContextBridge.overrideGlobalPropertyFromIsolatedWorld(['isFun'], () => true, setter);
contextBridge.exposeInMainWorld('foo', {
callArgs: () => callArgs
});
});
const result = await callWithBindings(async (root: any) => {
root.isFun = 123;
return root.foo.callArgs();
});
expect(result).to.have.lengthOf(1);
expect(result[0]).to.have.lengthOf(1);
expect(result[0][0]).to.equal(123);
});
});
describe('overrideGlobalValueWithDynamicPropsFromIsolatedWorld', () => {
it('should not affect normal values', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], {
a: 123,
b: () => 2,
c: () => ({ d: 3 })
});
});
const result = await callWithBindings(async (root: any) => {
return [root.thing.a, root.thing.b(), root.thing.c()];
});
expect(result).to.deep.equal([123, 2, { d: 3 }]);
});
it('should work with getters', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], {
get foo () {
return 'hi there';
}
});
});
const result = await callWithBindings(async (root: any) => {
return root.thing.foo;
});
expect(result).to.equal('hi there');
});
it('should work with setters', async () => {
await makeBindingWindow(() => {
let a: any = null;
contextBridge.internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], {
get foo () {
return a;
},
set foo (arg: any) {
a = arg + 1;
}
});
});
const result = await callWithBindings(async (root: any) => {
root.thing.foo = 123;
return root.thing.foo;
});
expect(result).to.equal(124);
});
it('should work with deep properties', async () => {
await makeBindingWindow(() => {
contextBridge.internalContextBridge.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], {
a: () => ({
get foo () {
return 'still here';
}
})
});
});
const result = await callWithBindings(async (root: any) => {
return root.thing.a().foo;
});
expect(result).to.equal('still here');
});
});
});
});
};

View file

@ -19,6 +19,17 @@ declare namespace Electron {
setAppPath(path: string | null): void;
}
interface ContextBridge {
debugGC(): { functionCount: number }
internalContextBridge: {
contextIsolationEnabled: boolean;
overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void;
isInMainWorld(): boolean;
}
}
interface WebContents {
_getURL(): string;
getOwnerBrowserWindow(): Electron.BrowserWindow;