Error: EVP_PKEY_sign_init:operation not supported for this keytype - jwt

With jsonwebtoken 8.2.0, the following code signs a payload with RS256:
const jwt = require('jsonwebtoken');
const token = jwt.sign( //<<==sign throw error below
{
uid: this.id, //<<==payload
},
key, //<<==RSA private key of 2048bit
{
expiresIn: (parseInt(process.env.jwt_token_expire_days) * 24).toString() + 'h',
algorithm: 'RS256'
}
);
The sign throws error:
(node:6528) UnhandledPromiseRejectionWarning: Error: error:0608D096:digital envelope routines:EVP_PKEY_sign_init:operation not supported for this keytype
at Sign.sign (internal/crypto/sig.js:110:29)
at Object.sign (C:\d\code\js\xyz\node_modules\jwa\index.js:152:45)
at Object.jwsSign [as sign] (C:\d\code\js\xyz\node_modules\jws\lib\sign-stream.js:32:24)
at Object.module.exports [as sign] (C:\d\code\js\xyz\node_modules\jsonwebtoken\sign.js:204:16)
at Viewer.RSAAuthToken (C:\d\code\js\xyz\models\viewer.js:162:21)
at C:\d\code\js\xyz\routes\viewers.js:184:41
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Viewer verification status update failed TypeError: res.setheader is not a function
at C:\d\code\js\xyz\routes\viewers.js:203:17
at processTicksAndRejections (internal/process/task_queues.js:93:5)
The RSA private key (2048bit) looks like below:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtBwLxqZEirr0uhtMTThmVDu3XKFVgE+qQqQ6oi6P/cvnTBHc
zlnmgqYNpufUbnIgGSZ9RzL29gVq6o/Dc4Sf1C0sEdkU1A5weFEegpeQTfEU1XI9
.....
0q6yoDXSl7JC+y5BWaz75xFX+tb4hKVTD27BvNDYRuvRsFeiKnn7vDmVS1/CoSnd
bv9Y1DrudRU2PkgAUPqbxDzuCNY9VW8IAP/DCw0oJBJP+wzdH9uvhg==
-----END RSA PRIVATE KEY-----
What is wrong here?

It is probably because your RSA key is actually an RSA-PSS one with restrictions on used padding, usage, algorithms, digests, or any combination of those. You can confirm this hypothesis by executing
const { createPrivateKey } = require('crypto')
const pk = createPrivateKey(pem)
console.log(pk.asymmetricKeyType)
If you get rsa-pss logged, then your key is restricting the operations that can be executed with it.

Related

Flutter Web Error: [firebase_functions/internal] internal

I have a HTTP Callable Cloud Function written in Python that does some calculations and updates some Firestore documents.
It is actually working for both the android emulator and Chrome (Flutter-Web).
Still, I get the following error when I trigger it from Chrome (Flutter-Web):
Instance of '_Future<HttpsCallableResult<dynamic>>'
Error: [firebase_functions/internal] internal
at Object.throw_ [as throw] (http://localhost:54521/dart_sdk.js:5067:11)
at https_callable_web.HttpsCallableWeb.new.call (http://localhost:54521/packages/cloud_functions_web/https_callable_web.dart.lib.js:45:23)
at call.throw (<anonymous>)
at http://localhost:54521/dart_sdk.js:40576:38
at _RootZone.runBinary (http://localhost:54521/dart_sdk.js:40445:59)
at _FutureListener.thenAwait.handleError (http://localhost:54521/dart_sdk.js:35374:33)
at handleError (http://localhost:54521/dart_sdk.js:35947:51)
at Function._propagateToListeners (http://localhost:54521/dart_sdk.js:35973:17)
at _Future.new.[_completeError] (http://localhost:54521/dart_sdk.js:35823:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:54521/dart_sdk.js:35859:31)
at Object._microtaskLoop (http://localhost:54521/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:54521/dart_sdk.js:40714:13)
at http://localhost:54521/dart_sdk.js:36191:9
In the GCP Log I do not have any error shown.
This is what I return from the CF return '{"status":"200", "data": "OK"}'
In the chrome developers tools under the Network tab and status I get a CORS error. I did read quite a lot of SO Questions and I did understand that the CORS error is apparently no the real reason of the error.
Also in the same tab (Network) under Headers -> Request Headers there is shown the following Provisional headers are shown, in the Payload the value {data:null} and Response has nothing to show, which is weird since I am returning a "data": "OK".
I am fully confused, since the error thrown: internal error is not leading me anywhere.
I finally fixed it by omitting region() on the cloud function.
My original code:
exports.checkAuth = functions.region("asia-southeast1").https.onCall(async (data, context: functions.https.CallableContext) => {
return `uid: ${context.auth?.uid ?? "X"} - email: ${context.auth?.token.email ?? "X"}`;
});
I changed it to:
exports.checkAuth = functions.https.onCall(async (data, context: functions.https.CallableContext) => {
return `uid: ${context.auth?.uid ?? "X"} - email: ${context.auth?.token.email ?? "X"}`;
});
===UPDATE===
The real root cause is the region you specified in the cloud functions and the firebase functions are different, for example in my original code I used:
functions.region("asia-southeast1").https.onCall()
So, when I instantiate firebase functions in main.dart I must do this:
void main() async {
...
final firebaseFunctions = FirebaseFunctions.instanceFor(region: 'asia-southeast1');
...
}

Class variable is undefined... despite being defined

I have a class called RouteBinder that looks like this:
class RouteBinder
constructor: (#server, #pool) ->
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, (req, res, next) ->
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
)
I declare it and call it like this:
binder = new RouteBinder server, pool
binder.bindRoute "login", controllers.login
(Pool is node-postgres's Pool and is declared and tested earlier like this)
pool = new Pool
[...]
try
client = await pool.connect()
await client.query 'SELECT 1=1'
catch e
console.fatal "Could not connect to database: #{e}"
return
finally
try client.release() if client?
catch e
console.fatal "Couldn't release client: #{e}"
return
console.info 'Database is OK!'
When running this, I get this error:
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:3:24)
at _next (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:25:9)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:21:12
at /home/vi/[redacted]_accounts/main.js:166:26
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
02/14 18:44:34 error (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using CoffeeScript compiled transpiled with Babel. My .babelrc looks like this:
{
"presets": ["#babel/env"],
"plugins": [
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Sorry if it's a rookie question, I'm still learning and would love all the advice I can get.
I figured out my mistake. Both #pool and #server were defined, however, the inline function (handler) for #server[method] was running in the context of that function.
The solution was to bind it to the RouteBinder instance using .bind(#) (or .bind(this), if you prefer)
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, ((req, res, next) ->
console.log "pool", #pool
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
).bind(#))

GitHub Probot : ERROR probot: Bad Request

I am developing an application for Probot. I have configured .envand already downloaded PEM file in the folder.
Here is the content of file index.js.
module.exports = (robot) => {
robot.on('issues.opened', async context => {
const params = context.issue({ body: 'Hello World!' })
return context.github.issues.createComment(params)
})
}
But I am getting this error.
ERROR probot: Bad Request
Error: Bad Request
at Request.callback (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:696:15)
at IncomingMessage.parser (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:906:18)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
How to fix this issue?
This error not because of Probot, but the error is on GitHub ends.
This error is possibly because you have entered wrong User authorization call back URL, while creating a new GitHub application. Updating this will fix the issue.

[Frisby]Can't report correctly if test is fail

I wrote RestAPI TEST with frisby.js.
If Test result is True, There is no probrem.
But If Test result is False, Frisby doesn't report correctly on Linux.(report correctly on windows)
following are sample codes:
const frisby = require('frisby');
const Joi = frisby.Joi;
describe('TEST', () => {
it ('should return a status of 200', (done) =>{
frisby
.get('https://jsonfeed.org/feed.json')
.expect('status', 400) //deliberately error
.done(done);
});
});
If this spec.js run on Windows, result is below
> jasmine-node .
F
Failures:
1) TEST should return a status of 200
Message:
Expected 'AssertionError: HTTP status 400 !== 200
at FrisbySpec.status ([mydirpath]\expects.js:25:12)
(snip)
But, If spec.js run on Linux(Ubuntu), result is below
(node:28704) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: HTTP status 400 !== 200
at FrisbySpec.status (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/expects.js:25:12)
at FrisbySpec._addExpect.response (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:368:23)
at FrisbySpec._runExpects (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:260:24)
at _fetch.fetch.then.then.responseBody (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:139:14)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:28704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:28704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
F
Failures:
1) TEST should return a status of 200
Message:
timeout: timed out after 5000 msec waiting for spec to complete
Stacktrace:
undefined
"Failures:" section is displayed as "Timeout".
(On windows, displayed as "Expected 'AssertionError: HTTP status 400 !== 200".It is correct.)
Environments:
frisby#2.0.11
jasmine-node#1.14.5
node/9.4.0
Ubuntu16.04

How can I use a different email send method for the Accounts.sendEnrollmentEmail method in Meteor?

I use Mandrill to send emails from within Meteor. I don't have the default email method configured. I use this smart package https://github.com/Wylio/meteor-mandrill
Is there a way to change the Accounts.sendEnrollmentEmail method to use a smart package to send the email?
Right now I get the error below when I try to use that method.
Here is my error trace
message: Invalid login - 435 4.7.8 Error: authentication failed:
421 4.7.0 ip-10-102-139-231 Error: too many errors stack:
AuthError: Invalid login - 435 4.7.8 Error: authentication failed:
at Object.Future.wait (/Users/Bechard/.meteor/packages/meteor-tool/.1.0.36.15lvyk8++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/lib/node_modules/fibers/future.js:326:15)
at smtpSend (packages/email/email.js:91)
at Object.Email.send (packages/email/email.js:168)
at Object.Email.send (packages/meteorhacks:kadira/lib/hijack/email.js:9)
at Object.Accounts.sendEnrollmentEmail (packages/accounts-password/password_server.js:460)
at Object.Utils.create_user (app/server/lib/globals.js:83:22)
at Meteor.methods.singleDonation (app/server/methods/donate.js:73:36)
at methodMap.(anonymous function) (packages/meteorhacks:kadira/lib/hijack/wrap_session.js:182)
at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1599)
at packages/ddp/livedata_server.js:648
- - - - -
421 4.7.0 ip-10-102-139-231 Error: too many errors
at SMTPClient._actionAUTHComplete (/Users/Bechard/.meteor/packages/email/.1.0.4.ioat51++os+web.browser+web.cordova/npm/node_modules/simplesmtp/lib/client.js:826:23)
at SMTPClient._onData (/Users/Bechard/.meteor/packages/email/.1.0.4.ioat51++os+web.browser+web.cordova/npm/node_modules/simplesmtp/lib/client.js:329:29)
at CleartextStream.emit (events.js:95:17)
at CleartextStream.<anonymous> (_stream_readable.js:748:14)
at CleartextStream.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:410:10)
at _stream_readable.js:403:7
at process._tickCallback (node.js:419:13)
Turns out I didn't declare the Mandrill key in my startup function.
I originally had this
Meteor.startup(function() {
return Meteor.Mandrill.config({
username: Meteor.settings.mandrillUsername
});
});
I changed it to this and the email sent fine.
Meteor.startup(function() {
return Meteor.Mandrill.config({
username: Meteor.settings.mandrillUsername,
"key": Meteor.settings.mandrillKey
});
});