fix: Server crash from unhandled promise rejection when multiple Cloud Code validator fields fail#10540
Conversation
…d Code validator fields fail
|
🚀 Thanks for opening this pull request! We appreciate your effort in improving the project. Please let us know once your pull request is ready for review. Tip
Note Please respond to review comments from AI agents just like you would to comments from a human reviewer. Let the reviewer resolve their own comments, unless they have reviewed and accepted your commit, or agreed with your explanation for why the feedback was incorrect. Caution Pull requests must be written using an AI agent with human supervision. Pull requests written entirely by a human will likely be rejected, because of lower code quality, higher review effort and the higher risk of introducing bugs. Please note that AI review comments on this pull request alone do not satisfy this requirement. Our CI and AI review are safeguards, not development tools. If many issues are flagged, rethink your development approach. Invest more effort in planning and design rather than using review cycles to fix low-quality code. |
📝 WalkthroughWalkthroughFixes a server crash caused by an unhandled promise rejection when multiple Cloud Code validated fields fail simultaneously. Refactors field validation in ChangesValidation rejection fix
Estimated code review effort: 2 (Simple) | ~10 minutes Sequence Diagram(s)sequenceDiagram
participant CloudFunction
participant builtInTriggerValidator
participant validateOptions
CloudFunction->>builtInTriggerValidator: invoke with multiple invalid fields
loop for each field in options.fields
builtInTriggerValidator->>builtInTriggerValidator: collect [opt, key, val] into optionValidations
end
builtInTriggerValidator->>validateOptions: Promise.all(optionValidations.map(validateOptions))
validateOptions-->>builtInTriggerValidator: rejection reasons
builtInTriggerValidator-->>CloudFunction: reject with VALIDATION_ERROR (no unhandled rejection)
🚥 Pre-merge checks | ✅ 5 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Biome (2.5.1)src/triggers.jsFile contains syntax errors that prevent linting: Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: return types can only be used in TypeScript files Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/triggers.js (1)
903-912: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSame latent pattern remains in the
requireUserKeysbranch.This block still invokes
validateOptions(...)immediately inside the loop beforePromise.all, the same pattern that caused#8826in theoptions.fieldsbranch. It's not currently exploitable here since no other statement in this loop throws synchronously, but it's structurally fragile — any future addition of a synchronous check (e.g. arequiredvalidation) in this loop would reintroduce the same unhandled-rejection risk. Consider applying the same input-deferral pattern here for consistency.♻️ Suggested consistency fix
} else if (typeof userKeys === 'object') { - const optionPromises = []; + const optionValidations = []; for (const key in options.requireUserKeys) { const opt = options.requireUserKeys[key]; if (opt.options) { - optionPromises.push(validateOptions(opt, key, reqUser.get(key))); + optionValidations.push([opt, key, reqUser.get(key)]); } } - await Promise.all(optionPromises); + await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v))); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/triggers.js` around lines 903 - 912, The `requireUserKeys` branch in `src/triggers.js` has the same eager-promise pattern as the earlier `options.fields` fix: `validateOptions(...)` is being invoked directly inside the loop before `Promise.all`, which can reintroduce unhandled-rejection risk if a future synchronous check is added. Update the logic in this branch to defer execution the same way as the `options.fields` path, collecting functions/thunks (or equivalent deferred work) and only invoking `validateOptions` during the `Promise.all` phase, keeping `userKeys` handling consistent and safe.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/triggers.js`:
- Around line 903-912: The `requireUserKeys` branch in `src/triggers.js` has the
same eager-promise pattern as the earlier `options.fields` fix:
`validateOptions(...)` is being invoked directly inside the loop before
`Promise.all`, which can reintroduce unhandled-rejection risk if a future
synchronous check is added. Update the logic in this branch to defer execution
the same way as the `options.fields` path, collecting functions/thunks (or
equivalent deferred work) and only invoking `validateOptions` during the
`Promise.all` phase, keeping `userKeys` handling consistent and safe.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4d4e34ea-7b2f-4ebd-a9aa-6101770f1c21
📒 Files selected for processing (2)
spec/CloudCode.Validator.spec.jssrc/triggers.js
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## alpha #10540 +/- ##
=======================================
Coverage 92.66% 92.66%
=======================================
Files 193 193
Lines 16981 16981
Branches 248 248
=======================================
Hits 15736 15736
Misses 1224 1224
Partials 21 21 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@coderabbitai what is the practical use case where the server crashed ? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
fd triggers.js src
echo "---"
ast-grep run --pattern 'function builtInTriggerValidator($$$) { $$$ }' --lang js src/triggers.js | head -100Length of output: 5201
In
Before the fix, the code did: optionPromises.push(validateOptions(opt, key, val)); // called immediately, inside the loopand only after the entire Here's the crash scenario matching fields: {
type: { type: String, options: ['a', 'b'] }, // validated first
project: { required: true } // validated second
}
So the practical trigger is: a Cloud Code validator with a The fix defers invocation of |
|
@coderabbitai does the test correctly cover the issue, with a try/catch system within the test any chance of a false positive test even in case of a crash ? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
fd "CloudCode.Validator.spec.js" spec
echo "---"
rg -n "unhandled rejection when multiple fields" -A 40 spec/CloudCode.Validator.spec.js | head -80Length of output: 1836
There is no try {
Parse.Cloud.define('hello', () => 'Hello world!', {
fields: {
type: { type: String, options: ['Option A', 'Option B'] },
project: { required: true },
},
});
await expectAsync(Parse.Cloud.run('hello', { type: 'Invalid' })).toBeRejectedWith(
jasmine.objectContaining({ code: Parse.Error.VALIDATION_ERROR })
);
await new Promise(resolve => setTimeout(resolve, 100));
expect(rejections).toEqual([]);
} finally {
process.removeListener('unhandledRejection', onUnhandledRejection);
}The Why the Node.js only terminates the process on an unhandled rejection when there are zero listeners registered for the
So if the pre-fix code path in Field ordering also matches the exact repro from One caveat worth noting: the So to directly answer: yes, the test correctly reproduces and covers the crash scenario, and no, there's no |
| } | ||
| } | ||
| await Promise.all(optionPromises); | ||
| await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v))); |
There was a problem hiding this comment.
@coderabbitai i'm not sure why it can help to fix the server crash, we should use a promise all settled here no ?
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
gh pr diff 10540 --repo parse-community/parse-server -- src/triggers.js || true
echo "---full file at base---"
gh api repos/parse-community/parse-server/pulls/10540 --jq '.base.sha' > /tmp/base_sha.txt
cat /tmp/base_sha.txt
git fetch origin $(cat /tmp/base_sha.txt) --depth=1 2>&1 | tail -5 || true
git show $(cat /tmp/base_sha.txt):src/triggers.js | sed -n '780,900p' || trueLength of output: 11352
@Moumouls Good question — I dug into the base commit (7e9d53a08) to compare, and I can now explain precisely why this small reordering fixes the crash, and why Promise.allSettled wouldn't be the right tool here.
Root cause (confirmed from the pre-PR code):
const optionPromises = [];
for (const key in options.fields) {
...
if (opt.type) {
const type = getType(opt.type);
const valType = Array.isArray(val) ? 'array' : typeof val;
if (valType !== type) {
throw `Validation failed. Invalid type for ${key}. Expected: ${type}`; // synchronous throw, not caught here
}
}
if (opt.options) {
optionPromises.push(validateOptions(opt, key, val)); // eagerly invoked -> live Promise created NOW
}
}
await Promise.all(optionPromises); // never reached if a LATER field throws aboveWith multiple fields (e.g. project and type from the issue), the loop iterates over all fields in order:
- If an earlier field's
opt.optionscheck runs first,validateOptions(...)is called immediately, creating a live Promise that's pushed intooptionPromises. - If a later field's
opt.typecheck then throws synchronously (a plainthrow, no try/catch around it), the whole loop — and the containingasync function— unwinds right there. Execution never reachesawait Promise.all(optionPromises). - The Promise created in step 1 is now orphaned: nothing ever attaches a
.then/.catchto it. If/when it eventually settles as rejected (validateOptionsdoes anawait opts(val)for function-based options, so it can resolve/reject on a later microtask), Node's unhandled-rejection detection fires because no handler was ever attached — and depending on the Node version/flags, that terminates the process.
Why the fix works:
const optionValidations = [];
for (const key in options.fields) {
...
if (opt.options) {
optionValidations.push([opt, key, val]); // just data, no Promise created yet
}
}
await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));Now validateOptions is never invoked while the loop is running — we only store [opt, key, val] tuples. Promises are only constructed (via .map(...)) right before Promise.all(...), and only if the loop finished without an early synchronous throw. So if a later field's type check throws first, no dangling, unhandled Promise was ever created for the earlier field — there's nothing left "floating" to reject unhandled.
Why not Promise.allSettled:
allSettledwouldn't address the actual bug — the eager creation of the promise inside the loop is the problem, and that still happens whether you later reduce withallorallSettled.- Also,
allSettlednever rejects: it resolves with an array of{status, value/reason}results, somaybeRunValidator's.catch()would never trigger for these field validations. You'd need extra code to inspect the results array and manuallythrowon the first failure — otherwise a failed field validation would silently be treated as a pass, which is a real regression, not an equivalent fix.
So the targeted change here (defer promise construction until after the loop) is the correct, minimal fix — it removes the possibility of orphaned promises without changing validation semantics. Let me know if you'd like me to also double check the requireUserKeys block further down, which still uses the eager-push pattern (optionPromises.push(validateOptions(...))) — it has the same theoretical exposure, though there's no synchronous throw between iterations there today, so it isn't affected by the same #8826 crash scenario.
🧬 Code Graph Analysis Results
Relevant snippets for user comment (promise/all-settled)
1) src/triggers.js (promise parallelism in built-in validator)
- Lines ~480-610 (function
builtInTriggerValidator, includesPromise.all)
async function builtInTriggerValidator(options, request, auth) {
if (request.master && !options.validateMasterKey) {
return;
}
let reqUser = request.user;
if (
!reqUser &&
request.object &&
request.object.className === '_User' &&
!request.object.existed()
) {
reqUser = request.object;
}
...
const validateOptions = async (opt, key, val) => {
let opts = opt.options;
if (typeof opts === 'function') {
try {
const result = await opts(val);
if (!result && result != null) {
throw opt.error || `Validation failed. Invalid value for ${key}.`;
}
} catch (e) {
if (!e) {
throw opt.error || `Validation failed. Invalid value for ${key}.`;
}
throw opt.error || e.message || e;
}
return;
}
...
};
...
if (Array.isArray(options.fields)) {
for (const key of options.fields) {
requiredParam(key);
}
} else {
const optionValidations = [];
for (const key in options.fields) {
...
if (opt.options) {
optionValidations.push([opt, key, val]);
}
}
await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));
}
let userRoles = options.requireAnyUserRoles;
let requireAllRoles = options.requireAllUserRoles;
const promises = [Promise.resolve(), Promise.resolve(), Promise.resolve()];
if (userRoles || requireAllRoles) {
promises[0] = auth.getUserRoles();
}
if (typeof userRoles === 'function') {
promises[1] = userRoles();
}
if (typeof requireAllRoles === 'function') {
promises[2] = requireAllRoles();
}
const [roles, resolvedUserRoles, resolvedRequireAll] = await Promise.all(promises);
...
if (userRoles) {
const hasRole = userRoles.some(requiredRole => roles.includes(`role:${requiredRole}`));
if (!hasRole) {
throw `Validation failed. User does not match the required roles.`;
}
}
if (requireAllRoles) {
for (const requiredRole of requireAllRoles) {
if (!roles.includes(`role:${requiredRole}`)) {
throw `Validation failed. User does not match all the required roles.`;
}
}
}
...
}2) src/triggers.js (validator wrapper; how rejections propagate)
- Lines ~420-480 (function
maybeRunValidator, includes.catchbehavior)
export function maybeRunValidator(request, functionName, auth) {
const theValidator = getValidator(functionName, Parse.applicationId);
if (!theValidator) {
return;
}
if (typeof theValidator === 'object' && theValidator.skipWithMasterKey && request.master) {
request.skipWithMasterKey = true;
}
return new Promise((resolve, reject) => {
return Promise.resolve()
.then(() => {
return typeof theValidator === 'object'
? builtInTriggerValidator(theValidator, request, auth)
: theValidator(request);
})
.then(() => {
resolve();
})
.catch(e => {
const error = resolveError(e, {
code: Parse.Error.VALIDATION_ERROR,
message: 'Validation failed.',
});
reject(error);
});
});
}3) src/triggers.js (how trigger/after hooks are synchronized)
- Lines ~610-735 (function
maybeRunTrigger, comment about promise return from afterSave/afterDelete/afterLogin)
export function maybeRunTrigger(
triggerType,
auth,
parseObject,
originalParseObject,
config,
context
) {
if (!parseObject) {
return Promise.resolve({});
}
return new Promise(function (resolve, reject) {
var trigger = getTrigger(parseObject.className, triggerType, config.applicationId);
if (!trigger) { return resolve(); }
var request = getRequestObject(
triggerType,
auth,
parseObject,
originalParseObject,
config,
context
);
var { success, error } = getResponseObject(
request,
object => {
...
resolve(object);
},
error => {
...
reject(error);
}
);
// AfterSave and afterDelete triggers can return a promise, which if they
// do, needs to be resolved before this promise is resolved,
// so trigger execution is synced with RestWrite.execute() call.
// If triggers do not return a promise, they can run async code parallel
// to the RestWrite.execute() call.
return Promise.resolve()
.then(() => {
return maybeRunValidator(request, `${triggerType}.${parseObject.className}`, auth);
})
.then(() => {
if (request.skipWithMasterKey) {
return Promise.resolve();
}
const promise = trigger(request);
if (
triggerType === Types.afterSave ||
triggerType === Types.afterDelete ||
triggerType === Types.afterLogin
) {
logTriggerAfterHook(
triggerType,
parseObject.className,
parseObject.toJSON(),
auth,
config.logLevels.triggerAfter
);
}
// beforeSave is expected to return null (nothing)
if (triggerType === Types.beforeSave) {
if (promise && typeof promise.then === 'function') {
return promise.then(response => {
// response.object may come from express routing before hook
if (response && response.object) {
return response;
}
return null;
});
}
return null;
}
return promise;
})
.then(success, error);
});
}4) src/Routers/FunctionsRouter.js (only tangentially related; Promise.all not present)
- Lines 32-58:
function parseObject(obj, config) {
if (Array.isArray(obj)) {
return obj.map(item => {
return parseObject(item, config);
});
} else if (obj && obj.__type == 'Date') {
return Object.assign(new Date(obj.iso), obj);
} else if (obj && obj.__type == 'File') {
if (obj.url) {
const { validateFileUrl } = require('../FileUrlValidator');
validateFileUrl(obj.url, config);
}
return Parse.File.fromJSON(obj);
} else if (obj && obj.__type == 'Pointer') {
return Parse.Object.fromJSON({
__type: 'Pointer',
className: obj.className,
objectId: obj.objectId,
});
} else if (Buffer.isBuffer(obj)) {
return obj;
} else if (obj && typeof obj === 'object') {
return parseParams(obj, config);
} else {
return obj;
}
}🧠 Learnings used
Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10117
File: benchmark/performance.js:713-737
Timestamp: 2026-03-06T21:30:03.253Z
Learning: In Parse Server LiveQuery, use liveQuery: { classNames: [...] } in the server config to specify which classes emit pub/sub events (server-side producers). Use ParseServer.createLiveQueryServer(httpServer, { appId, masterKey, serverURL }) to start the WebSocket server that forwards events to subscribed clients (event consumers); this function does not require a classNames parameter, as it simply matches incoming events against active client subscriptions.
Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10117
File: benchmark/performance.js:52-52
Timestamp: 2026-03-06T21:30:10.326Z
Learning: In reviews of JavaScript files, ensure separation of concerns for LiveQuery in Parse Server: do not rely on the LiveQuery server to perform className filtering. The filtering and class event emission should occur in the ParseServer configuration (classNames within liveQuery) or related server logic, while ParseServer.createLiveQueryServer(httpServer, { appId, masterKey, serverURL }) should only establish the WebSocket-based delivery of already-filtered events. Treat classNames filtering as the responsibility of ParseServer, not the LiveQuery server, and verify that LiveQuery code receives pre-filtered events and does not duplicate filtering logic.
Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10225
File: spec/Utils.spec.js:399-419
Timestamp: 2026-03-16T21:02:42.989Z
Learning: In the parse-community/parse-server repository, Biome is not used. Do not flag Biome lint issues (e.g., lint/suspicious/noThenProperty) or suggest biome-ignore comments in any JavaScript files. Treat Biome-related checks as exempt for all JS sources under this repo; if CI enforces Biome, ensure this guidance is reflected in CI configuration accordingly.
mtrezza
left a comment
There was a problem hiding this comment.
Please resolve any open discussions
Closes #8826
Summary by CodeRabbit