MongoDB production AUTH FAILED - node.js

I'm trying to connect my server to my MongoDB database in production,
But When I try to do that :
mongoose.connect("mongodb://user:randompassword#ds011452.mlab.com:11452/dbname?authSource=dbWithUserCredentials");
I get a
connection error: { [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
note : my dbname is the same as the username...
Any IDeas ?

I've find my answer :
I've upgraded mongoDB to the 3.0 version,
and after that I've upgraded mongoose to the > 4.3.0 version
http://mongoosejs.com/docs/compatibility.html
and It works !
edit :
after update mongoDB to 3.0
(I used brew)
package.json
->
"dependencies": {
"mongoose": "~4.3.0",
...
then npm install

Related

Getting MongoServerSelectionError in localhost

I have a node.js application deployed in Azure which connects to Azure CosmosDB (MongoDb database).
To connect to to mongo-db i use this code
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
client = new MongoClient(mongoConnectionUri, options)
// #ts-ignore
global._mongoClientPromise = client.connect()
clientPromise = global._mongoClientPromise
this is working fine when deployed in Azure as containerapp, but when i try to run it from localhost
npm run dev -- -- open
When the part to connect to mongo-db comes, I am getting this error,
MongoServerSelectionError: Server selection timed out after 30000 ms
at Timeout._onTimeout (xyz/node_modules/mongodb/lib/sdam/topology.js:293:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(1) {
'my-db.mongo.cosmos.azure.com:10255' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'globaldb',
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
MongoDB connection string:
mongodb://my-db:abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz==#my-db.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#my-db#
there are no network restrictions
My node version
node --version
v16.17.1
npm version
{
npm: '8.15.0',
node: '16.17.1',
v8: '9.4.146.26-node.22',
uv: '1.43.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.18.1',
modules: '93',
nghttp2: '1.47.0',
napi: '8',
llhttp: '6.0.9',
openssl: '1.1.1q+quic',
cldr: '41.0',
icu: '71.1',
tz: '2022a',
unicode: '14.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
}
This was working from local before , but suddenly it is not working,
From Az cli in my local I am able to retrieve the database details in cosmosdb
az cosmosdb database show --resource-group rgname --name accountname --db-name dbname
Update:
If i try the connection string by installing mongosh
mongosh and the command
mongosh "mongodb://my-db:abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz==#my-db.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#my-db#"
MongoServerSelectionError: Server selection timed out after 30000 ms
I am getting the same errorMongoServerSelectionError: Server selection timed out after 30000 ms
Can anyone please help?
Update:
Mobile hotspot:
Able to connect with my mobile-hotspot in the same machine (macOS big slur) to the same remote db without any errors.
Tried this will different versions of node.js and mongodb libraries including latest but the same error when connecting with Home wifi. Before recently i had changed the wifi security from wpa to wpa2 personal and ever since this error occurs

Jest detects open redis client on travis-ci

I encountered some difficulties with redis testing on travis-ci.
Here is the redis setup code,
async function getClient() {
const redisClient = createClient({
socket: {
url: redisConfig.connectionString,
reconnectStrategy: (currentNumberOfRetries: number) => {
if (currentNumberOfRetries > 1) {
throw new Error("max retries reached");
}
return 1000;
},
},
});
try {
await redisClient.connect();
} catch (e) {
console.log(e);
}
return redisClient;
}
Here is the travis config, note that I run npm install redis because it is listed as a peer dependency.
language: node_js
node_js:
- "14"
dist: focal # ubuntu 20.04
services:
- postgresql
- redis-server
addons:
postgresql: "13"
apt:
packages:
- postgresql-13
env:
global:
- PGUSER=postgres
- PGPORT=5432 # for some reason unlike what documentation says, the port is 5432
jobs:
- NODE_ENV=ci
cache:
directories:
- node_modules
before_install:
- sudo sed -i -e '/local.*peer/s/postgres/all/' -e 's/peer\|md5/trust/g' /etc/postgresql/*/main/pg_hba.conf
- sudo service postgresql restart
- sleep 1
- postgres --version
- pg_lsclusters # shows port of postgresql, ubuntu specific command
install:
- npm i
- npm i redis
before_script:
- sudo psql -c 'create database orm_test;' -p 5432 -U postgres
script:
- npm run test-detectopen
The first issue is this missing client.connect function, whereas connection on my local machine with redis-server running works.
console.log
TypeError: redisClient.connect is not a function
at Object.getClient (/home/travis/build/sunjc826/mini-orm/src/connection/redis/index.ts:21:23)
at Function.init (/home/travis/build/sunjc826/mini-orm/src/data-mapper/index.ts:33:30)
at /home/travis/build/sunjc826/mini-orm/src/lib-test/tests/orm.test.ts:25:20
at Promise.then.completed (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/utils.js:390:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/utils.js:315:10)
at _callCircusHook (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/run.js:181:40)
at _runTestsForDescribeBlock (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/run.js:47:7)
at run (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/run.js:25:3)
at runAndTransformResultsToJestFormat (/home/travis/build/sunjc826/mini-orm/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:166:21)
The second is this open handle issue, on my local machine, even if connection fails, jest does not give such an error and exits cleanly.
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPWRAP
7 |
8 | async function getClient() {
> 9 | const redisClient = createClient({
| ^
10 | socket: {
11 | url: redisConfig.connectionString,
12 | reconnectStrategy: (currentNumberOfRetries: number) => {
at RedisClient.Object.<anonymous>.RedisClient.create_stream (node_modules/redis/index.js:196:31)
at new RedisClient (node_modules/redis/index.js:121:10)
at Object.<anonymous>.exports.createClient (node_modules/redis/index.js:1023:12)
at Object.getClient (src/connection/redis/index.ts:9:23)
at Function.init (src/data-mapper/index.ts:33:30)
at src/lib-test/tests/orm.test.ts:25:20
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/#jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/#jest/core/build/cli/index.js:261:3)
It turns out that this is likely caused by redis being a peer dependency.
Listing out node-redis versions, I'm guessing the version tagged latest (as of time writing 3.1.2) was installed instead of the version 4+.
So, I moved redis to regular dependencies instead.

MongoDB node.js: index created ignoring TTL

I'm trying to create an index with TTL using the MongoDB driver for Node.js and a Mongo server hosted at mLab.
Node version 9.3.0.
Driver version 3.0.0.rc0
mongod version: 3.4.10 (MMAPv1)
Code in node.js:
var processCollection;
async function init (options) {
processCollection = await options.db.collection('processes');
await processCollection.dropIndexes();
await processCollection.createIndex(
{ 'modified': 1 },
{ expireAfterSeconds: 3600 }
);
}
Results in DB:
db['system.indexes'].find()
{
"v": 2,
"key": {
"modified": 1
},
"name": "modified_1",
"ns": "e-consular.processes"
}
The option expireAfterSeconds is missing in the resulting index. What am I doing wrong?
Collection.createIndex is broken in versions 3.0.0rc0 and 3.0.0 of the Node mongodb driver. It will ignore the options object argument.
This was fixed in version 3.0.1 of the driver. (You can see the fix here).
Update your driver to the latest version (e.g. npm i mongodb#3.0.4) and it should work as expected.

bundle.js bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-core\lib\topologies/../../package.json'

I am getting the below error:
bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-ore\lib\topologies/../../package.json'
Here is my version detial:
OS: Windows10
MongoDB: 2.2.16
MongoDB-core: 2.1.2
Node: 6.9.2
I have used npm install bson-ext and changed \node_modules\mongodb-core\node_modules\bson-ext\ext\index.js to
try {
// Load the precompiled win32 binary
if(process.platform == "win32" && process.arch == "x64") {
bson = require('bson');
} else if(process.platform == "win32" && process.arch == "ia32") {
bson = require('bson');
} else {
bson = require('bson');
}
} catch(err) {
console.log(err)
// Attempt to load the release bson version
try {
bson = require('bindings')('bson.node');
} catch (err) {
throw new Error("js-bson: Failed to load c++ bson extension, using pure JS version");
}
}
while the original is:
bson = require('./win32/x64/bson');
because when I try browserify range.js > bundle.js, it cannot find bson-ext module in mongoDB-core.
I am not sure whether this kind of operation may cause the above error.
Here is my package.json file :
"dependencies": {
"browserify": "^13.1.1",
"bson": "^1.0.1",
"d3": "^4.4.0",
"express": "^4.14.0",
"hbs": "^4.0.1",
"jsdom": "^9.9.1",
"mongodb": "^2.2.16",
"mongodb-core": "^2.1.2"
}
I haven't been able to confirm this yet, but I think the problem is that MongoDB's JavaScript (Node.js) driver is not intended for use in a browser, for security reasons. Not clear if the problem in the OP is due to Browserify incorrectly resolving relative paths or something else, but regardless the preferred technique is to proxy requests to your MongoDB instance via a Node server.
Mongo lists off-the-shelf solutions for this here:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/
Note also the --rest option, which allows an application to read directly from the DB via a URL schema:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/#simple-rest-api
As the docs mention, this is not good practice for security concerns, but may help with prototyping.

Could not connect to mongod from mongo shell when auth enabled (on ubuntu)

System: ubuntu 14.04
mongodb 3.0.3 tar ball is downloaded from mongodb download center
connected to mongodb without auth, then from mongo shell, created a user for 'test' db. following is the command.
db.createUser({user: "user1",
pwd: "test123",
roles: [ { role: "readWrite", db: "test" }
]})
Verified that user details in admin db. Following is the command & result:
> db.system.users.findOne({user:'user1'})
{
"_id" : "testdb.user1",
"user" : "user1",
"db" : "testdb",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "kNfOd1vs+QT+ueH7SI6Vzw==",
"storedKey" : "JCesIKSW1pb74ddo2Y19rEO1GVY=",
"serverKey" : "d87Sb1htoD5K8zecAy73JPZyHdc="
}
},
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
Now exit from the mongo shell, killed the mongod.
Started the mongodb with auth, following is the command.
$ ./mongod --auth
Connected to mongo shell as usual, see the below:
$ ./mongo
MongoDB shell version: 3.0.3
connecting to: test
> show collections
2016-05-11T22:33:46.302+0530 E QUERY Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on test to execute command { listCollections: 1.0 }",
"code" : 13
}
at Error (<anonymous>)
at DB._getCollectionInfosCommand (src/mongo/shell/db.js:646:15)
at DB.getCollectionInfos (src/mongo/shell/db.js:658:20)
at DB.getCollectionNames (src/mongo/shell/db.js:669:17)
at shellHelper.show (src/mongo/shell/utils.js:625:12)
at shellHelper (src/mongo/shell/utils.js:524:36)
at (shellhelp2):1:1 at src/mongo/shell/db.js:646
> db.auth({user:'user1', pwd:'test123'})
1
> use test
switched to db test
> db.collone.insert({name:'firstcollection'})
WriteResult({ "nInserted" : 1 })
> show collections
collone
system.indexes
> db.collone.find()
{ "_id" : ObjectId("5733669fb7d44cd444ebf028"), "name" : "firstcollection" }
> exit
bye
When i tried to do the authentication while starting the mongo shell, getting authentication failed error. See below:
$ ./mongo test -u 'user1' -p 'test123' --authenticationDatabase 'admin'
MongoDB shell version: 3.0.3
connecting to: test
2016-05-11T22:37:21.559+0530 E QUERY Error: 18 Authentication failed.
at DB._authOrThrow (src/mongo/shell/db.js:1266:32)
at (auth):6:8
at (auth):7:2 at src/mongo/shell/db.js:1266
exception: login failed
All this is just a POC that i'm trying to do.
Once it's success, my target is to connect from mongoose client(from Node.js app) to mongod.
The following command from a stackoverflow post can help me to set up connection from mongoose to mongod with auth.

Resources