MongoDB db.serverStatus() gives error when running using tunnel that is targeted to api.cloudfoundry.com - mongodb

Following is the console session...
C:\Users\xxx>vmc tunnel myMongoDB
Getting tunnel connection info: OK
Service connection info:
username : uuuu
password : pppp
name : db
url : mongodb://uuuu:pppp#172.30.xx.xx:25200/db
Starting tunnel to myMongoDB on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore
Which client would you like to start?: 2
Launching 'mongo --host localhost --port 10000 -u uuuu -p pppp db'
MongoDB shell version: 2.0.6
connecting to: localhost:10000/db
> db.serverStatus()
{ "errmsg" : "need to login", "ok" : 0 }
>
Which credentials should I use to login (assuming should use db.auth) to get rid of the error "{ "errmsg" : "need to login", "ok" : 0 }".
When I run the same in micro CF on my machine it works ok and gives me the expected output.
P.S. I'm trying this to get to know the current connections on my application, written in node.js. Trying to debug some issues with connections to the DB. If there is any other alternative that I can use please suggest that as well.

this should work! Not sure why your tunnel isn't connecting, my immediate suggestion is to try another instance of MongoDB and see if the same error occurs.
If you are trying to inspect the bound services on you node.js app you should be able to inspect them in the VCAP_SERVICES environment variable. For example;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env.VCAP_SERVICES));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
This code is currently running at http://node-headers.cloudfoundry.com/ to serve as an example. However, mongodb connections for node.js applications should automatically configure to the bound service. If this does not work for you, then please do let me know.

Related

IntelliJ Database explorer won't work with localhost Mongo 4.4.3

I'm up-the-middle MongoDB with authentication localhost. I have the mongod configured to bind a specific user to a specific database and from the mongo shell and my Java programs, everything works great. When I log in as that user I can do all the mongo stuff on the mongo db I bound that user to.
$ mongo -u totallyLegitUser --authenticationDatabase admin
MongoDB shell version v4.4.3
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2ba7a3f6-2ca1-49b7-8241-8133ceb3d842") }
MongoDB server version: 4.4.3
> use mfg-plan;
switched to db mfg-plan
> show collections;
activity
...
When I try to set up the same user through IntelliJ's "Database" thing, the "Test Connection" says everything is fine, but I can't run any queries through the console and the "explorer" drop down thing doesn't show collections I know are in the database.
This is what shows up when I look in the console after I've try to run the db.activity.findOne(); from the cli session...
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-256, userName='totallyLegitUser', source='mfg-plan', password=<hidden>, mechanismProperties=<hidden>} com.mongodb.MongoCommandException: Command failed with error 17 (ProtocolError): 'Attempt to switch database target during SASL authentication.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Attempt to switch database target during SASL authentication.", "code": 17, "codeName": "ProtocolError"}
I have confirmed that the username, password, and database are all correct.
How do I get IntelliJ to connect to my authenticating mongos?
Problem solved. In the "Data Sources and Drivers" dialog for my mongo hosts it asks for a Database. I was giving it the database I wanted to connect to on the host (mfg-plan). What it wants is the authenticationDatabase for the host (usually 'admin'). When I change that to 'admin', all is well.

Mongodb connectionString can't connect

I can connect via Mongodb COMPASS using my username and password but apparently i can't connect it to my website.
mongodb://localhost:27017/mydb works fine in connection string but not atlas/online cluster
{"connectionString":"mongodb+srv://myuser:mypass#thiscluster.azure.mongodb.net/mydb?retryWrites=true&w=majority"
,"secret":""}
Error :
Server listening on port 3000
Unhandled rejection MongoError: not authorized on admin to execute command { lis
tIndexes: "sessions", cursor: { } }
at Function.MongoError.create (C:\Users\user\Documents\GitHub\meanie\serv
er\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\user\Documents\GitHub\meanie\server\node_modul
es\mongodb-core\lib\cursor.js:212:36)
at C:\Users\user\Documents\GitHub\meanie\server\node_modules\mongodb-core
\lib\connection\pool.js:469:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)
I am using MEANIE STACK BLOG
Reference : Cloud mongodb guide
mongodb+srv://:#thiscluster.azure.mongodb.net/?retryWrites=true&w=majority
Other reference : https://docs.mongodb.com/manual/reference/connection-string/
SOLVED
config.json / node's "connectionString" can't be parsed using mongo+srv://user:pw#thiscluster.mongodb.com/mydb?thisoptions
node version i'm using is 2.2 12
fixed via :
"connectionString":"mongodb://user:pass#test-shard-00-00-sample.azure.mongodb.net:27017,test-shard-00-01-sample.azure.mongodb.net:27017,test-shard-00-02-sample.azure.mongodb.net:27017/THISDB?ssl=true&replicaSet=Test-shard-0&authSource=admin&retryWrites=true&w=majority",

Mongo DB 3.2 Authentication

I've just followed this guide on setting up Auth with Mongo DB, as well as this guide to get a user set up as an administrator.
Running mongo > use admin > show users prints the following:
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
After this, I run the server again with --auth and use the following command:
mongo -u "root" -p "xxx" --authenticationDatabase "admin"
This prints the following:
MongoDB shell version: 3.2.19
connecting to: test
2018-03-29T15:52:32.329+0200 E QUERY [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow#src/mongo/shell/db.js:1441:20
#(auth):6:1
#(auth):1:2
exception: login failed
Trying to run this without the --auth parameter lets me log in just fine.
The --auth parameter also gives me the following output in the server console:
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
But I'm actually unsure about why it isn't picking up any root/admin user I create. When trying to connect with Robo 3T, the terminal prints the following:
I NETWORK [initandlisten] connection accepted from xxx:44924 #2 (2 connections now open)
I ACCESS [conn2] SCRAM-SHA-1 authentication failed for root on admin from client xxx ; UserNotFound: Could not find user root#admin
I NETWORK [conn2] end connection xxx:44924 (1 connection now open
Solution by OP.
Issue fixed by following this article.
It seems that, despite using --auth when connecting to the server, by not commenting out the line bindIp: 127.0.0.1 and adding authorization: 'enabled' to the security section in /etc/mongod.conf, I was only allowing access to the local machine - the server itself. The error messages could have been worded a bit better, but that's security. I guess.
Whilst this was a very silly oversight, no documentation I had previously looked at had covered this issue.

MongoDB unable to connect to one MongoDB instance from another MongoDB instance using connect() Description

I am trying to access a MongoDB collection in my QA env from my Dev env. I am trying to achive something similar to
DBLink (Database Link) in Oracle.
MongoDB version = 3.4.4
RoboMongo = 0.9.0-RC10
Example of how i am trying to establish Database Link
[Note - my mongoDB Dev instance is not password protected]
Case 1 : Connect QA from DEV
Login to MongoDB Dev Instance in Robomongo and then run below query.
var db2 = connect('<SERVER_NAME>:<PORT>/<QA_DB_NAME>')
Output:-
connecting to: <SERVER_NAME>:<PORT>/<QA_DB_NAME>
Error: socket exception [CLOSED] for <SERVER_IP>:<PORT> :
connect#src/mongo/shell/mongo.js:226:14
#(shell):1:15
Case 2 : Connect DEV from QA
var db2 = connect('<SERVER_NAME>:<PORT>/<DEV_DB_NAME>', '<USERNAME>', '<PASSWORD>')
Login to MongoDB QA Instance in Robomongo and then run below query.
var db2 = connect(':/')
Output:-
connecting to: <SERVER_NAME>:<PORT>/<QA_DB_NAME>
Error: network error while attempting to run command 'isMaster' on host '<SERVER_NAME>:<PORT>' :
connect#src/mongo/shell/mongo.js:226:14
#(shell):1:15

MongoDB: set user/password to access to db

I'm trying to set password for mongodb to prevent access to db with empty login and pass (set by default).
I'm statring mongo server:
sudo ./mongod
Starting client:
./mongo
Setting password:
use admin
db.addUser("root", "root")
exit
The output is:
MongoDB shell version: 2.2.0
connecting to: test
> use admin
switched to db admin
> db.addUser("root", "root")
{
"user" : "root",
"readOnly" : false,
"pwd" : "2a8025f0885adad5a8ce0044070032b3",
"_id" : ObjectId("50c90b94e28c41a388104f64")
}
> exit
Hoever, wheh I try to auth with empty credentials (I use mViever admin UI), it still works. Otherwise, access with root/root is not avialable. What I'm doing wrong?
Also tried to start mongo server with -auth parameter, the same result:
./mongod -auth
UPD: After starting with -auth parameter can't login with any pass. Getting:
Thu Dec 13 03:27:38 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
Update: I dont know what's goin on...
> db.auth("root","root");
1
> ^C
bye
It can login. Let's restart ./mongod --auth and ./mongo:
MacBook-Pro-Ilya:bin ilyarusanen$ ./mongo
MongoDB shell version: 2.2.2
connecting to: test
> db.auth("root","root")
Error: { errmsg: "auth fails", ok: 0.0 }
0
> db.test.insert({"yeah":"2342"})
Fri Dec 14 08:52:05 uncaught exception: getlasterror failed: { "errmsg" : "need to login", "ok" : 0 }
> use admin
switched to db admin
> db.addUser("root","root")
Fri Dec 14 08:52:14 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
> db.auth("root","root")
1
Why at first it can login? Why after restarting mongo is not able to login? And why after FAILED attempt to addUser, it becomes able to login? Thanks.
UPDATE2: MongoHub seems to auth ok. However, from NodeJS I still can't login: I use such code:
mongo_db.open(function(err,data){
if(data){
data.authenticate("root", "root",function(err2,data2){
if(data2){
console.log("Database opened");
}
else{
console.log(err2);
}
});
} else {
console.log(err);
}
});
And I get:
{ [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }
But mention, MongoHub with same credentials works fine.
From your comment you mention that you are using mViewer. Version 0.9.1 of mViewer does not support authentication. According to this issue on the mViewer GitHub, this is resolved in version 0.9.2, which was targeted for release in Oct.
Before starting the node with authentication, log on to the node and add a user. Then start the node with --auth and connect to the shell without mViewer.
At this point you can connect to the admin database and authenticate your admin user:
use admin
db.auth('root', 'root')
Since you set up an admin user, which will have access to all the databases, you need to authenticate against the admin database. Once you have done this you will have access to all the databases. You will also be able to create new users on any database, or create new read only users for all the databases.
If you create a new user that has access to only one database, that user would need to use that database and db.auth(name, pass) against it.
If you create a new user that has read only access to all databases, they would use admin and then db.auth(name, pass) to gain their read only access to all databases
You can find more information on setting up authentication here and more information about setting up users here
Note: When you start a node without --auth then no authentication is enabled. This means you can connect with the shell and db.auth('root','root') but it won't do anything as far as access is concerned. MongoDB will not deny access to the databases without --auth command line option (--keyFile in sharded setups or replica sets)