CLOUD SQL -> Enable Allow SSL Connection -> Error The server doesn't support SSL connections - google-cloud-sql

`Hi Experts,
I am enabling Allow only SSL connection and with below knex configuration
`
const Knex = require('knex');
const fs = require('fs');
const createTcpPool = async config => {
const dbConfig = {
client: 'pg',
connection: {
host: process.env.INSTANCE_HOST, // e.g. '127.0.0.1'
port: process.env.DB_PORT, // e.g. '5432'
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
},
...config,
};
if (process.env.DB_ROOT_CERT) {
dbConfig.connection.ssl = {
rejectUnauthorized: false,
ca: fs.readFileSync(process.env.DB_ROOT_CERT), // e.g., '/path/to/my/server-ca.pem'
key: fs.readFileSync(process.env.DB_KEY), // e.g. '/path/to/my/client-key.pem'
cert: fs.readFileSync(process.env.DB_CERT), // e.g. '/path/to/my/client-cert.pem'
};
}
return Knex(dbConfig);
};
module.exports = createTcpPool;
`
and when i try to execute query with createTcpPool, I get an error that The server doesnt support SSL connection. I am not sure what i else I am missing

Related

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

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

naming and getting a particular connection in typeorm

Previously, typeorm seems to have allowed the use of a ConnectionManager that seems to have allowed to name a particular connection whilst creation and fetch/check the connection with the same name like this:
import { Connection, createConnection, getConnectionManager } from 'typeorm';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import * as tenantsOrmconfig from '../../tenants-orm.config';
export function getTenantConnection(tenantId: string): Promise<Connection> {
const connectionName = `tenant_${tenantId}`;
const connectionManager = getConnectionManager();
if (connectionManager.has(connectionName)) {
const connection = connectionManager.get(connectionName);
return Promise.resolve(connection.isConnected ? connection : connection.connect());
}
return createConnection({
...(tenantsOrmconfig as PostgresConnectionOptions),
name: connectionName,
schema: connectionName,
});
}
But, I'm confused now as to how to achieve this when I'm using a Datasource using a factory to create dynamic connection:
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const host = configService.get('MY_DB_HOST');
const port = parseInt(configService.get('MY_DB_PORT'));
const user = configService.get('MY_DB_USER');
const password = configService.get('MY_DB_PASSWORD');
const dbName = configService.get('MY_DB_NAME');
return {
type: 'postgres',
host: host,
port: port,
username: user,
password: password,
database: dbName,
entities: entities,
synchronize: true,
};
}
})
],
controllers: [AppController],
providers: [AppService],
})
I'm trying to fetch an existing connection from the connection pool which typeorm is supposed to manage by default if it already exists, and that connection is supposed to belong to a tenant if it exists, else it should create a new connection for the tenant. How do I do this with a Datasource?
I can see that there is a datasourceInstance.manager.find() method, but, that seems to take an Entity which seems to query the database, and I can't find anything more useful in the docs.

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.

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

How to connect knex.js to PostgresSQL database?

Hi i'am trying to connect a database to server.js with Knex.js i have tried to add user as postgresql and i tried also to add host as localhost but that didn't work an i always get
Below is when i list all the databases!
Failed to load resource: the server responded with a status of 400 (Bad Request)
Below is a snapshot of my error when i tries to register me!
Below is my register.js that should help with the reigistering to the database!
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister: handleRegister
};
Here is my server.js file below!
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : 'localhost',
user : 'postgres',
database : 'smartbrain1'
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
And here is my databases that i have created in postgreSQL in the terminal as a snapshot!
You should start by just trying to write standalone node app, that connects pg and runs a query. Then You can start integrating with other parts of your app when you know that connecting DB works as expected. Now the question has way too much irrelevant information.
First try to connect your SQL server from shell without using UNIX socket, but with TCP:
psql postgres://postgres#localhost/smartbrain1
If that fails, it probably means that your database is configured so that it does not allow any external TCP connections.
To allow access from localhost to postgres this should do it in pg_hba.conf by setting
host all all 127.0.0.1/32 trust
Also you may need to add password for your postgres user and try connecting with password enabled:
psql postgres://postgres:<password>#localhost/smartbrain1
When connecting from command line works you can try something like this in knex config:
const db = knex({
client: 'pg',
connection: 'postgres://postgres:<password>#localhost/smartbrain1'
});
Some more info for debugging this is found here Knex:Error Pool2 - error: password authentication failed for user and probably in tens of other generic postgres database connection problem questions.