Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions src/node_sqlite.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace sqlite {

using v8::Array;
using v8::ArrayBuffer;
using v8::BackingStore;
using v8::BackingStoreInitializationMode;
using v8::BackingStoreOnFailureMode;
using v8::BigInt;
Expand Down Expand Up @@ -2396,21 +2397,42 @@ void DatabaseSync::ApplyChangeset(const FunctionCallbackInfo<Value>& args) {
}
}

// Keep the database alive during sqlite3changeset_apply(), which may
// call conflict or filter callbacks that trigger JavaScript execution.
// If the JavaScript callback drops all references to the database,
// the DatabaseSync could otherwise be garbage-collected while the
// callback is still executing, causing a use-after-free.
// Keep the database alive in case a callback drops all references to it,
// which could otherwise let it be garbage-collected mid-callback.
BaseObjectPtr<DatabaseSync> guard(db);

ArrayBufferViewContents<uint8_t> buf(args[0]);
if (buf.length() > std::numeric_limits<int>::max()) {
THROW_ERR_OUT_OF_RANGE(env, "The changeset is too large.");
return;
}

// A callback may detach/modify the input buffer mid-apply, so copy it.
// With no callbacks, no JS runs during sqlite3changeset_apply(), so no
// copy is needed.
std::unique_ptr<BackingStore> changeset;
if (buf.length() > 0 &&
(context.filterCallback || context.conflictCallback)) {
Comment thread
trivikr marked this conversation as resolved.
changeset = ArrayBuffer::NewBackingStore(
env->isolate(),
buf.length(),
BackingStoreInitializationMode::kUninitialized,
BackingStoreOnFailureMode::kReturnNull);
if (!changeset) {
THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
return;
}
std::memcpy(changeset->Data(), buf.data(), buf.length());
}

int r;
{
CallbackDepthGuard guard(db);
r = sqlite3changeset_apply(
db->connection_,
buf.length(),
const_cast<void*>(static_cast<const void*>(buf.data())),
static_cast<int>(buf.length()),
changeset ? changeset->Data()
: const_cast<void*>(static_cast<const void*>(buf.data())),
context.filterCallback ? xFilter : nullptr,
xConflict,
static_cast<void*>(&context));
Expand Down
48 changes: 48 additions & 0 deletions test/parallel/test-sqlite-session.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,25 @@ suite('conflict resolution', () => {
[{ value: 'world' }]); // unchanged
});

test('database.applyChangeset() - changeset detached by onConflict', (t) => {
const { database2, changeset } = prepareConflict();
const result = database2.applyChangeset(changeset, {
onConflict: () => {
const transferred = structuredClone(changeset.buffer, {
transfer: [changeset.buffer],
});
new Uint8Array(transferred).fill(0);
return constants.SQLITE_CHANGESET_REPLACE;
}
});

t.assert.strictEqual(result, true);
t.assert.strictEqual(changeset.byteLength, 0);
deepStrictEqual(t)(
database2.prepare('SELECT * FROM data ORDER BY key').all(),
[{ key: 1, value: 'hello' }, { key: 2, value: 'foo' }]);
});

test('database.applyChangeset() - SQLITE_CHANGESET_DATA conflict handled with SQLITE_CHANGESET_REPLACE', (t) => {
const { database2, changeset } = prepareDataConflict();
let conflictType = null;
Expand Down Expand Up @@ -406,6 +425,35 @@ test('filter handler throws', (t) => {
});
});

test('database.applyChangeset() - changeset detached by filter', (t) => {
const database1 = new DatabaseSync(':memory:');
const database2 = new DatabaseSync(':memory:');
database1.exec('CREATE TABLE data(key INTEGER PRIMARY KEY)');
database2.exec('CREATE TABLE data(key INTEGER PRIMARY KEY)');

const session = database1.createSession();
database1.exec('INSERT INTO data VALUES (1), (2), (3)');
const changeset = session.changeset();

const result = database2.applyChangeset(changeset, {
filter: () => {
const transferred = structuredClone(changeset.buffer, {
transfer: [changeset.buffer],
});
new Uint8Array(transferred).fill(0);
return true;
}
});

t.assert.strictEqual(result, true);
t.assert.strictEqual(changeset.byteLength, 0);
deepStrictEqual(t)(database2.prepare('SELECT * FROM data').all(), [
{ key: 1 },
{ key: 2 },
{ key: 3 },
]);
});

test('database.createSession() - filter changes', (t) => {
const database1 = new DatabaseSync(':memory:');
const database2 = new DatabaseSync(':memory:');
Expand Down
Loading