Mongo authentication fail or invalid connection string - node.js

Using "mongoose": "^5.4.21", and Mongo Atlas, I can not seem to connect to my database in my node.js application
I tried to encode my connection string but that gives me Invalid connection string, if I remove encodeURIComponent I get authentication failed
mongoose.connect(encodeURIComponent("mongodb+srv://name:}Izu#[{!6o#cluster-oxzyp.mongodb.net/"), { dbName: "website", useNewUrlParser: true });

You can separate the username and password part of the connecting URI into the options section as shown below:
mongoose.connect("mongodb+srv://cluster-oxzyp.mongodb.net", {
user: 'name', //assuming this is your username
pass: '}Izu#[{!6o', //assuming this is your password
dbName: "website",
useNewUrlParser: true
});
This is probably happening due to the presence of # character in your password. Or you can try doing it like below:
mongoose.connect(`mongodb+srv://name:${encodeURIComponent('}Izu#[{!6o')}#cluster-oxzyp.mongodb.net/`, {
user: '',
pass: '',
dbName: 'website',
useNewUrlParser: true });

Related

Failed to connect to *name_server* - getaddrinfo ENOTFOUND

When connecting to the database with sequelize-typescript, an error occurs
Failed to connect to SERVER\SQL2016:1433 - getaddrinfo ENOTFOUND SERVER\SQL2016
Connection settings
import { Sequelize } from 'sequelize-typescript'
import { environment } from '../config'
import { normalize, join } from 'path'
export default new Sequelize({
database: environment.database.database,
dialect: "mssql",
username: environment.database.username,
// port: environment.database.port,
password: environment.database.password,
host: environment.database.host,
logging: !environment.production ? console.log : false,
models: [normalize(join(__dirname, "..", "models"))],
dialectOptions: {
options: {
enableArithAbort: true,
cryptoCredentialsDetails: {
minVersion: "TLSv1",
},
},
},
})
interface DatabaseConnection {
database: string
username: string
port: number
password: string
host: string
hostAsodu: string
databaseAsodu: string
}
export const environment: Environment = {
port: process.env.PORT ? Number(process.env.PORT) : 3030,
production: process.env.NODE_ENV === "production",
database: {
database: process.env.DB_DATABASE ?? String(),
username: process.env.DB_USERNAME ?? String(),
port: process.env.DB_PORT ? Number(process.env.DB_PORT) : 0,
password: process.env.DB_PASSWORD ?? String(),
host: process.env.DB_HOST ?? String(),
hostAsodu: process.env.DB_HOST_ASODU ?? String(),
databaseAsodu: process.env.DB_DATABASE_ASODU ?? String()
},
}
I tried connectit with and without a port, the error is the same. It just connects to SERVER, but does not want to connect to the named SERVER \ SQL2016. How can I fix this error? Found nothing on the docks
ENOTFOUND is an operating-system-level error from your OS's networking code. It means you asked it to look up a hostname and it came up with nothing. In the lingo, your name "could not be resolved." (www.stackoverflow.com is a hostname, for example. https://www.stackoverflow.com is a URL, which happens to contain a hostname.)
getaddrinfo() is OS method that asks the domain name service (DNS) to look up a hostname.
It looks to me like you tried to look up the hostname SERVER\SQL2016. That's not a hostname. You probably want something like sql2016.example.com instead. Ask the person who operates that SQL Server instance for the correct hosthame.
The SQL Server instance I use has a hostname something like devdatabase.dev.example.com.
Edit The SQL2016 part of your connection string is known as the server instance or DataSource. You need to specify it separately from the hostname. See this. Error connecting to SQL Server database with sequelize You also need to make sure your SQL Server software is configured to allow TCP connections.
Try this as you connect.
export default new Sequelize({
database: environment.database.database,
dialect: "mssql",
username: environment.database.username,
// port: environment.database.port,
password: environment.database.password,
host: environment.database.host, /* should be the hostname without \SQL2016 */
logging: !environment.production ? console.log : false,
models: [normalize(join(__dirname, "..", "models"))],
dialectOptions: {
instanceName: 'SQL2016',
options: {
enableArithAbort: true,
cryptoCredentialsDetails: {
minVersion: "TLSv1",
},
},
},
})

How to add an SSL certificate (ca-cert) to node.js environment variables in order to connect to Digital Ocean Postgres Managed Database?

I am currently using node-postgres to create my pool. This is my current code:
const { Pool } = require('pg')
const pgPool = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
port: process.env.PGPORT,
ssl: {
rejectUnauthorized: true,
// Would like to add line below
// ca: process.env.CACERT,
},
})
I found another post where they read in the cert using 'fs' which can be seen below.
const config = {
database: 'database-name',
host: 'host-or-ip',
user: 'username',
password: 'password',
port: 1234,
// this object will be passed to the TLSSocket constructor
ssl: {
ca: fs.readFileSync('/path/to/digitalOcean/certificate.crt').toString()
}
}
I am unable to do that as I am using git to deploy my application. Specifically Digital Oceans new App Platform. I have attempted reaching out to them with no success. I would prefer not to commit my certificate in my source control. I see a lot of posts of people suggesting to set
ssl : { rejectUnauthorized: false}
That is not the approach I want to take. My code does work with that but I want it to be secure.
Any help is appreciated thanks.
Alright I finally was able to figure it out. I think the issue was multiline and just unfamiliarity with dotenv for my local developing environment.
I was able to get it all working with my code like this. It also worked with the fs.readFileSync() but I didn't want to commit that to my source control.
const { Pool } = require('pg')
const fs = require('fs')
const pgPool = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
port: process.env.PGPORT,
ssl: {
rejectUnauthorized: true,
// ca: fs.readFileSync(
// `${process.cwd()}/cert/ca-certificate.crt`.toString()
// ),
ca: process.env.CA_CERT,
},
})
.on('connect', () => {
console.log('connected to the database!')
})
.on('error', (err) => {
console.log('error connecting to database ', err)
})
Now in my config.env I had to make it look like this:
CA_CERT="-----BEGIN CERTIFICATE-----\nVALUES HERE WITH NO SPACES AND A \n
AFTER EACH LINE\n-----END CERTIFICATE-----"
I had to keep it as a single line string to have it work. But I was finally to connect with
{rejectUnauthorized:true}
For the digital ocean app platform environment variable, I copied everything including the double quotes and pasted it in there. Seems to work great. I do not think you will be able to have this setting set to true with their $7 development database though. I had to upgrade to the managed one in order to find any CA cert to download.

Mongoose throwing `Authentication failed`

I am using Mongoose Ver:4.3
I am able to connect to mongoDb using Studio3T mongo client.
But getting an authentication error when trying to connect using Mongoose within NodeJs.
My code looks as below:
const sslOptions = {
server: {
sslValidate: false,
ssl: true,
sslCert: certFileBuf,
sslKey: certFileBuf,
checkServerIdentity: false,
sslPass: 'mysslPass',
},
user: 'myUser',
pass: 'myPass'
};
connName = mongoose.createConnection("mongodb://server.com:27017/db1?tls=true&authSource=db1", sslOptions);
The above throwing an error:
mongodb\node_modules\mongoose\node_modules\mongodb\lib\utils.js:98
process.nextTick(function() { throw err; });
^
Error [MongoError]: Authentication failed.
set username and password in url
connName = mongoose.createConnection("mongodb://myUser:myPass#server.com:27017/db1?tls=true&authSource=db1", {
sslValidate: false,
ssl: true,
sslCert: certFileBuf,
sslKey: certFileBuf,
checkServerIdentity: false,
sslPass: 'mysslPass',
});

Nodejs connect to Redshift using temporal credentials error

I'd like to connect to Redshift using temporal credentials.
I'd tried connecting with master username and password and it works fine. The problem of the temporal credentials is the username that is following format:
username: 'IAM:awsuser'.
So I think the connection is not understanding correctly the ":". So it always through invalid password. I have try this username and password from the Redshift query-editor and it connects without any problem.
This is the configuration I'm using:
const configRed = {
host: 'redshift-cluster-name.aaaaaaa.eu-west-1.redshift.amazonaws.com',
user: 'IAM:awsuser',
password: data.DbPassword,
database: 'dev',
port: 5439,
idleTimeoutMillis: 0,
max: 10000
};
redshiftPool = new psql.Pool(configRed);
redshiftCon = await redshiftPool.connect();
I have also tried using the username with encodeURIComponent:
user: encodeURIComponent('IAM:awsuser'),
It through next error:
"errorMessage": "password authentication failed for user \"IAM:awsuser\"",
Could be possible to change the connection URL in the PG library, for some custom URL like:
jdbc:redshift:iam://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev
Specifying "ssl: true" in the params argument when creating the Pool object indeed works:
const configRed = {
host: 'redshift-cluster-name.aaaaaaa.eu-west-1.redshift.amazonaws.com',
user: 'IAM:awsuser',
password: data.DbPassword,
database: 'dev',
port: 5439,
idleTimeoutMillis: 0,
max: 10000,
ssl: true
};

Node.js mssql error: tedious deprecated The default value for `config.options.enableArithAbort` will change from `false` to `true`

I get the error below. How do I fix it?
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
Change your database config options to the following:
var config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'databasename',
"options": {
"encrypt": true,
"enableArithAbort": true
}
};
read issue details here: https://github.com/tediousjs/node-mssql/issues/976
The following worked for me :
const config = {
user: 'sa',
password: '<YOUR_PASSWORD>',
server: '<COMPUTER_NAME>\\SQLEXPRESS',
database: '<DBNAME>',
requestTimeout: 180000, // for timeout setting
connectionTimeout: 180000, // for timeout setting
"options": {
"encrypt": false, // need to stop ssl checking in case of local db
"enableArithAbort": true
}
}
According to tedious docs
and
SET ARITHABORT
enableArithAbort: true // Ends a query when an overflow or divide-by-zero error occurs during query execution.
encrypt: true, // A boolean determining whether or not the connection will be encrypted. Set to true if you're on Windows Azure.
instead of setting in config in your project, set the value in node_modules
node_modules/sequelize/lib/dialects/mssql/connection-manager.js.
options: {
enableArithAbort: true,//<----------set this to true
port: parseInt(config.port, 10),
database: config.database,
trustServerCertificate: true
}

Resources