Skip to content

Commit 47307a2

Browse files
committed
sqlite: reject connection access from authorizer callbacks
SQLite requires that an authorizer callback not modify the connection that invoked it, and counts sqlite3_prepare_v2() and sqlite3_step() as modifications. node:sqlite let an authorizer callback call prepare(), exec(), the statement execution methods, and other connection-mutating APIs on the same DatabaseSync. Track authorizer depth on DatabaseSync with an RAII guard around the callback, and throw ERR_INVALID_STATE from the affected entry points while the callback is on the stack. The depth is per-connection, so other connections stay usable from the callback. The guard covers every authorizer invocation, not just those from an explicit prepare(), since SQLite may re-prepare a statement during sqlite3_step() after a schema change. serialize() and the session changeset() and patchset() methods prepare statements internally, so they re-enter the authorizer too. Reentry through changeset() does not terminate: it recurses until the process is killed, with no way to catch it from JavaScript. Finalizing a statement is a separate hazard. It frees the virtual machine that sqlite3_step() is executing, which crashes rather than throwing, and any callback SQLite invokes during execution can reach it, not only an authorizer. Track the statements currently being stepped and reject finalizing one of those, so a user-defined function can still prepare and finalize its own helper statements. Disposal stays idempotent, since throwing for an already-finalized statement would demote a `using` scope's exception to a SuppressedError. Signed-off-by: Trevor Burnham <[email protected]> Fixes: nodejs#63207 Assisted-by: claude:opus-5
1 parent e6fa5bf commit 47307a2

5 files changed

Lines changed: 455 additions & 5 deletions

File tree

‎doc/api/sqlite.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,11 @@ wrapper around [`sqlite3_create_function_v2()`][].
439439

440440
<!-- YAML
441441
added: v24.10.0
442+
changes:
443+
- version: REPLACEME
444+
pr-url: https://github.com/nodejs/node/pull/65156
445+
description: Accessing the invoking database connection from the authorizer
446+
callback now throws.
442447
-->
443448

444449
* `callback` {Function|null} The authorizer function to set, or `null` to
@@ -464,6 +469,23 @@ The callback must return one of the following constants:
464469
* `SQLITE_DENY` - Deny the operation (causes an error).
465470
* `SQLITE_IGNORE` - Ignore the operation (silently skip).
466471

472+
SQLite requires that the authorizer callback not modify the database connection
473+
that invoked it, which includes preparing and stepping statements. Methods that
474+
would do so throw an error with code `ERR_INVALID_STATE` while the callback is
475+
on the stack, including `database.prepare()`, `database.exec()`, the execution
476+
methods of that connection's statements, iterators, and tag stores, and
477+
`database.setAuthorizer()` itself. Other connections remain usable.
478+
479+
The callback can also be invoked from within `statement.run()`,
480+
`statement.get()`, and similar methods, because SQLite may re-prepare a
481+
statement during execution after a schema change.
482+
483+
Separately, `statement.close()` throws if the statement is the one currently
484+
being executed, because finalizing it would free the virtual machine that is
485+
running. This applies to any callback SQLite invokes during execution, such as
486+
a user-defined function. Other statements on the connection can still be
487+
finalized.
488+
467489
```cjs
468490
const { DatabaseSync, constants } = require('node:sqlite');
469491
const db = new DatabaseSync(':memory:');

‎src/node_sqlite.cc‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,25 @@ inline MaybeLocal<String> Utf8StringMaybeOneByte(Isolate* isolate,
9696
} \
9797
} while (0)
9898

99+
// SQLite requires that an authorizer callback not modify the connection that
100+
// invoked it. Preparing and stepping statements both count as modifying it.
101+
// See https://www.sqlite.org/c3ref/set_authorizer.html.
102+
#define THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db) \
103+
THROW_AND_RETURN_ON_BAD_STATE( \
104+
(env), \
105+
(db)->IsInAuthorizerCallback(), \
106+
"database cannot be accessed from an authorizer callback")
107+
108+
// Finalizing a statement frees its virtual machine. A callback that SQLite
109+
// invokes from inside sqlite3_step() therefore must not finalize the statement
110+
// being stepped, which would be a use-after-free rather than merely a contract
111+
// violation. Finalizing other statements on the connection stays allowed.
112+
#define THROW_AND_RETURN_IF_STEPPING(env, stmt) \
113+
THROW_AND_RETURN_ON_BAD_STATE( \
114+
(env), \
115+
(stmt)->db_->IsSteppingStatement((stmt)->statement_), \
116+
"statement cannot be finalized while it is being executed")
117+
99118
#define SQLITE_VALUE_TO_JS(from, isolate, use_big_int_args, result, ...) \
100119
do { \
101120
switch (sqlite3_##from##_type(__VA_ARGS__)) { \
@@ -825,6 +844,12 @@ Intercepted DatabaseSyncLimits::LimitsSetter(
825844
return Intercepted::kYes;
826845
}
827846

847+
if (limits->database_->IsInAuthorizerCallback()) {
848+
THROW_ERR_INVALID_STATE(
849+
env, "database cannot be accessed from an authorizer callback");
850+
return Intercepted::kYes;
851+
}
852+
828853
if (!value->IsNumber()) {
829854
THROW_ERR_INVALID_ARG_TYPE(
830855
isolate, "Limit value must be a non-negative integer or Infinity.");
@@ -1081,6 +1106,7 @@ void DatabaseSync::CreateTagStore(const FunctionCallbackInfo<Value>& args) {
10811106
THROW_ERR_INVALID_STATE(env, "database is not open");
10821107
return;
10831108
}
1109+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
10841110
int capacity = 1000;
10851111
if (args.Length() > 0 && !args[0]->IsUndefined()) {
10861112
if (!args[0]->IsNumber()) {
@@ -1483,6 +1509,7 @@ void DatabaseSync::Prepare(const FunctionCallbackInfo<Value>& args) {
14831509
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
14841510
Environment* env = Environment::GetCurrent(args);
14851511
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1512+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
14861513

14871514
if (!args[0]->IsString()) {
14881515
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
@@ -1606,6 +1633,7 @@ void DatabaseSync::Exec(const FunctionCallbackInfo<Value>& args) {
16061633
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
16071634
Environment* env = Environment::GetCurrent(args);
16081635
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1636+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
16091637

16101638
if (!args[0]->IsString()) {
16111639
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
@@ -1630,6 +1658,7 @@ void DatabaseSync::CustomFunction(const FunctionCallbackInfo<Value>& args) {
16301658
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
16311659
Environment* env = Environment::GetCurrent(args);
16321660
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1661+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
16331662

16341663
if (!args[0]->IsString()) {
16351664
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
@@ -1803,6 +1832,7 @@ void DatabaseSync::Serialize(const FunctionCallbackInfo<Value>& args) {
18031832
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
18041833
Environment* env = Environment::GetCurrent(args);
18051834
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1835+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
18061836

18071837
std::string db_name = "main";
18081838
if (!args[0]->IsUndefined()) {
@@ -1858,6 +1888,7 @@ void DatabaseSync::Deserialize(const FunctionCallbackInfo<Value>& args) {
18581888
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
18591889
Environment* env = Environment::GetCurrent(args);
18601890
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1891+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
18611892

18621893
if (!args[0]->IsUint8Array()) {
18631894
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
@@ -1933,6 +1964,7 @@ void DatabaseSync::AggregateFunction(const FunctionCallbackInfo<Value>& args) {
19331964
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
19341965
Environment* env = Environment::GetCurrent(args);
19351966
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
1967+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
19361968
Utf8Value name(env->isolate(), args[0].As<String>());
19371969
Local<Object> options = args[1].As<Object>();
19381970
Local<Value> start_v;
@@ -2144,6 +2176,7 @@ void DatabaseSync::CreateSession(const FunctionCallbackInfo<Value>& args) {
21442176
DatabaseSync* db;
21452177
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
21462178
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
2179+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
21472180

21482181
sqlite3_session* pSession;
21492182
int r = sqlite3session_create(db->connection_, db_name.c_str(), &pSession);
@@ -2313,6 +2346,7 @@ void DatabaseSync::ApplyChangeset(const FunctionCallbackInfo<Value>& args) {
23132346
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
23142347
Environment* env = Environment::GetCurrent(args);
23152348
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
2349+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
23162350

23172351
if (!args[0]->IsUint8Array()) {
23182352
THROW_ERR_INVALID_ARG_TYPE(
@@ -2447,6 +2481,7 @@ void DatabaseSync::EnableLoadExtension(
24472481
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
24482482
Environment* env = Environment::GetCurrent(args);
24492483
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
2484+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
24502485

24512486
Isolate* isolate = env->isolate();
24522487
if (!args[0]->IsBoolean()) {
@@ -2475,6 +2510,7 @@ void DatabaseSync::EnableDefensive(const FunctionCallbackInfo<Value>& args) {
24752510
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
24762511
Environment* env = Environment::GetCurrent(args);
24772512
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
2513+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
24782514

24792515
Isolate* isolate = env->isolate();
24802516
if (!args[0]->IsBoolean()) {
@@ -2500,6 +2536,7 @@ void DatabaseSync::LoadExtension(const FunctionCallbackInfo<Value>& args) {
25002536
env, !db->allow_load_extension_, "extension loading is not allowed");
25012537
THROW_AND_RETURN_ON_BAD_STATE(
25022538
env, !db->enable_load_extension_, "extension loading is not allowed");
2539+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
25032540

25042541
if (!args[0]->IsString()) {
25052542
THROW_ERR_INVALID_ARG_TYPE(env->isolate(),
@@ -2528,6 +2565,7 @@ void DatabaseSync::SetAuthorizer(const FunctionCallbackInfo<Value>& args) {
25282565
ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
25292566
Environment* env = Environment::GetCurrent(args);
25302567
THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
2568+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, db);
25312569

25322570
Isolate* isolate = env->isolate();
25332571

@@ -2564,6 +2602,7 @@ int DatabaseSync::AuthorizerCallback(void* user_data,
25642602
const char* param4) {
25652603
DatabaseSync* db = static_cast<DatabaseSync*>(user_data);
25662604
CallbackDepthGuard guard(db);
2605+
AuthorizerDepthGuard authorizer_guard(db);
25672606
Environment* env = db->env();
25682607
Isolate* isolate = env->isolate();
25692608
HandleScope handle_scope(isolate);
@@ -2677,12 +2716,20 @@ void StatementSync::Close(const FunctionCallbackInfo<Value>& args) {
26772716
Environment* env = Environment::GetCurrent(args);
26782717
THROW_AND_RETURN_ON_BAD_STATE(
26792718
env, stmt->IsFinalized(), "statement has been finalized");
2719+
THROW_AND_RETURN_IF_STEPPING(env, stmt);
26802720
stmt->Close();
26812721
}
26822722

26832723
void StatementSync::Dispose(const FunctionCallbackInfo<Value>& args) {
26842724
StatementSync* stmt;
26852725
ASSIGN_OR_RETURN_UNWRAP(&stmt, args.This());
2726+
Environment* env = Environment::GetCurrent(args);
2727+
// Disposal is idempotent, so an already-finalized statement is a no-op even
2728+
// inside a callback.
2729+
if (stmt->IsFinalized()) {
2730+
return;
2731+
}
2732+
THROW_AND_RETURN_IF_STEPPING(env, stmt);
26862733
stmt->Close();
26872734
}
26882735

@@ -2963,6 +3010,7 @@ MaybeLocal<Value> StatementExecutionHelper::All(Environment* env,
29633010
LocalVector<Value> row_values(isolate);
29643011
LocalVector<Name> row_keys(isolate);
29653012

3013+
SteppingStatementGuard stepping(db, stmt);
29663014
while ((r = sqlite3_step(stmt)) == SQLITE_ROW) {
29673015
if (num_cols == 0) {
29683016
num_cols = sqlite3_column_count(stmt);
@@ -3005,7 +3053,10 @@ MaybeLocal<Object> StatementExecutionHelper::Run(Environment* env,
30053053
bool use_big_ints) {
30063054
Isolate* isolate = env->isolate();
30073055
EscapableHandleScope scope(isolate);
3008-
sqlite3_step(stmt);
3056+
{
3057+
SteppingStatementGuard stepping(db, stmt);
3058+
sqlite3_step(stmt);
3059+
}
30093060
int r = sqlite3_reset(stmt);
30103061
CHECK_ERROR_OR_THROW(isolate, db, r, SQLITE_OK, MaybeLocal<Object>());
30113062

@@ -3083,7 +3134,11 @@ MaybeLocal<Value> StatementExecutionHelper::Get(Environment* env,
30833134
EscapableHandleScope scope(isolate);
30843135
auto reset = OnScopeLeave([&]() { sqlite3_reset(stmt); });
30853136

3086-
int r = sqlite3_step(stmt);
3137+
int r;
3138+
{
3139+
SteppingStatementGuard stepping(db, stmt);
3140+
r = sqlite3_step(stmt);
3141+
}
30873142
if (r == SQLITE_DONE) return scope.Escape(Undefined(isolate));
30883143
if (r != SQLITE_ROW) {
30893144
THROW_ERR_SQLITE_ERROR(isolate, db);
@@ -3127,6 +3182,7 @@ void StatementSync::All(const FunctionCallbackInfo<Value>& args) {
31273182
Environment* env = Environment::GetCurrent(args);
31283183
THROW_AND_RETURN_ON_BAD_STATE(
31293184
env, stmt->IsFinalized(), "statement has been finalized");
3185+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, stmt->db_.get());
31303186
Isolate* isolate = env->isolate();
31313187
int r = stmt->ResetStatement();
31323188
CHECK_ERROR_OR_THROW(isolate, stmt->db_.get(), r, SQLITE_OK, void());
@@ -3154,6 +3210,7 @@ void StatementSync::Iterate(const FunctionCallbackInfo<Value>& args) {
31543210
Environment* env = Environment::GetCurrent(args);
31553211
THROW_AND_RETURN_ON_BAD_STATE(
31563212
env, stmt->IsFinalized(), "statement has been finalized");
3213+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, stmt->db_.get());
31573214
int r = stmt->ResetStatement();
31583215
CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
31593216

@@ -3177,6 +3234,7 @@ void StatementSync::Get(const FunctionCallbackInfo<Value>& args) {
31773234
Environment* env = Environment::GetCurrent(args);
31783235
THROW_AND_RETURN_ON_BAD_STATE(
31793236
env, stmt->IsFinalized(), "statement has been finalized");
3237+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, stmt->db_.get());
31803238
int r = stmt->ResetStatement();
31813239
CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
31823240

@@ -3201,6 +3259,7 @@ void StatementSync::Run(const FunctionCallbackInfo<Value>& args) {
32013259
Environment* env = Environment::GetCurrent(args);
32023260
THROW_AND_RETURN_ON_BAD_STATE(
32033261
env, stmt->IsFinalized(), "statement has been finalized");
3262+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, stmt->db_.get());
32043263
int r = stmt->ResetStatement();
32053264
CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
32063265

@@ -3483,6 +3542,7 @@ void SQLTagStore::Run(const FunctionCallbackInfo<Value>& args) {
34833542

34843543
THROW_AND_RETURN_ON_BAD_STATE(
34853544
env, !session->database_->IsOpen(), "database is not open");
3545+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get());
34863546

34873547
BaseObjectPtr<StatementSync> stmt = PrepareStatement(args);
34883548

@@ -3509,6 +3569,7 @@ void SQLTagStore::Iterate(const FunctionCallbackInfo<Value>& args) {
35093569

35103570
THROW_AND_RETURN_ON_BAD_STATE(
35113571
env, !session->database_->IsOpen(), "database is not open");
3572+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get());
35123573

35133574
BaseObjectPtr<StatementSync> stmt = PrepareStatement(args);
35143575

@@ -3537,6 +3598,7 @@ void SQLTagStore::Get(const FunctionCallbackInfo<Value>& args) {
35373598

35383599
THROW_AND_RETURN_ON_BAD_STATE(
35393600
env, !session->database_->IsOpen(), "database is not open");
3601+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get());
35403602

35413603
BaseObjectPtr<StatementSync> stmt = PrepareStatement(args);
35423604

@@ -3566,6 +3628,7 @@ void SQLTagStore::All(const FunctionCallbackInfo<Value>& args) {
35663628

35673629
THROW_AND_RETURN_ON_BAD_STATE(
35683630
env, !session->database_->IsOpen(), "database is not open");
3631+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get());
35693632

35703633
BaseObjectPtr<StatementSync> stmt = PrepareStatement(args);
35713634

@@ -3592,6 +3655,10 @@ void SQLTagStore::All(const FunctionCallbackInfo<Value>& args) {
35923655
void SQLTagStore::Clear(const FunctionCallbackInfo<Value>& args) {
35933656
SQLTagStore* store;
35943657
ASSIGN_OR_RETURN_UNWRAP(&store, args.This());
3658+
Environment* env = Environment::GetCurrent(args);
3659+
if (store->database_) {
3660+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, store->database_.get());
3661+
}
35953662
store->sql_tags_.Clear();
35963663
}
35973664

@@ -3785,6 +3852,7 @@ void StatementSyncIterator::Next(const FunctionCallbackInfo<Value>& args) {
37853852
Environment* env = Environment::GetCurrent(args);
37863853
THROW_AND_RETURN_ON_BAD_STATE(
37873854
env, iter->stmt_->IsFinalized(), "statement has been finalized");
3855+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, iter->stmt_->db_.get());
37883856
Isolate* isolate = env->isolate();
37893857

37903858
auto iter_template = getLazyIterTemplate(env);
@@ -3807,7 +3875,12 @@ void StatementSyncIterator::Next(const FunctionCallbackInfo<Value>& args) {
38073875
iter->statement_reset_generation_ != iter->stmt_->reset_generation_,
38083876
"iterator was invalidated");
38093877

3810-
int r = sqlite3_step(iter->stmt_->statement_);
3878+
int r;
3879+
{
3880+
SteppingStatementGuard stepping(iter->stmt_->db_.get(),
3881+
iter->stmt_->statement_);
3882+
r = sqlite3_step(iter->stmt_->statement_);
3883+
}
38113884
if (r != SQLITE_ROW) {
38123885
CHECK_ERROR_OR_THROW(
38133886
env->isolate(), iter->stmt_->db_.get(), r, SQLITE_DONE, void());
@@ -3862,6 +3935,7 @@ void StatementSyncIterator::Return(const FunctionCallbackInfo<Value>& args) {
38623935
Environment* env = Environment::GetCurrent(args);
38633936
THROW_AND_RETURN_ON_BAD_STATE(
38643937
env, iter->stmt_->IsFinalized(), "statement has been finalized");
3938+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, iter->stmt_->db_.get());
38653939
Isolate* isolate = env->isolate();
38663940

38673941
sqlite3_reset(iter->stmt_->statement_);
@@ -3940,6 +4014,7 @@ void Session::Changeset(const FunctionCallbackInfo<Value>& args) {
39404014
env, !session->database_->IsOpen(), "database is not open");
39414015
THROW_AND_RETURN_ON_BAD_STATE(
39424016
env, session->session_ == nullptr, "session is not open");
4017+
THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get());
39434018

39444019
int nChangeset;
39454020
void* pChangeset;

0 commit comments

Comments
 (0)