Skip to content

fs: prevent multiple invocations of callback in Dir class #58430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
21 changes: 11 additions & 10 deletions lib/internal/fs/dir.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,22 +115,22 @@ class Dir {
return;
}

let dirent;
if (this.#processHandlerQueue()) {
try {
const dirent = ArrayPrototypeShift(this.#bufferedEntries);
dirent = ArrayPrototypeShift(this.#bufferedEntries);

if (this.#options.recursive && dirent.isDirectory()) {
this.readSyncRecursive(dirent);
}

if (maybeSync)
process.nextTick(callback, null, dirent);
else
callback(null, dirent);
return;
} catch (error) {
return callback(error);
}
if (maybeSync)
process.nextTick(callback, null, dirent);
else
callback(null, dirent);
return;
}

const req = new FSReqCallback();
Expand All @@ -145,16 +145,17 @@ class Dir {
return callback(err, result);
}

let dirent;
try {
this.processReadResult(this.#path, result);
const dirent = ArrayPrototypeShift(this.#bufferedEntries);
dirent = ArrayPrototypeShift(this.#bufferedEntries);
if (this.#options.recursive && dirent.isDirectory()) {
this.readSyncRecursive(dirent);
}
callback(null, dirent);
} catch (error) {
callback(error);
return callback(error);
}
return callback(null, dirent);
};

this.#operationQueue = [];
Expand Down
52 changes: 52 additions & 0 deletions test/parallel/test-fs-opendir.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const test = require('node:test');

const tmpdir = require('../common/tmpdir');

Expand Down Expand Up @@ -287,3 +288,54 @@ doConcurrentAsyncMixedOps().then(common.mustCall());
dir.closeSync();
assert.rejects(dir.close(), dirclosedError).then(common.mustCall());
}

test('fs.opendir should not double callback if user callback throws', async (t) => {
let readCallbackInvokedCount = 0;
let userErrorThrown = false;

const dir = await fs.promises.opendir('.');

t.after(() => dir.close().catch((err) => console.error('Error closing dir in t.after:', err)));

await new Promise((resolve, reject) => {
const operationTimeout = setTimeout(() => {
if (userErrorThrown && readCallbackInvokedCount === 1) {
resolve(); // User error handled, no double callback
} else if (readCallbackInvokedCount === 0) {
reject(new Error('dir.read callback was never invoked.'));
} else {
reject(new Error('Test timeout reached in an unexpected state.'));
}
}, 1000);

dir.read((err, dirent) => {
readCallbackInvokedCount++;

if (err) {
// This is an error from dir.read() itself, not the user error we're testing.
clearTimeout(operationTimeout);
return reject(new Error(`dir.read reported an error: ${err.message}`));
}

if (readCallbackInvokedCount === 1) {
userErrorThrown = true;
// Simulate the user's code throwing an error.
// A robust fs.Dir should catch this internally and not call this callback again.
throw new Error('Simulated user error in dir.read callback');
Comment on lines +323 to +324
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not correct: fs.Dir should not catch and suppress errors from user-provided callback, this error must bubble up.

The test shows that the simulated error disappears on its way, probably due to how FSReqCallback's oncomplete is handled on C++ side.

We might need to either investigate the cause and make errors inside oncomplete be thrown, or detach the callback call from it (e.g. using queueMicrotask).

}

if (readCallbackInvokedCount > 1) {
clearTimeout(operationTimeout);
return reject(new Error('dir.read callback was invoked multiple times.'));
}

// If dirent is null and it's the first call, and no user error was meant to be thrown yet,
// it implies an empty directory or an issue with the test setup if we expected more entries.
// For this specific test, we expect the user error to be thrown on the first entry.
if (dirent === null && readCallbackInvokedCount === 1 && !userErrorThrown) {
clearTimeout(operationTimeout);
return reject(new Error('Directory reading finished before user error could be simulated.'));
}
});
});
});
Loading