How to connect PostgreSQL Database to Cypress 10+ , no pg_hba.conf entry error - postgresql

When I try to connect and query on my PostgreSQL database, I keep getting a cypress error: “no pg_hba.conf entry for host “ user “postgres”, database “postgres”, SSL off”. How do I solve the error. Is this an issue with code or with the database?
this is my cypres.config.js file:
const pg = require("pg")
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on("task", {
//create a task - take two parameters - first being a config and second is sql
READFROMDB({ dbConfig, sql }) {
//create a client using the config argument
const client = new pg.Pool(dbConfig)
//return thw result from sql
return client.query(sql)
}
})
},
DB:{
database: "<name>",
user: "<name>",
password: "<pw>",
host: "<hostname>.amazonaws.com", //not localhost
port: 5432,
dialect: "postgres",
dialectOptions: {
ssl: {
require: true, // This will help you. But you will see nwe error
rejectUnauthorized: false // This line will fix new error
}
}
}
}
})
This is my test:
cy.task("READFROMDB",{
//get config from db
dbConfig: Cypress.config('DB'),
//SQL we want to perform
sql: 'select * from user where user=\'Phoebe\''
}).then((result)=>{
console.log(result.rows)
})

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
});

Heroku Postgres - The server does not support SSL connections

I have been working on an small app and connecting with Heroku PostgreSQL, for many days was working right but now is showing me this SSL error
The server does not support SSL connections
I have been looking for solutions but I cannot find anything that works for me, my code is:
import pg from 'pg'
import db from '../config.js'
const pool = new pg.Pool({
host: db.host,
database: db.database,
user: db.user,
port: db.port,
password: db.password,
ssl: { rejectUnauthorized: false },
})
export default function query(text, params) {
return pool.query(text, params)
}
Try changing it from Pool to Client and then using that to connect and query.
async function get(){
const client = new pg.Client({
ssl: {
rejectUnauthorized: false
},
user: ...,
password: ...,
port: ...,
host: ...,
database: ...
});
client.connect();
const response = await client.query(`SELECT * FROM ...;`)
return response.rows
}
Double check your values in the Heroku database.
Also, in production, you should just need
const client = new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
}
The first set of code is for local connection to your db.
One last note, I would put your user, password, etc... into a .env file and don't commit that to your repo.
UPDATE:
You can also put this into a config file like ./db.config.js as the following
const pg = require('pg')
module.exports =
process.env.DATABASE_URL
?
new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
})
:
new pg.Client({
// connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
port: process.env.DATABASE_PORT,
host: process.env.DATABASE_HOST,
database: process.env.DATABASE
})
So if it is in production, it will use the database url, and if there is none (which is local) then it will use the username password connection.

Can't solve an error "✖ Database connection failed! Check your typeORM config file. "

I’m trying to connect to RDS and seed data.
ormconfig.js
const entities = process.env.NODE_ENV === 'test' ? ['./src/**/**/*.ts'] : ['./dist/**/**/*.js'];
const logging = process.env.NODE_ENV !== 'test';
module.exports = {
type: 'postgres',
host: 'rds.ap-northeast-1.rds.amazonaws.com',
port: 5432,
username: 'postgres',
password: 'password',
database: 'db',
synchronize: true,
migrationsRun: false,
logging,
migrations: [`${__dirname}/dist/migration/*.js`],
entities,
};
// # sourceMappingURL=ormconfig.js.map
Error
✖ Database connection failed! Check your typeORM config file.
RDS is running for sure and all the values of DB are from AWS Secrets Manager, so they are correct.
Why is this happening?

deno connect to mongodb

I've tried to follow this tutorial https://www.youtube.com/watch?v=VF38U2qd27Q, but to no avail.
I realised that the syntax in the video already obsolete for example connectWithUri to become connect.
but when I tried to connect to mongo using deno_mongo with the latest docs, it still not working.
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
Then I found another library denodb but again can't connect to mongodb:
import { Database } from 'https://deno.land/x/denodb/mod.ts';
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
this.db = new Database('mongo', {
uri: dbString,
database: mongoDB
});
the error message:
error: Uncaught AssertionError
deno | throw new AssertionError(msg);
deno | ^
deno | at assert (asserts.ts:152:11)
deno | at MongoClient.database (client.ts:48:5)
deno | at new connectDB (connectDB.ts:35:23)
which part is wrong?
Looking at the deno_mongo README on GitHub.
For a local database you should use
//Connecting to a Local Database
await client.connect("mongodb://localhost:27017");
And if you are connecting to Mongo Atlas Database (and probably any other remote database) you should use:
//Connecting to a Mongo Atlas Database
await client.connect({
db: "<db_name>",
tls: true,
servers: [
{
host: "<db_cluster_url>",
port: 27017,
},
],
credential: {
username: "<username>",
password: "<password>",
db: "<db_name>",
mechanism: "SCRAM-SHA-1",
},
});
FYI
If you are using Mongo Atlas make sure to split up the connection string you get from 'Connection Wizard' in the Mongo Atlas dashboard over 3 (or how many replicas you have) entries in the server array. Like this:
servers: [
{
host: this.dbUrl1, // e.g. <name-of-cluster>-00-00.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl2, // e.g. <name-of-cluster>-00-01.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl3, // e.g. <name-of-cluster>-00-02.fbnrc.mongodb.net
port: 27017,
}
]
You get the connection string by:
Click 'Clusters' under Data storage (left side of the screen)
Click 'Connect' button
Click 'Connect to Application'
Select Driver: 'Node.js' and Version: '2.2.12 or later'
Connection string is displayed below. The servers are listed in a comma separated manner like this:
...<name-of-cluster>-00-00.fbnrc.mongodb.net:27017,<name-of-cluster>-00-01.fbnrc.mongodb.net:27017,<name-of-cluster>-00-02.fbnrc.mongodb.net:27017...
FYI-2
Make sure the master replica is listed first in the server array. Because if you want to do insertions into the database the master replica should be targeted. For me this was the 2nd mongo url, therefore the following server array worked for me:
servers: [
{
host: this.dbUrl2,
port: 27017,
},
{
host: this.dbUrl1,
port: 27017,
},
{
host: this.dbUrl3,
port: 27017,
}
]
the below code is working for me.
import { DataTypes, Database, Model } from 'https://deno.land/x/denodb/mod.ts';
const db = new Database('mongo', {
host: 'mongodb://localhost:27017',
username: '',
password: '',
database: 'DBMYAPP',
});
console.log(db)
I also faced the same issue while updating deno_mongo to the latest version. Use await to resolve client.connect method
Try this:
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
await client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
I had the same problem on windows 10, so try this
on your local mongodb:
await client.connect("mongodb://127.0.0.1:27017");

Typeorm Postgres ConnectionPool opening and closing for each request when using ssl

I am trying to establish a fixed connection pool using the typeorm for postgres in my rest service.
let option = {
name: 'default',
type: 'postgres',
host: 'host',
port: port,
username: 'username',
password: 'password',
database: 'database',
synchronize: true,
dropSchema: false,
logging: true,
ssl: {
ca: process.env.SSL_CERT,
},
entities: ['src/**/*.entity.ts'],
}
In app.ts
await createConnection(option).then(() => {
logger.debug('Database connection established');
}).catch((error: any) => {
logger.error('Database connection failed', error);
throw new Error(error);
});
When the app gets initialised the connectionpool gets established via ssl but it then closes, every time a query is executed the connection is created and then closed.
But without the ssl the connectionpool does not close until the .close method is called.
It would be helpful if someone could let me know on how to prevent the connectionpool from closing.
Or is there an option to set the time to live in ssl connection for postgres but I couldn't find reference for that in typeorm documentation.