Skip to content

Commit ae98298

Browse files
committed
src: fix sqlite connection leak in Web Storage
Storage::Open() only adopted the sqlite3 handle into its RAII holder after initialisation succeeded, so every early error return leaked the connection opened by sqlite3_open(), which usually returns a handle even on failure. Repeated failed initialisations then leaked one file descriptor each, since db_ is never set and every operation retries. Adopt the handle immediately after sqlite3_open() instead. Also check the sqlite3_prepare_v2() return value in Open(), which was overwritten before being checked by a duplicated sqlite3_exec() of the initialisation SQL that also ran the script a second time on every open. Validate the stored schema version's column type instead of asserting it, so a crafted localStorage file surfaces ERR_INVALID_STATE rather than aborting the process. Fixes: nodejs#64640 Signed-off-by: Yusufhan Saçak <[email protected]>
1 parent 01c1300 commit ae98298

2 files changed

Lines changed: 122 additions & 3 deletions

File tree

‎src/node_webstorage.cc‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ Maybe<void> Storage::Open() {
173173
}
174174

175175
int r = sqlite3_open(location_.c_str(), &db);
176+
// sqlite3_open() usually returns a database handle even on failure, so
177+
// adopt it immediately to ensure it is closed on every error return path.
178+
auto conn = conn_unique_ptr(db);
176179
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
177180
r = sqlite3_exec(db, init_sql_v0.data(), nullptr, nullptr, nullptr);
178181
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
@@ -184,12 +187,15 @@ Maybe<void> Storage::Open() {
184187
get_schema_version_sql.size(),
185188
&s,
186189
nullptr);
187-
r = sqlite3_exec(db, init_sql_v0.data(), nullptr, nullptr, nullptr);
188190
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
189191
auto stmt = stmt_unique_ptr(s);
190192
CHECK_ERROR_OR_THROW(
191193
env(), sqlite3_step(stmt.get()), SQLITE_ROW, Nothing<void>());
192-
CHECK(sqlite3_column_type(stmt.get(), 0) == SQLITE_INTEGER);
194+
if (sqlite3_column_type(stmt.get(), 0) != SQLITE_INTEGER) {
195+
THROW_ERR_INVALID_STATE(env(),
196+
"localStorage schema version is not an integer");
197+
return Nothing<void>();
198+
}
193199
int schema_version = sqlite3_column_int(stmt.get(), 0);
194200
stmt = nullptr; // Force finalization.
195201

@@ -209,7 +215,7 @@ Maybe<void> Storage::Open() {
209215
CHECK_ERROR_OR_THROW(env(), r, SQLITE_OK, Nothing<void>());
210216
}
211217

212-
db_ = conn_unique_ptr(db);
218+
db_ = std::move(conn);
213219
return JustVoid();
214220
}
215221

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
common.skipIfSQLiteMissing();
5+
6+
if (common.isWindows) {
7+
common.skip('SQLite on Windows uses HANDLEs, not fds');
8+
}
9+
10+
const tmpdir = require('../common/tmpdir');
11+
const assert = require('node:assert');
12+
const { spawnPromisified } = common;
13+
const { writeFileSync } = require('node:fs');
14+
const { join } = require('node:path');
15+
const { DatabaseSync } = require('node:sqlite');
16+
const { test } = require('node:test');
17+
18+
tmpdir.refresh();
19+
20+
// Regression tests for https://github.com/nodejs/node/issues/64640. Failed
21+
// localStorage initialisation leaked the SQLite connection opened by
22+
// sqlite3_open(), which usually returns a database handle even on failure.
23+
// Each retry then leaked one more file descriptor.
24+
async function assertFailedInitDoesNotLeak(localStorageFile, message) {
25+
const cp = await spawnPromisified(process.execPath, [
26+
'--localstorage-file', localStorageFile,
27+
'-e', `
28+
const assert = require('node:assert');
29+
const { openSync, closeSync } = require('node:fs');
30+
// The lowest fd available to a new file. If a failed localStorage
31+
// initialisation leaks its connection, this number grows.
32+
const probeFd = () => {
33+
const fd = openSync(process.execPath, 'r');
34+
closeSync(fd);
35+
return fd;
36+
};
37+
const expected = { code: 'ERR_INVALID_STATE', message: ${message} };
38+
// Warm up lazily initialised resources before sampling the fd space.
39+
assert.throws(() => localStorage.length, expected);
40+
const before = probeFd();
41+
for (let i = 0; i < 15; i++) {
42+
assert.throws(() => localStorage.length, expected);
43+
}
44+
assert.strictEqual(probeFd(), before);
45+
`,
46+
]);
47+
48+
assert.strictEqual(cp.stderr, '');
49+
assert.strictEqual(cp.code, 0);
50+
assert.strictEqual(cp.signal, null);
51+
}
52+
53+
test('corrupt non-SQLite file does not leak fds', async () => {
54+
const file = join(tmpdir.path, 'corrupt.localstorage');
55+
writeFileSync(file, 'not a sqlite database '.repeat(10));
56+
await assertFailedInitDoesNotLeak(file, '/not a database/');
57+
});
58+
59+
test('unopenable database path does not leak fds', async () => {
60+
const file = join(tmpdir.path, 'missing-dir', 'db.localstorage');
61+
await assertFailedInitDoesNotLeak(file, '/unable to open database file/');
62+
});
63+
64+
test('newer schema version does not leak fds', async () => {
65+
const file = join(tmpdir.path, 'newer-schema.localstorage');
66+
const db = new DatabaseSync(file);
67+
db.exec(`CREATE TABLE nodejs_webstorage_state(
68+
max_size INTEGER NOT NULL DEFAULT 10485760,
69+
total_size INTEGER NOT NULL,
70+
schema_version INTEGER NOT NULL DEFAULT 0,
71+
single_row_ INTEGER NOT NULL DEFAULT 1 CHECK(single_row_ = 1),
72+
PRIMARY KEY(single_row_)
73+
) STRICT;
74+
INSERT INTO nodejs_webstorage_state (total_size, schema_version)
75+
VALUES (0, 99);`);
76+
db.close();
77+
await assertFailedInitDoesNotLeak(file, '/newer version of Node\\.js/');
78+
});
79+
80+
test('empty state table does not leak fds', async () => {
81+
const file = join(tmpdir.path, 'zero-rows.localstorage');
82+
const db = new DatabaseSync(file);
83+
// The extra NOT NULL column makes the initialisation script's
84+
// INSERT OR IGNORE skip silently, leaving the state table empty, so
85+
// Open() fails while a prepared statement is still live.
86+
db.exec(`CREATE TABLE nodejs_webstorage_state(
87+
max_size INTEGER NOT NULL DEFAULT 10485760,
88+
total_size INTEGER NOT NULL,
89+
schema_version INTEGER NOT NULL DEFAULT 0,
90+
single_row_ INTEGER NOT NULL DEFAULT 1 CHECK(single_row_ = 1),
91+
extra INTEGER NOT NULL,
92+
PRIMARY KEY(single_row_)
93+
) STRICT;`);
94+
db.close();
95+
await assertFailedInitDoesNotLeak(file, '/no more rows available/');
96+
});
97+
98+
test('non-integer schema version throws instead of aborting', async () => {
99+
const file = join(tmpdir.path, 'text-schema.localstorage');
100+
const db = new DatabaseSync(file);
101+
db.exec(`CREATE TABLE nodejs_webstorage_state(
102+
max_size INTEGER NOT NULL DEFAULT 10485760,
103+
total_size INTEGER NOT NULL,
104+
schema_version TEXT NOT NULL,
105+
single_row_ INTEGER NOT NULL DEFAULT 1 CHECK(single_row_ = 1),
106+
PRIMARY KEY(single_row_)
107+
) STRICT;
108+
INSERT INTO nodejs_webstorage_state (total_size, schema_version)
109+
VALUES (0, 'pwned');`);
110+
db.close();
111+
await assertFailedInitDoesNotLeak(
112+
file, '/schema version is not an integer/');
113+
});

0 commit comments

Comments
 (0)