Skip to content

Commit 14a57e6

Browse files
inspector: avoid JS execution in DOMStorage.getDOMStorageItems
Protocol messages from a remote frontend are dispatched from a V8 API interrupt, where executing JavaScript is disallowed. DOMStorageAgent::getDOMStorageItems() previously looked up globalThis.localStorage and globalThis.sessionStorage via v8::Object::Get(), invoking their lazy JS getters on globalThis. In addition, Storage::GetAll() opened the backing store via Storage::Open(), which threw a JS Error on failure only for the inspector agent to catch it with v8::TryCatch. Track live Storage instances in webstorage::BindingData when the inspector subclasses construct them in Storage::New(), using the flag they pass to tell localStorage from sessionStorage, since both can be in memory. Check HasRealNamedCallbackProperty() before reading the global property so the lazy JS getter is not invoked during an interrupt. When the store has not yet been initialized by JS during an interrupt, read the SQLite backing file directly for localStorage and return an empty map for sessionStorage. Factor Storage::OpenConnection() to return open errors as a C++ string rather than throwing a JS exception in Storage::GetAll(). Co-authored-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com> Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
1 parent 3090ade commit 14a57e6

7 files changed

Lines changed: 214 additions & 99 deletions

File tree

‎src/base_object_types.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ namespace node {
2626
V(http2_binding_data, http2::BindingData) \
2727
V(http_parser_binding_data, http_parser::BindingData) \
2828
V(quic_binding_data, quic::BindingData) \
29-
V(sqlite_binding_data, sqlite::BindingData)
29+
V(sqlite_binding_data, sqlite::BindingData) \
30+
V(webstorage_binding_data, webstorage::BindingData)
3031

3132
// List of (non-binding) BaseObjects that are serializable in the snapshot.
3233
// The first argument should match what the type passes to

‎src/inspector/dom_storage_agent.cc‎

Lines changed: 71 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
#include "dom_storage_agent.h"
22
#include <optional>
3+
#include "base_object-inl.h"
34
#include "env-inl.h"
45
#include "inspector/inspector_object_utils.h"
6+
#include "node_realm-inl.h"
7+
#include "path.h"
58
#include "util.h"
69
#include "v8-exception.h"
710
#include "v8-isolate.h"
@@ -100,38 +103,35 @@ protocol::DispatchResponse DOMStorageAgent::getDOMStorageItems(
100103
is_local_storage ? &local_storage_map_ : &session_storage_map_;
101104
std::optional<StorageMap> storage_map_fallback;
102105
if (storage_map->empty()) {
103-
auto web_storage_obj = getWebStorage(is_local_storage);
106+
bool is_uninitialized = false;
107+
auto web_storage_obj = getWebStorage(is_local_storage, &is_uninitialized);
104108
// Each way of failing below says something different about the store, so
105109
// each reports a different reason. A frontend that cannot read a store
106110
// otherwise has no way to tell a missing one from a corrupt one.
107-
if (!web_storage_obj) {
111+
if (!web_storage_obj && !is_uninitialized) {
108112
return protocol::DispatchResponse::ServerError(
109113
"Could not read DOM storage items: storage is unavailable");
110114
}
111-
// A message from a remote frontend is dispatched without a HandleScope
112-
// on the stack, and opening the backing file can throw, so give the
113-
// exception a scope to be allocated in and somewhere to land.
114-
v8::HandleScope handle_scope(env_->isolate());
115-
v8::TryCatch try_catch(env_->isolate());
116-
storage_map_fallback = web_storage_obj.value()->GetAll();
117-
if (try_catch.HasCaught()) {
118-
// Pass the reason along; "the file was written by a newer Node.js" and
119-
// "the file is locked" are not the same problem to the user. Read it
120-
// off the Message, which was built when the exception was thrown.
121-
// Converting the exception itself would call a user-patchable
122-
// Error.prototype.toString, and there is no JavaScript frame here to
123-
// run it from.
124-
Local<v8::Message> message = try_catch.Message();
125-
if (!message.IsEmpty()) {
126-
Utf8Value reason(env_->isolate(), message->Get());
127-
return protocol::DispatchResponse::ServerError(
128-
std::string("Could not read DOM storage items: ") + reason.out());
115+
std::string open_error;
116+
if (web_storage_obj) {
117+
storage_map_fallback = web_storage_obj.value()->GetAll(&open_error);
118+
} else if (is_local_storage) {
119+
std::string location = env_->options()->localstorage_file;
120+
if (location != node::webstorage::kInMemoryPath) {
121+
location = ToNamespacedPath(env_, location);
129122
}
130-
// V8 builds that Message on a best-effort basis, so the throw is all we
131-
// can report when it is missing.
123+
storage_map_fallback =
124+
node::webstorage::Storage::ReadAllFromFile(location, &open_error);
125+
} else {
126+
storage_map_fallback.emplace();
127+
}
128+
if (!open_error.empty()) {
129+
// Pass the reason along; "the file was written by a newer Node.js" and
130+
// "the file is locked" are not the same problem to the user. Prefix with
131+
// "Uncaught Error: " to match the v8::Message format without invoking
132+
// JavaScript during a V8 interrupt.
132133
return protocol::DispatchResponse::ServerError(
133-
"Could not read DOM storage items: the backing store could not be "
134-
"opened");
134+
"Could not read DOM storage items: Uncaught Error: " + open_error);
135135
}
136136
if (!storage_map_fallback.has_value()) {
137137
return protocol::DispatchResponse::ServerError(
@@ -318,26 +318,60 @@ void DOMStorageAgent::registerStorage(Local<Context> context,
318318
}
319319

320320
std::optional<node::webstorage::Storage*> DOMStorageAgent::getWebStorage(
321-
bool is_local_storage) {
321+
bool is_local_storage, bool* is_uninitialized) {
322+
*is_uninitialized = false;
323+
if (!env_->options()->webstorage) {
324+
return std::nullopt;
325+
}
326+
if (is_local_storage && env_->options()->localstorage_file.empty()) {
327+
return std::nullopt;
328+
}
329+
if (auto* binding = env_->principal_realm()
330+
->GetBindingData<node::webstorage::BindingData>()) {
331+
const auto& storage_ptr =
332+
is_local_storage ? binding->local_storage : binding->session_storage;
333+
if (storage_ptr) {
334+
return storage_ptr.get();
335+
}
336+
}
337+
if (env_->no_browser_globals()) {
338+
return std::nullopt;
339+
}
322340
v8::Isolate* isolate = env_->isolate();
323341
v8::HandleScope handle_scope(isolate);
324-
v8::Local<v8::Object> global = env_->context()->Global();
342+
v8::Local<v8::Context> context = env_->context();
343+
v8::Local<v8::Object> global = context->Global();
344+
v8::Local<v8::String> prop_name =
345+
is_local_storage ? FIXED_ONE_BYTE_STRING(isolate, "localStorage")
346+
: FIXED_ONE_BYTE_STRING(isolate, "sessionStorage");
347+
// Protocol messages from a remote frontend are dispatched from a V8 API
348+
// interrupt, where executing JavaScript is disallowed. Both globals are
349+
// defined as lazy JS getters, so check whether the property is still an
350+
// accessor before reading it.
351+
bool is_accessor = false;
352+
if (!global->HasRealNamedCallbackProperty(context, prop_name)
353+
.To(&is_accessor)) {
354+
return std::nullopt;
355+
}
356+
if (is_accessor) {
357+
if (env_->is_processing_v8_interrupt()) {
358+
*is_uninitialized = true;
359+
return std::nullopt;
360+
}
361+
if (!env_->can_call_into_js()) {
362+
return std::nullopt;
363+
}
364+
}
325365
v8::Local<v8::Value> web_storage_val;
326366
v8::TryCatch try_catch(isolate);
327-
if (!global
328-
->Get(env_->context(),
329-
is_local_storage
330-
? FIXED_ONE_BYTE_STRING(isolate, "localStorage")
331-
: FIXED_ONE_BYTE_STRING(isolate, "sessionStorage"))
332-
.ToLocal(&web_storage_val) ||
367+
if (!global->Get(context, prop_name).ToLocal(&web_storage_val) ||
333368
!web_storage_val->IsObject() || try_catch.HasCaught()) {
334369
return std::nullopt;
335-
} else {
336-
node::webstorage::Storage* storage;
337-
ASSIGN_OR_RETURN_UNWRAP(
338-
&storage, web_storage_val.As<v8::Object>(), std::nullopt);
339-
return storage;
340370
}
371+
node::webstorage::Storage* storage;
372+
ASSIGN_OR_RETURN_UNWRAP(
373+
&storage, web_storage_val.As<v8::Object>(), std::nullopt);
374+
return storage;
341375
}
342376

343377
bool DOMStorageAgent::canEmit(const std::string& domain) {

‎src/inspector/dom_storage_agent.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ class DOMStorageAgent : public protocol::DOMStorage::Backend,
5454
private:
5555
typedef std::unordered_map<std::u16string, std::u16string> StorageMap;
5656
std::optional<node::webstorage::Storage*> getWebStorage(
57-
bool is_local_storage);
57+
bool is_local_storage, bool* is_uninitialized);
5858
std::unique_ptr<protocol::DOMStorage::Frontend> frontend_;
5959
StorageMap local_storage_map_ = {};
6060
StorageMap session_storage_map_ = {};

‎src/node_webstorage.cc‎

Lines changed: 96 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "node.h"
99
#include "node_errors.h"
1010
#include "node_mem-inl.h"
11+
#include "node_realm-inl.h"
1112
#include "path.h"
1213
#include "simdutf.h"
1314
#include "sqlite3.h"
@@ -98,6 +99,14 @@ static void ThrowQuotaExceededException(Local<Context> context) {
9899
isolate->ThrowException(exception);
99100
}
100101

102+
BindingData::BindingData(Realm* realm, Local<Object> wrap)
103+
: BaseObject(realm, wrap) {}
104+
105+
void BindingData::MemoryInfo(MemoryTracker* tracker) const {
106+
tracker->TrackField("local_storage", local_storage);
107+
tracker->TrackField("session_storage", session_storage);
108+
}
109+
101110
Storage::Storage(Environment* env,
102111
Local<Object> object,
103112
std::string_view location)
@@ -117,7 +126,8 @@ void Storage::MemoryInfo(MemoryTracker* tracker) const {
117126
tracker->TrackField("location", location_);
118127
}
119128

120-
Maybe<void> Storage::Open() {
129+
conn_unique_ptr Storage::OpenConnection(std::string_view location,
130+
std::string* error) {
121131
static const int kCurrentSchemaVersion = 1;
122132
static constexpr std::string_view get_schema_version_sql =
123133
"SELECT schema_version FROM nodejs_webstorage_state";
@@ -180,21 +190,24 @@ Maybe<void> Storage::Open() {
180190
""
181191
"INSERT OR IGNORE INTO nodejs_webstorage_state (total_size) VALUES (0);";
182192

183-
sqlite3* db = db_.get();
184-
if (db != nullptr) {
185-
return JustVoid();
186-
}
187-
188-
int r = sqlite3_open(location_.c_str(), &db);
193+
sqlite3* db = nullptr;
194+
std::string loc(location);
195+
int r = sqlite3_open(loc.c_str(), &db);
189196
// Adopt the connection before anything below can return early, so that a
190197
// failure does not leak it. sqlite3_open() allocates a connection to be
191198
// closed even when it fails. This is declared ahead of the statement below
192199
// so that the statement is finalized first; sqlite3_close() fails while a
193200
// statement is still open, and conn_deleter treats that as fatal.
194201
auto conn = conn_unique_ptr(db);
195-
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
202+
if (r != SQLITE_OK) {
203+
if (error != nullptr) *error = sqlite3_errstr(r);
204+
return nullptr;
205+
}
196206
r = sqlite3_exec(db, init_sql_v0.data(), nullptr, nullptr, nullptr);
197-
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
207+
if (r != SQLITE_OK) {
208+
if (error != nullptr) *error = sqlite3_errstr(r);
209+
return nullptr;
210+
}
198211

199212
// Get the current schema version, used to determine schema migrations.
200213
sqlite3_stmt* s = nullptr;
@@ -204,22 +217,30 @@ Maybe<void> Storage::Open() {
204217
&s,
205218
nullptr);
206219
auto stmt = stmt_unique_ptr(s);
207-
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
208-
CHECK_ERROR_OR_THROW(
209-
env(), sqlite3_step(stmt.get()), SQLITE_ROW, Nothing<void>());
210-
CHECK_COLUMN_TYPE_OR_THROW(env(),
211-
stmt.get(),
212-
0,
213-
SQLITE_INTEGER,
214-
"expected schema_version to be an integer",
215-
Nothing<void>());
220+
if (r != SQLITE_OK) {
221+
if (error != nullptr) *error = sqlite3_errstr(r);
222+
return nullptr;
223+
}
224+
r = sqlite3_step(stmt.get());
225+
if (r != SQLITE_ROW) {
226+
if (error != nullptr) *error = sqlite3_errstr(r);
227+
return nullptr;
228+
}
229+
if (sqlite3_column_type(stmt.get(), 0) != SQLITE_INTEGER) {
230+
if (error != nullptr) {
231+
*error = "localStorage database is malformed: "
232+
"expected schema_version to be an integer";
233+
}
234+
return nullptr;
235+
}
216236
int schema_version = sqlite3_column_int(stmt.get(), 0);
217237
stmt = nullptr; // Force finalization.
218238

219239
if (schema_version > kCurrentSchemaVersion) {
220-
THROW_ERR_INVALID_STATE(
221-
env(), "localStorage was created with a newer version of Node.js");
222-
return Nothing<void>();
240+
if (error != nullptr) {
241+
*error = "localStorage was created with a newer version of Node.js";
242+
}
243+
return nullptr;
223244
}
224245

225246
if (schema_version < kCurrentSchemaVersion) {
@@ -229,10 +250,25 @@ Maybe<void> Storage::Open() {
229250
std::to_string(kCurrentSchemaVersion) + ";";
230251
r = sqlite3_exec(
231252
db, set_user_version_sql.c_str(), nullptr, nullptr, nullptr);
232-
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
253+
if (r != SQLITE_OK) {
254+
if (error != nullptr) *error = sqlite3_errstr(r);
255+
return nullptr;
256+
}
233257
}
234258

235-
db_ = std::move(conn);
259+
return conn;
260+
}
261+
262+
Maybe<void> Storage::Open() {
263+
if (db_ != nullptr) {
264+
return JustVoid();
265+
}
266+
std::string error;
267+
db_ = OpenConnection(location_, &error);
268+
if (db_ == nullptr) {
269+
THROW_ERR_INVALID_STATE(env(), "%s", error.c_str());
270+
return Nothing<void>();
271+
}
236272
return JustVoid();
237273
}
238274

@@ -255,7 +291,15 @@ void Storage::New(const FunctionCallbackInfo<Value>& args) {
255291
ToNamespacedPath(env, &location);
256292
}
257293

258-
new Storage(env, args.This(), location.ToStringView());
294+
Storage* storage = new Storage(env, args.This(), location.ToStringView());
295+
// The inspector subclasses pass whether this is localStorage, which the
296+
// location cannot tell: --localstorage-file=:memory: is valid too.
297+
BindingData* binding_data = realm->GetBindingData<BindingData>();
298+
if (binding_data != nullptr && args[2]->IsBoolean()) {
299+
auto& slot = args[2]->IsTrue() ? binding_data->local_storage
300+
: binding_data->session_storage;
301+
slot = BaseObjectWeakPtr<Storage>(storage);
302+
}
259303
}
260304

261305
Maybe<void> Storage::Clear() {
@@ -310,23 +354,18 @@ MaybeLocal<Array> Storage::Enumerate() {
310354
return Array::New(env()->isolate(), values.data(), values.size());
311355
}
312356

313-
std::optional<std::unordered_map<std::u16string, std::u16string>>
314-
Storage::GetAll() {
315-
if (!Open().IsJust()) {
316-
return std::nullopt;
317-
}
318-
357+
static std::optional<Storage::StorageMap> ReadAllFromDb(sqlite3* db) {
319358
static constexpr std::string_view sql =
320359
"SELECT key, value FROM nodejs_webstorage";
321360
sqlite3_stmt* s = nullptr;
322-
int r = sqlite3_prepare_v2(db_.get(), sql.data(), sql.size(), &s, nullptr);
361+
int r = sqlite3_prepare_v2(db, sql.data(), sql.size(), &s, nullptr);
323362
auto stmt = stmt_unique_ptr(s);
324363
// Unlike the other accessors, this one has no JavaScript caller to throw at,
325364
// so every failure below is reported to the inspector agent instead.
326365
if (r != SQLITE_OK) {
327366
return std::nullopt;
328367
}
329-
std::unordered_map<std::u16string, std::u16string> result;
368+
Storage::StorageMap result;
330369
while ((r = sqlite3_step(stmt.get())) == SQLITE_ROW) {
331370
if (sqlite3_column_type(stmt.get(), 0) != SQLITE_BLOB ||
332371
sqlite3_column_type(stmt.get(), 1) != SQLITE_BLOB) {
@@ -350,6 +389,25 @@ Storage::GetAll() {
350389
return result;
351390
}
352391

392+
std::optional<Storage::StorageMap> Storage::GetAll(std::string* error) {
393+
if (db_ == nullptr) {
394+
db_ = OpenConnection(location_, error);
395+
if (db_ == nullptr) {
396+
return std::nullopt;
397+
}
398+
}
399+
return ReadAllFromDb(db_.get());
400+
}
401+
402+
std::optional<Storage::StorageMap> Storage::ReadAllFromFile(
403+
std::string_view location, std::string* error) {
404+
conn_unique_ptr conn = OpenConnection(location, error);
405+
if (conn == nullptr) {
406+
return std::nullopt;
407+
}
408+
return ReadAllFromDb(conn.get());
409+
}
410+
353411
MaybeLocal<Value> Storage::Length() {
354412
if (!Open().IsJust()) {
355413
return {};
@@ -762,8 +820,13 @@ static void Initialize(Local<Object> target,
762820
Local<Value> unused,
763821
Local<Context> context,
764822
void* priv) {
765-
Environment* env = Environment::GetCurrent(context);
823+
Realm* realm = Realm::GetCurrent(context);
824+
Environment* env = realm->env();
766825
Isolate* isolate = env->isolate();
826+
Realm* principal = env->principal_realm();
827+
if (principal->GetBindingData<BindingData>() == nullptr) {
828+
principal->AddBindingData<BindingData>(target);
829+
}
767830
auto ctor_tmpl = NewFunctionTemplate(isolate, Storage::New);
768831
auto inst_tmpl = ctor_tmpl->InstanceTemplate();
769832

0 commit comments

Comments
 (0)