Postgres: Error 28P01 and non-asked user login - node.js

I have an NodeJS app that runs ok in my dev machine, but in production have a wierd behaviour: it asks for a user that I didn't call!
Here is my .env file:
PGUSER=postgres
PGHOST=my.domain
PGPASSWORD=my.passwd
PGDATABASE=my.dbase
PGPORT=5432
As I said, it runs ok in my machine but when I try to run it in my AWS Lighsail VPS it crashes:
/home/ubuntu/apps/bounce/node_modules/pg-protocol/dist/parser.js:287
const message = name === 'notice' ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
^
error: password authentication failed for user "ubuntu"
at Parser.parseErrorMessage (/home/ubuntu/apps/bounce/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/home/ubuntu/apps/bounce/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/home/ubuntu/apps/bounce/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/home/ubuntu/apps/bounce/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 102,
severity: 'FATAL',
code: '28P01',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '330',
routine: 'auth_failed'
}
The wierd thing: I didn't called "ubuntu" user in my code - I´m using "postgres", as in my .env file. I tried setting an user/passwd "ubuntu" and tested it , with PgAdmin and BeeKeeper - in booth apps I can access Postgres, but I couldn't do it through my Nodejs app hosted online.
My pg_hba.conf is here:
local all postgres peer
local all ubuntu trust
local all all md5
host all all 0.0.0.0/0 md5
And my connectin file is here:
require('dotenv').config();
const Pool = require('pg').Pool;
const conecta = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGDATABASE,
host: process.env.PGHOST,
port: process.env.PGPORT
});
module.exports = conecta;
Why it insists in "ubuntu" user? And why my NodeJS app can't connect if PgAdmin and BeeKeeper can?

Simple answer: use a literal call to the .env file inside config():
require('dotenv').config({ path: '/path/to/your/.env' });

Related

PG Pool: relation does not exist

I recently started coding in javascript. Been trying to use pg module to interact with my postgres db. But it keeps saying relation does not exist even though everything is okay and the table does exist. Any help will be appreciated.
const Pool = require('pg').Pool
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'test',
password: 'test#123',
port: '5432',
})
pool.query("SELECT * FROM clients", (error, results) => {
if (error) throw error
console.log(results)
})
module.exports = pool```
Error:
```error: relation "clients" does not exist
at Parser.parseErrorMessage (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\Maaz\Desktop\Code\acube_backend\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 106,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1384',
routine: 'parserOpenTable'
}

NodeJS/PostgreSQL Errors

I am setting up a Node app that has connections to multiple databases. I am using a map to create Pools for all my databases as such:
const stnPool = new Map();
async function getOtherDb(stnName){
if(!stnPool.has(stnName)){
stnPool.set(stnName, new Pool({
host: 'localhost',
database: stnName.toLowerCase(),
user: USERNAME,
password: PASSWORD,
port: 5432,
max: 2000,
idleTimeoutMillis: 0,
connectionTimeoutMillis: 0,
}))
}
return stnPool.get(stnName);
}
PostgreSQL currently has 10 'station' databases. I have 10 remote servers that connect to my server and upload data every 3 seconds. I also have an X number of clients that connect to view the uploaded data in realtime. Bot Server and Client connections connect to upload/request data via Websockets.
To establish aan query a Pool connection:
var uvDb = await db.getOtherDb("wx_uv")
if( uvDb != -1 ) {
const dbT = await uvDb.connect()
... do various db queries ...
dbT.release()
}
After a few hours of getting Server uploads and Client requests I get this error:
/.../node/node_modules/pg-protocol/dist/parser.js:287
const message = name === 'notice' ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
^
error: parallel worker failed to initialize
at Parser.parseErrorMessage (/.../node/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/.../node/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/.../node/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/.../node/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:365:28)
at addChunk (node:internal/streams/readable:314:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 163,
severity: 'ERROR',
code: '55000',
detail: undefined,
hint: 'More details may be available in the server log.',
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parallel.c',
line: '826',
routine: 'WaitForParallelWorkersToFinish'
}
Anyone have any ideas on what causes this?
=======UPDATE=======
Tried adding a try/catch to release the connection as well:
if( uvDb != -1 ) {
const dbT = await uvDb.connect()
try{
... do various db queries ...
dbT.release()
} catch (err) {
dbT.release()
}
}
But now I get other errors...
"error: lost connection to parallel worker"
"error: parallel worker failed to initialize"

Heroku, Node.js, PostgreSQL error: no pg_hba.conf entry for host

My Heroku app crash a week ago and I have been troubleshooting for 3 days with no success. Tried to change the connection code to ssl and also did some changes to pg_hba.conf and postgresql.conf files but no luck.
This is the error that keep coming up :
ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host "", user "", database "", SSL off
at /app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24
at Connection.connectingErrorHandler (/app/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:210:5)
at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:134:12)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:308:12)
at readableAddChunk (_stream_readable.js:289:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
name: 'SequelizeConnectionError',
parent: error: no pg_hba.conf entry for host "52.206.229.39", user "pirotuslftnuae", database "d7q6mo0trncmiq", SSL off
at Connection.parseE (/app/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/app/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:308:12)
at readableAddChunk (_stream_readable.js:289:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
name: 'error',
length: 167,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '496',
routine: 'ClientAuthentication'
},
const db = new Sequelize({
user: "name",
password: "****",
database: "databaseName",
port: 5432,
host: "localhost",
ssl: true,
dialect: 'postgres',
dialectOptions: {
"ssl": {"rejectUnauthorized": false}
}
});
# Database administrative login by Unix domain socket
local all postgres peer
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
# Allow rep
# - Connection Settings -
#listen_addresses = '*' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
port = 5432 # (change requires restart)
max_connections = 100 # (change requires restart)
#superuser_reserved_connections = 3 # (change requires restart)
unix_socket_director`enter code here`ie
I finally solve my issue with this ssl code in my database file
let config
if (process.env.DATABASE_URL) {
config = {
logging: false,
ssl: true,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
}
} else {
config = {
logging: false
}
}
const db = new Sequelize(
process.env.DATABASE_URL ||
`postgres://localhost:5432/${databaseName}`,
config
)

The db connection throws error in model unit test without explicit invoking

I am doing unit test on nodejs 12.x jest 25 app. When the unit test is started with npm test, at the end it throws an error about a startup file db.js which establishes db connection. Here is the db.js file:
const Sql = require("sequelize");
const db = new Sql('emps', 'postgres', `${process.env.DB_PASSWORD}`, {
host: 'localhost',
dialect: 'postgres',
port:5432,
} );
db
.authenticate() //<<<====this line causes the error
.then(() => {
console.log('DB connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = db;
Here is the error at the end of jest unit test:
console.error startup/db.js:32
Unable to connect to the database: ConnectionError [SequelizeConnectionError]: password authentication failed for user "postgres"
at C:\D\code\js\emps_bbone\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:182:24
at Connection.connectingErrorHandler (C:\D\code\js\emps_bbone\node_modules\pg\lib\client.js:194:14)
at Connection.emit (events.js:311:20)
at Socket.<anonymous> (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:134:12)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
name: 'SequelizeConnectionError',
parent: error: password authentication failed for user "postgres"
at Connection.Object.<anonymous>.Connection.parseE (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:614:13)
at Connection.Object.<anonymous>.Connection.parseMessage (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:413:19)
at Socket.<anonymous> (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:129:22)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
name: 'error',
length: 163,
severity: 'FATAL',
code: '28P01',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'd:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\libpq\\auth.c',
line: '336',
routine: 'auth_failed'
},
original: error: password authentication failed for user "postgres"
at Connection.Object.<anonymous>.Connection.parseE (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:614:13)
at Connection.Object.<anonymous>.Connection.parseMessage (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:413:19)
at Socket.<anonymous> (C:\D\code\js\emps_bbone\node_modules\pg\lib\connection.js:129:22)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
name: 'error',
length: 163,
severity: 'FATAL',
code: '28P01',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'd:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\libpq\\auth.c',
line: '336',
routine: 'auth_failed'
}
}
The db.js is required in app's index.js:
require("./startup/db");
Since my unit tests only test models (the db connection works fine. The problem is likely process.env.DB_PASSWORD didn't return a value somehow.), I don't quite understand how the db connection test jumps in by itself and throws error.

Unhandled rejection SequelizeConnectionError: password authentication failed for user "ankitj"

This happens even when the DB user specified in .env file is different. For the record "ankitj" is also the username of my system. I don't understand why this is happening.
Here's the error:
Unhandled rejection SequelizeConnectionError: password authentication failed for user "ankitj"
at connection.connect.err (/home/ankitj/Desktop/skillbee/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:128:24)
at Connection.connectingErrorHandler (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/client.js:140:14)
at Connection.emit (events.js:160:13)
at Socket.<anonymous> (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/connection.js:124:12)
at Socket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:599:20)
I'm assuming that you're getting this error using Sequelize with Node.js. I ran into the same error when I had the following:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
}
)
I was able to solve the issue by replacing it with a connection ur:
const sequelize = new Sequelize("postgres://postgres:postgres#localhost/gql", {
dialect: 'postgres'
// anything else you want to pass
})
where gql is the name of DATABASE in my .env file.
The user "ankitj" executes the command to run the Node script, so the script is trying to connect as that user. I first tried to solve this on the Postgres end by adding a user and granting permissions, but was unable to get that to work--I'd be interested in seeing that solution--but specifying a connection url worked for me.
I had the same issue when I was using the default password for the PostgreSQL. Try to change it from the command line as follows.
psql
\password
Then Enter a new password and update your .env files and that should Work.
Instead of using the process.env variables I put the actual names but wrapped in quotes (" ") and it's worked.
I have faced the same issue when I connect with NodeJS and Postgres SQL. I found a solution. We need to check db.config.js file(database config file) and index.js(where u called the const sequelize = new Sequelize(.......) properties name is matching or not.
// db.config.js
module.exports = {
user: '******',
host: 'localhost',
database: '***********',
password: '***',
port: 5432,
dialect: "postgres", // we need to implement
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
const Sequelize = require("sequelize");
const dbConfig = require("../config/db.config.js");
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
},
})
Mentioned the above params line as (dbConfig.database, dbConfig.user, dbConfig.password) we need to check with db.config.js file
Note: please add dialect properties on the db.config.js file.
Now Problem is solved...Thanks
Console verbiage log
I also had the same error but I solved it by using template strings
const sequelize = new Sequelize(`${process.env.DB_NAME}`, `${process.env.DB_USER}`, `${process.env.DB_PASSWORD}`, {
host: process.env.DB_HOST,
dialect: 'postgres'
});

Resources