How can I set TLS for Mongoose connection - mongodb

I'm trying to migrate my mongo database from Compose to IBM Cloud Databases for Mongo and in their documnetations (https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/): "With a new Databases for MongoDB deployment, you'll be provided with a replica set of two endpoints to connect to your database. Databases for MongoDB also uses a TLS certificate, so you'll need to configure your MongoDB application driver to accept two hosts and a TLS certificate"
How can I set the TLS certificate provided by IBM Cloud in Mongoose connection ?
Nothing I've tried worked :(
I can see my database if I'm using the IBM cli but from my node.js application I cannot connect to it
var mongoose = require('mongoose');
mongoose.Promise = Promise;
var uri="mongodb://admin:passSftgdsdfvrrdfs#host1-1231243242.databases.appdomain.cloud:32605,host2-1231243242,host1-1231243242/testDatabaseName?authSource=admin&replicaSet=replset"
myDb.db = mongoose.createConnection(uri, {
tls: true,
tlsCAFile:`076baeec-1337-11e9-8c9b-ae5t6r3d1b17` (this is the name of the certificate and is placed in the root)
// tlsCAFile: require('fs').readFileSync('041baeec-1272-11e9-8c9b-ae2e3a9c1b17') // I have also tried something like this
absolute nothing is working even the database is there
Please help me

I'm also facing same problem
this works for me
mongoose.connect(‘mongodb+srv://username:password#host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})

Try the following:
var key = fs.readFileSync('/home/node/mongodb/mongodb.pem');
var ca = [fs.readFileSync('/home/node/mongodb/ca.pem')];
var o = {
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
sslKey: key,
sslCert:key
},
user: '****',
pass: '****'
};
m.connect('mongodb://dbAddr/dbName', o)```

I did it locally, you need to install the tunnel first
$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name#server_ip_OR_server_url> -N
I managed to implement it as follows
const CERTIFICATE_PATH = 'rds-combined-ca-bundle.pem'
const certificateCA = CERTIFICATE_PATH && [fs.readFileSync(CERTIFICATE_PATH)];
const sslOptions = certificateCA
? ({
ssl: true,
tlsAllowInvalidHostnames: true,
sslCA: certificateCA,
user: MONGODB_USER,
pass: MONGODB_PASSWORD,
} as ConnectionOptions)
: {};
const options: ConnectionOptions = {
...sslOptions,
};
export const connectMongoDb = async (): Promise<void> => {
await mongoose.connect('mongodb://localhost:27017/test', options);
console.log('📊 Successfully connected to the database');
};
You need to set
MONGODB_USER
MONGODB_PASSWORD

Related

Connecting to Heroku Postgres from Auth0 results in: err no pg_hba.conf entry for host, no encryption

I'm trying to connect to my PostgreSQL database hosted on Heroku through Auth0's Database Connections.
I am getting an error when I try to invoke the Get User script within Auth0's database actions:
no pg_hba.conf entry for host "xx.xxx.xx.x", user "xxx", database "xxx", no encryption
The script looks like this:
function loginByEmail(email, callback) {
const postgres = require('pg');
const conString = configuration.DATABASE_URL;
postgres.connect(conString, function (err, client, done) {
if (err) return callback(err);
const query = 'SELECT id, nickname, email FROM organizations WHERE email = $1';
client.query(query, [email], function (err, result) {
done(); // Close the connection to the database
if (err || result.rows.length === 0) return callback(err);
const user = result.rows[0];
return callback(null, {
user_id: user.id,
nickname: user.nickname,
email: user.email
});
});
});
}
Connection String:
configuration.DATABASE_URL: 'postgres://xxx:xxx#xxx?sslmode=require'
I appended sslmode=require to the end of my connection string to ensure I have a SSL connection to my database.
I have also tried changing sslmode=require to ssl=true, which results in a different error:
self signed certificate
I am unsure where to go from here, so any help would be appreciated.
You should first establish the client and specify the rejectUnauthorized flag, like so:
const client = new postgres.Client({
connectionString: conString,
ssl: { sslmode: 'require', rejectUnauthorized: false }
});
Then, instead of using your postgres to connect, use the client:
client.connect();
client.query(...);
This should solve your problem, and the connection will be encrypted. You won't, however, be protected against Man-In-The-Middle (MITM) attacks, as specified in documentation.
#Pexers solution worked for me, however, somehow it shows TypeScript error. The way I did it is just ssl: true:
const client = new postgres.Client({
connectionString: conString,
ssl: true
});

Pipedream's MongoDB API connection not working?

https://www.pipedream.com has an UI-assisted integration with MongoDB. It requires 4 values to connect to the API:
$username
$password
$database
$hostname
my default connect to app connection string is: mongodb+srv://<username>:<password>#cluster0.45xcf.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
(yes, I'm using the default cluster0 and myFirstDatabase values here)
I get back this error response:
MongoAPIError
URI must include hostname, domain name, and tld
DETAILS
at null.resolveSRVRecord (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/connection_string.js:51:25)
at null.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/operations/connect.js:32:57)
at null.null (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:127:35)
at null.maybePromise (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/utils.js:409:5)
at MongoClient.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:126:41)
at Function.connect (/tmp/ee/c_m4fDxGe5/node_modules/.pnpm/mongodb#4.5.0/node_modules/mongodb/lib/mongo_client.js:190:36)
at Object.run (/steps/mongodb.js:19:38)
at global.executeComponent (/var/task/launch_worker.js:171:53)
at MessagePort.messageHandler (/var/task/launch_worker.js:653:28)
I'm trying to connect to the API with:
$username = {REDACTED}
$password = {REDACTED}
$database = myFirstDatabase
$hostname = cluster0
and it's not able to connect, but it does work connecting via mongosh, Compass, etc
here's the full Node.js code Pipedream uses to connect to MongoDB's API:
module.exports = defineComponent({
props: {
mongodb: {
type: "app",
app: "mongodb",
}
},
async run({steps, $}) {
const MongoClient = require('mongodb').MongoClient
const {
database,
hostname,
username,
password,
} = this.mongodb.$auth
const url = `mongodb+srv://${username}:${password}#${hostname}/test?retryWrites=true&w=majority`
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = client.db(database)
// Enter your target collection as a parameter to this step
this.res = await db.collection(params.collection).insertOne({ name: "Luke Skywalker" })
await client.close()
},
})
Just don't understand why it won't connect. I can confirm the username and password aren't the problem.
I had a similar error message and it was a red herring.
The hostname needed to be the whole thing; cluster0.xx0xx.mongodb.net in my case, and I had the password wrong.

MongoDB connection error in Digital Ocean droplet

I am in the process of deploying my MERN app to a Digital Ocean droplet (Ubuntu 20.04 server).
I have cloned my GitHub repo to the droplet, installed the dependencies using npm install. Next, when I am starting the server using npm start, I get the following error:
The error essentially says that the first parameter to mongoose.connect() is undefined and must be a string. However, everything works fine in my local machine and when I console.log process.env.MONGO_URI, I get the connection string.
server/config/db.js
const mongoose = require("mongoose");
const colors = require("colors");
const dotenv = require("dotenv");
dotenv.config();
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
console.log(`MongoDB connected: ${conn.connection.host}`.cyan.bold);
} catch (error) {
console.error(`Error: ${error.message}`.red.bold.underline);
process.exit(1);
}
};
2;
module.exports = connectDB;
Why am I getting this error while starting the server in my Digital Ocean droplet?
dotenv doesn't load system variables.
Create .env file with
MONGO_URI=XXXXXXX
https://github.com/motdotla/dotenv#usage
Create a .env file in the root directory of your project. Add
environment-specific variables on new lines in the form of NAME=VALUE.
For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

I can not connect to monogdb with mongoose when authorization enabled

I am trying to connect with MongoDB by mongoose. Everything was ok, when I was connecting with my local db where there is no authentication.
When I've tried to connect to other DB with set admin user and credentials, I've got error and I've tried various different options but without any positive result.
I use these versions:
"mongodb": "^3.3.2",
"mongoose": "^5.7.1"
And my server side technology is node.js
I've tried these options:
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}?authSource=admin`,
{ useNewUrlParser: true, useUnifiedTopology: true });
then I've tried this:
let options = {
"auth": { "authSource":"admin"},
"user": "SVSAdmin",
"pass":"8&PG2DCUuDPvy$hx",
"useUnifiedTopology": true,
"useNewUrlParser": true
};
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}, options);
and this:
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=SCRAM-SHA-1')
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=MONGODB-CR')
and also this:
mongoose.connect('mongodb://user:password#host/yourDB?authSource=admin&w=1')
but it does not work. My credentials are ok.
The error message is:
{
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
Maybe important thing is that I'm connecting with db by ssh
I would be grateful for any help.
If u are using ur database remotly then u can use it via IP.
db = mongodb://52.221.52.32/DataBaseName

How do I connect to a MongoDB Database using SSL with Loopback

I am trying to connect to a MongoDB Database in Rackspace w/ SSL using loopback, but it's not working. It seems to connect fine; if I enter wrong credentials (on purpose) I get an error message saying "Can't connect", but when I use the correct credentials no error shows so I THINK I'm connecting fine. But when I try to query the database it always timesout, any idea whats happening?
My datasources.json looks something like:
"db": {
"name": "mongodb",
"url": "mongodb://username:password#iad-mongos2.objectrocket.com:port/dbName?ssl=true",
"debug": true,
"connector": "mongodb"
}
I keep reading things about needing a certificate file, but not sure if that applies in this case.
Any help would be greatly appreciated!
use datasources.env.js as below
var cfenv = require('cfenv');
var appenv = cfenv.getAppEnv();
// Within the application environment (appenv) there's a services object
var services = appenv.services;
// The services object is a map named by service so we extract the one for MongoDB
var mongodb_services = services["compose-for-mongodb"];
var credentials = mongodb_services[0].credentials;
// Within the credentials, an entry ca_certificate_base64 contains the SSL pinning key
// We convert that from a string into a Buffer entry in an array which we use when
// connecting.
var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];
var datasource = {
name: "db",
connector: "mongodb",
url:credentials.uri,
ssl: true,
sslValidate: false,
sslCA: ca
};
module.exports = {
'db': datasource
};
http://madkoding.gitlab.io/2016/08/26/loopback-mongo-ssl/
https://loopback.io/doc/en/lb3/Environment-specific-configuration.html#data-source-configuration
Create a Datasource using lb4 datasource command, edit the datasource generated by adding the SSL details to the config object: 'ssl', 'sslvalidated', 'checkserverIdentity, sslCA, sslKey etc.
import fs from 'fs';
import path from 'path';
const ca = fs.readFileSync(
path.join(__dirname, '../../utils/certs/mongodbca.cert'),
'utf8',
);
const config = {
name: 'test_db',
debug: true,
connector: 'mongodb',
url: false,
host:'hostname',
port: port,
user: 'user',
password: 'password',
database: 'databasename',
authSource: 'admin',
useNewUrlParser: true,
ssl: true,
sslValidate: true,
checkServerIdentity: false,
sslCA: [ca],
};
This worked for me, You can monkey patch the Mongo.connect() function by which you can add the option parameter.
Make a boot script file which can use the MongoDB option parameters of SSL certificate to make a secured connection to MongoDB, below code snippet, is written in a boot script js.
//Below code is written in a boot script
var monog_cert_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
var monog_ca_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/rootCA.pem'));
var monog_key_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
const mongoOptions = {
ssl: true,
sslValidate: false,
sslCA:monog_ca_file,
sslKey:monog_key_file,
sslCert:monog_cert_file,
authSource:"auth_db_name"
};
//Patching Mongo connect For option variable
const mongodb = require('mongodb').MongoClient;
const ogConnect = mongodb.connect;
const connectWrapper = function(url,cb) {
return ogConnect(url, mongoOptions, cb);
}
mongodb.connect = connectWrapper;
//Patching Mongo connect For option variable
use datasources.json as below
app_db: {
"host": "127.0.0.1",
"port": 27017,
"database": "test",
"name": "app_db",
"username": "youruser",
"password": "yourpassword",
"connector": "mongodb",
"ssl":true,
"server": {
"auto_reconnect": true,
"reconnectTries": 100,
"reconnectInterval": 1000,
"sslValidate":false,
"checkServerIdentity":false,
"sslKey":fs.readFileSync('path to key'),
"sslCert":fs.readFileSync('path to certificate'),
"sslCA":fs.readFileSync('path to CA'),
"sslPass":"yourpassphrase if any"
}
username,
password,
auto_reconnect,
tries and interval all are optional.
use below link to get the certificates using OpenSSL
https://docs.mongodb.com/manual/tutorial/configure-ssl/