Could not connect to mongod from mongo shell when auth enabled (on ubuntu) - node.js

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.

Related

Login problems connecting with SQL Server in nodejs

I'm working in osx with SQL Server using a docker image to be able to use it, running:
docker run -d --name sqlserver -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=myStrongPass' -e 'MSSQL_PID=Developer' -p 1433:1433 microsoft/mssql-server-linux:2017-latest
I can connect successfully in Azure Data Studio GUI with the following configuration
But the connection does not works in my nodejs code using mssql module.
const poolConnection = new sql.ConnectionPool({
database: 'myDbTest',
server: 'localhost',
port: 1433,
password: '*******',
user: 'sa',
connectionTimeout: 5000,
options: {
encrypt: false,
},
});
const [error, connection] = await to(poolConnection.connect());
The error always is the same:
ConnectionError: Login failed for user 'sa'
Is my first time working with SQL Server and is confusing for me the fact that I can connect correctly in the Azure Studio GUI but I can't do it in code.
I'm trying create new login users with CREATE LOGIN and give them privileges based on other post here in stackoverflow but nothing seems to work.
UPDATE:
I realize that i can connect correctly if i put master in database key.
Example:
const poolConnection = new sql.ConnectionPool({
database: 'master', <- Update here
server: 'localhost',
port: 1433,
password: '*******',
user: 'sa',
connectionTimeout: 5000,
options: {
encrypt: false,
},
});
1) Db that i can connect
2) Db that i want to connect but i can't.
Container error
2020-03-18 03:59:14.11 Logon Login failed for user 'sa'. Reason: Failed to open the explicitly specified database 'DoctorHoyCRM'. [CLIENT: 172.17.0.1]
I suspect a lot of people miss the sa password complexity requirement:
The password should follow the SQL Server default password policy, otherwise the container can not setup SQL server and will stop working. By default, the password must be at least 8 characters long and contain characters from three of the following four sets: Uppercase letters, Lowercase letters, Base 10 digits, and Symbols. You can examine the error log by executing the docker logs command.
An example based on: Quickstart: Run SQL Server container images with Docker
docker pull mcr.microsoft.com/mssql/server:2017-latest
docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=myStr0ngP4ssw0rd" -e "MSSQL_PID=Developer" -p 1433:1433 --name sqlserver -d mcr.microsoft.com/mssql/server:2017-latest
docker start sqlserver
Checking that the docker image is running (it should not say "Exited" under STATUS)...
docker ps -a
# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# af9f01eacab2 mcr.microsoft.com/mssql/server:2017-latest "/opt/mssql/bin/nonr…" 45 seconds ago Up 34 seconds 0.0.0.0:1433->1433/tcp sqlserver
Testing from within the docker container that SQL Server is installed and running...
docker exec -it sqlserver /opt/mssql-tools/bin/sqlcmd \
-S localhost -U "sa" -P "myStr0ngP4ssw0rd" \
-Q "select ##VERSION"
# --------------------------------------------------------------------
# Microsoft SQL Server 2017 (RTM-CU19) (KB4535007) - 14.0.3281.6 (X64)
# Jan 23 2020 21:00:04
# Copyright (C) 2017 Microsoft Corporation
# Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)
Finally, testing from NodeJS...
const sql = require('mssql');
const config = {
user: 'sa',
password: 'myStr0ngP4ssw0rd',
server: 'localhost',
database: 'msdb',
};
sql.on('error', err => {
console.error('err: ', err);
});
sql.connect(config).then(pool => {
return pool.request()
.query('select ##VERSION')
}).then(result => {
console.dir(result)
}).catch(err => {
console.error('err: ', err);
});
$ node test.js
tedious deprecated The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules/mssql/lib/tedious/connection-pool.js:61:23
{
recordsets: [ [ [Object] ] ],
recordset: [
{
'': 'Microsoft SQL Server 2017 (RTM-CU19) (KB4535007) - 14.0.3281.6 (X64) \n' +
'\tJan 23 2020 21:00:04 \n' +
'\tCopyright (C) 2017 Microsoft Corporation\n' +
'\tDeveloper Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)'
}
],
output: {},
rowsAffected: [ 1 ]
}
Hope this helps.

MongoDB production AUTH FAILED

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

Unable to execute nightwatch tests on chrome using Linux

Here's the bit in question from my nightwatch.json file :
"selenium" : {
"start_process" : true,
"server_path" : "lib/selenium-server-standalone.jar",
"log_path" : "test_logs"
},
"test_settings" : {
"jenkins" : {
"launch_url" : "url not disclosed",
"selenium_port" : 4444,
"selenium_host" : "jenkins.undisclosed-cloud.com",
"cli_args" : {
"webdriver.chrome.driver" : "/usr/local/bin/chromedriver"
},
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true,
"acceptSslCerts": true,
"platform" : "LINUX"
}
}
}
If I change the browserName to firefox then the test runs fine in the specified linux server, which is running on a DOCKER CONTAINER.
But when i choose chrome, i am getting the error:
Connection refused! Is selenium server started?
I've seen this error before on my local machine and managed to fix it by adding chromedriver to the path. I thought it would be the same issue on this linux server but it did not resolve it. I went on to the linux box and verified I can start the chromedriver directly in
"/usr/local/bin/chromedriver"
By the way I have verified I'm on 64-bit linux machine and the symlinks are all set.
Linux version: Linux 3.11.0-26-generic | v2.43.1 | r5163bce
ERROR LOG AFTER RUNNING TEST WITH --verbose
INFO Request: POST /wd/hub/session
- data: {"desiredCapabilities": {"browserName":"chrome","javascriptEnabled":true,"acceptSslCerts":true,"platform": "LINUX","name":"Free Resource Download Test"}}
- headers: {"Content-Type":"application/json; charset=utf-8","Content- Length":151}
ERROR Response 500 POST /wd/hub/session{ status: 13,
sessionId: null,
value:
{ message: 'chrome not reachable\n
So, this is a docker container and a problem is within Chrome&Docker.
you have 2 options, either run add "--privileged" parameter to a Docker or run Chrome with "--no-sandbox" argument.

AWS Cloudformation cloud-init on Amazon Linux AMI fails in util.py

I'm trying to have a userdata script in the NAT AMI provided by Amazon. The userdata script never starts execution and when I looked at the logs, I see that there's a failure at
Mar 10 21:34:13 cloud-init[2290]: util.py[DEBUG]: Failed running /var/lib/cloud/instance/scripts/part-001 [1]
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/cloudinit/util.py", line 638, in runparts
subp([exe_path], capture=False, shell=True)
File "/usr/lib/python2.6/site-packages/cloudinit/util.py", line 1529, in subp
cmd=args)
ProcessExecutionError: Unexpected error while running command.
Command: ['/var/lib/cloud/instance/scripts/part-001']
Exit code: 1
Reason: -
Stdout: ''
Stderr: ''
I found in this related StackOverflow Question that one user was able to get around it by having #!/bin/sh instead of #!/bin/sh -e -v in their UserData portion of the template, but the issue does not seem to have a clear solution.
I have tried using just #!/bin/bash, #!/bin/bash -xe and completely removing this line altogether. I still continue to hit that error.
Has anyone encountered this issue with the Amazon provided NAT AMI before and if so, how do I get around this issue?
My UserData looks like this:
"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash\n",
"sudo yum update -y aws-cfn-bootstrap\n",
"# Install the files and packages and run the commands from the metadata\n",
"sudo /opt/aws/bin/cfn-init -v --access-key ", { "Ref" : "IAMUserAccessKey" }, " --secret-key ", { "Ref" : "SecretAccessKey" },
" --stack ", { "Ref" : "AWS::StackName" },
" --resource NAT2 ",
" --configsets config ",
" --region ", { "Ref" : "AWS::Region" }, "\n"
]]}}
I was able to get around this issue. As Max had suggested, I removed sudo from the cfn-init command. But it did not have the desired effect.
But then, I realized that the environment variables EC2_HOME would not be setup for the sudo. I am doing a bunch of stuff in my configset which uses aws cli and for these to work, the EC2_HOME needs to be setup. So, I went in and removed sudo everywhere in my configset and UserData. So now, my UserData looks like:
"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash -xe\n",
"yum update -y aws-cfn-bootstrap\n",
"# Install the files and packages and run the commands from the metadata\n",
"/opt/aws/bin/cfn-init -v --access-key ", { "Ref" : "IAMUserAccessKey" }, " --secret-key ", { "Ref" : "SecretAccessKey" },
" --stack ", { "Ref" : "AWS::StackName" },
" --resource NAT2 ",
" --configsets config ",
" --region ", { "Ref" : "AWS::Region" }, "\n"
]]}}
For me I was trying to assign the Apache user to a file but we aren't using apache on this setup so the user didn't exist. This threw a CFN error. It was hard to track down the error but for anyone with this issue I suggest you view the logs here:
/var/log/cfn-init.log
and look for a traceback with an error message to help you debug.

Not authorized for query on admin.system.namespaces on mongodb

I start a new mongo instance, create a user, authorize it, but when I run "show collections", the system says that the id is not authorized. I do not know why?
# mongo admin
MongoDB shell version: 2.4.3
connecting to: admin
Server has startup warnings:
Thu May 23 18:23:56.735 [initandlisten]
Thu May 23 18:23:56.735 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
Thu May 23 18:23:56.735 [initandlisten] ** 32 bit builds are limited to less than 2GB of data (or less with --journal).
Thu May 23 18:23:56.735 [initandlisten] ** See http://dochub.mongodb.org/core/32bit
Thu May 23 18:23:56.735 [initandlisten]
> db = db.getSiblingDB("admin")
admin
> db.addUser({user:"sa",pwd:"sa",roles:["userAdminAnyDatabase"]})
{
"user" : "sa",
"pwd" : "75692b1d11c072c6c79332e248c4f699",
"roles" : [
"userAdminAnyDatabase"
],
"_id" : ObjectId("519deedff788eb914bc429b5")
}
> show collections\
Thu May 23 18:26:50.103 JavaScript execution failed: SyntaxError: Unexpected token ILLEGAL
> show collections
Thu May 23 18:26:52.418 JavaScript execution failed: error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:L128
> db.auth("sa","sa")
1
> show collections
Thu May 23 18:27:22.307 JavaScript execution failed: error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:L128
I had the same problem, but I found this tutorial and it helped me.
http://www.hacksparrow.com/mongodb-add-users-and-authenticate.html
use:
db.addUser('sa', 'sa')
instead of
db.addUser({user:"sa",pwd:"sa",roles:["userAdminAnyDatabase"]})
{
"user" : "sa",
"pwd" : "75692b1d11c072c6c79332e248c4f699",
"roles" : [
"userAdminAnyDatabase"
],
"_id" : ObjectId("519deedff788eb914bc429b5")
}
As Robert says, admin users has only rights to admin, not to write in databases.
So you have to create a custom user for your database. There's different ways. I have choose the dbOwner way.
(I use Ubuntu Server, mongo 2.6.3 and Robomongo)
So to do this, fisrt create your admin user like mongo says :
type mongo in your linux shell
and these command in the mongo shell :
use admin
db.createUser({user:"mongoadmin",pwd:"chooseyouradminpassword",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
db.auth("mongoadmin","chooseyouradminpassword")
exit
edit the mongo conf file with :
nano /etc/mongod.conf
You can use vi if nano is not installed.
activate authentication by uncommented/adding these line auth=true
if you want to use Robomongo from other machine change the line bind_ip=127.0.0.1 by bind_ip=0.0.0.0 (maybe you should add more protection in production).
type in linux shell :
service mongod restart
mongo
And in mongo shell :
use admin
db.auth("mongoadmin","pwd:"chooseyouradminpassword")
use doomnewdatabase
db.createUser({user:"doom",pwd:"chooseyourdoompassword",customData:{desc:"Just me as I am"},roles : [{role:"dbOwner",db:"doomnewdatabase"}]})
db.auth("doom","chooseyourdoompassword")
show collections
(customData is not required).
If you want to try if it works, type this in the mongo shell :
db.products.insert( { item: "card", qty: 15 } )
show collections
db.products.find()
Good luck ! Hope it will help you and others !
I have search this informations for hours.
I had the same problem and this is how I solved it:
db = db.getSiblingDB('admin')
db.addUser(
{ user: "mongoadmin",
pwd: "adminpass",
roles: ['clusterAdmin', 'userAdminAnyDatabase', 'readAnyDatabase'] } )
For MongoDB version 2.6 use:
db.createUser(
{
user: "testUser"
pwd: "password",
roles: [{role: "readWrite", db:"yourdatabase"}]
})
See the docs
I solved it like so
for mongoDB 2.6 + currently 3
db.createUser(
{
user: "username",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
)
note that for the role filed instead of userAdminAnyDatabase we use root
I would try granting the read role to the user. userAdminAnyDatabase grants the ability to administer users.

Resources