parse-server icon indicating copy to clipboard operation
parse-server copied to clipboard

FunctionsRouter.js fails in function 'static handleCloudFunction(req)' when issuing error()

Open zurcjoe opened this issue 8 years ago • 11 comments

We use GitHub Issues for bugs.

If you have a non-bug question, ask on Stack Overflow or Server Fault:

  • https://stackoverflow.com/questions/tagged/parse.com
  • https://serverfault.com/tags/parse

If you have a vulnerability disclosure, please follow our policy available here https://github.com/parse-community/parse-server/blob/master/SECURITY.md

You may also search through existing issues before opening a new one: https://github.com/parse-community/parse-server/issues?utf8=%E2%9C%93&q=is%3Aissue

--- Please use this template. If you don't use this template, your issue may be closed without comment. ---

Issue Description

My Parse.Cloud.Function "SMSVerifyPhone" contained in /cloud/main.js issues response.error({sid: -1}) subsequently "FunctionsRouter.js fails in function 'static handleCloudFunction(req)' when performing 'return Promise' error(...)"

It should be noted that if i replace response.error({sid:-1}) with response.success({sid:-1}) the operation completes successfully???

Lastly, this is an established working production environment that has been running for one year - recent testing uncovered this issue.

Parse.Cloud.define("SMSVerifyPhone", function (request, response) {
    /**
     *
     * Private Cloud function used to verifyPhone possession. 
     *
     * @param user Parse system supplied - if validate session token, etc. undefined if user not signed in.
     * @param to   caller supplied - properly formated phone number to send SMS
     * @param from caller supplied - properly formated phone number of originating SMS sender
     * @return {JSON} returns a valid SID returned from twilio or sid: -1 unauthorized access.
     * @throws {TypeError} logic pending.
     * 
     */
    if (request.user === undefined) {
        // guard against users not authenticated or expired session token, etc.
        response.error({
            sid: -1
        });
    } else {
        const client = require('twilio')(config.accountSid, config.authToken);
        client.messages
            .create({
                body: myConstants.smsPinIntroMsg + myModules.generateRandomPassCode(100000, 999999),
                to: request.params.to,
                from: request.params.from,
            })
            .then(function (message) {
                response.success({
                    sid: message.sid
                });
                return;
            }); // ** ERROR ERROR ** need to add catch logic!!! 03/25/18
    }
});

Steps to reproduce

Please include a detailed list of steps that reproduce the issue. Include curl commands when applicable.

  1. Create instance of Parse-Server
  2. javascript client application calls cloud function - cloud function issuesresponse.error({sid: -1);

Expected Results

javascript client application should receive response error({sid:-1}) and process accordingly.

Actual Outcome

snippet of code section failing 'static handleCloudFunction(req)'

error params before reject(error) is invoked in failing function -> code:141, message:Object {sid: -1}

error => {
          try {
            _logger.logger.error(`Failed running cloud function ${functionName} for user ${userString} with:\n  Input: ${cleanInput}\n  Error: ` + JSON.stringify(error), {
              functionName,
              error,
              params,
              user: userString
            });
            reject(error);
          } catch (e) {
            reject(e);
          }

Instead the following is occurs

Exception has occurred: Object Promise Rejection (#)

Environment Setup

  • Server

    • parse-server version (Be specific! Don't say 'latest'.) : [FILL THIS OUT]
    • Operating System: MAC OSX 10.13.3
    • Hardware: INTEL
    • Localhost or remote server? LOCALHOST
  • Database

    • MongoDB version: N/A
    • Storage engine: N/A
    • Hardware: N/A
    • Localhost or remote server? AWS-MLAB

Logs/Trace

Include all relevant logs. You can turn on additional logging by configuring VERBOSE=1 in your environment.

zurcjoe avatar Mar 24 '18 16:03 zurcjoe

Please include relevant logs

flovilmart avatar Mar 24 '18 16:03 flovilmart

Will do. Thanks zurcjoe

zurcjoe avatar Mar 24 '18 19:03 zurcjoe

IIRC, response.error doesn’t accept an object as a response but a code / message.

You can do

response.error(“my error”) the JS SDK will receive a Parse.Error with code 141 and message “my error”

Or

response.error(-1, “my error”) and the JS SDK will receive a Parse.Error with code -1 and message ‘my error’

Note that this is the behavior we want in the Parse SDK for consistency. Passing an object to the error callback breaks this consistency, and then it’s impossible to pass the error back to the client as a proper Parse.Error.

flovilmart avatar Mar 24 '18 19:03 flovilmart

Flovilmart,

I have previously tried both methods that you have recommended, prior to opening ticket, and the problem persists.

Please reopen - I just updated my Parse cloud function to reflect to your recommendation(s) and I the problem reported still occurs.

Parse.Cloud.define("SMSVerifyPhone", function (request, response) {
    /**
     *
     * Private Cloud function used to verifyPhone possession. 
     *
     * @param user Parse system supplied - if validate session token, etc. undefined if user not signed in.
     * @param to   caller supplied - properly formated phone number to send SMS
     * @param from caller supplied - properly formated phone number of originating SMS sender
     * @return {JSON} returns a valid SID returned from twilio or sid: -1 unauthorized access.
     * @throws {TypeError} logic pending.
     * 
     */
    if (request.user === undefined) {
        // guard against users not authenticated or expired session token, etc.
        response.error("FAILED");
    } else {
        const client = require('twilio')(config.accountSid, config.authToken);
        client.messages
            .create({
                body: myConstants.smsPinIntroMsg + myModules.generateRandomPassCode(100000, 999999),
                to: request.params.to,
                from: request.params.from,
            })
            .then(function (message) {
                response.success({
                    sid: message.sid
                });
                return;
            }); // ** ERROR ERROR ** need to add catch logic!!! 03/25/18
    }
}); 

Debugging with legacy protocol because Node.js v6.6.0 was detected. /usr/local/bin/node --nolazy --debug-brk=11963 index.js Debugger listening on [::]:11963 index.js >>>> using serverURL http://localhost:3000/parse index.js >>>> initialization completed index.js >>>> StickyApps, LLC - 2017(c) parse-server running on port 3000. error: Failed running cloud function SMSVerifyPhone for user undefined with: Input: {"to":"+16463330650","from":"+16467444569"} Error: {"code":141,"message":"FAILED"} functionName=SMSVerifyPhone, code=141, message=FAILED, to=+16433350650, from=+1643132569, user=undefined

zurcjoe avatar Mar 24 '18 21:03 zurcjoe

What problem? The log is the expected one.

flovilmart avatar Mar 24 '18 21:03 flovilmart

I am working to turn on VERBOSE=1.

zurcjoe avatar Mar 24 '18 21:03 zurcjoe

Debugging with legacy protocol because Node.js v6.6.0 was detected.
/usr/local/bin/node --nolazy --debug-brk=33086 index.js 
Debugger listening on [::]:33086
index.js >>>> using serverURL http://localhost:3000/parse
index.js >>>> initialization completed
index.js >>>> StickyApps, LLC - 2017(c) parse-server running on port 3000.
verbose: REQUEST for [POST] /parse/functions/SMSVerifyPhone: {
  "to": "+14442750650",
  "from": "+15567132569"
} method=POST, url=/parse/functions/SMSVerifyPhone, host=c73748b4.ngrok.io, content-length=248, origin=http://localhost:3000, user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36, content-type=text/plain, accept=*/*, referer=http://localhost:3000/, accept-encoding=gzip, deflate, br, accept-language=en-US,en;q=0.9, x-forwarded-proto=https, x-forwarded-for=185.232.22.27, to=+14442750650, from=+15567132569
error: Failed running cloud function SMSVerifyPhone for user undefined with:
  Input: {"to":"+14442750650","from":"+15567132569"}
  Error: {"code":141,"message":"FAILED"} functionName=SMSVerifyPhone, code=141, message=FAILED, to=+14442750650, from=+15567132569, user=undefined
error: Error generating response. ParseError { code: 141, message: 'FAILED' } code=141, message=FAILED
error: FAILED code=141, message=FAILED

zurcjoe avatar Mar 24 '18 21:03 zurcjoe

Everything you see is expected.

flovilmart avatar Mar 24 '18 21:03 flovilmart

Oops, let me investigate further.

I apologize.

zurcjoe avatar Mar 24 '18 22:03 zurcjoe

flovilmart, I truly apologize.

My bad.

Added the following to the client code .catch(function(error) {}); .... and the correct behavior is occurring.

Thank you for your support, assistance and fast response.

Please close.

zurcjoe.

zurcjoe avatar Mar 24 '18 22:03 zurcjoe

Glad I could be of help!

flovilmart avatar Mar 24 '18 22:03 flovilmart