External database with PGPASS file not working
Please note that security bugs or issues should be reported to [email protected].
Describe the bug
I have a file mounted in my container, which contains the password. I have verified i can cat the content of the file, and get the password.
Following the documentation, it states :
# External Database Settings
#
# All configuration settings are stored by default in the SQLite database.
# In order to use external databases like PostgreSQL sets the value of
# CONFIG_DATABASE_URI like below:
# dialect+driver://username:password@host:port/database
#
# PostgreSQL:
# postgresql://username:password@host:port/database
# Specify Schema Name
# postgresql://username:password@host:port/database?options=-csearch_path=pgadmin
# Using PGPASS file
# postgresql://username@host:port?options=-csearch_path=pgadmin
I have deployed pgadmin with the following connection variables:
- name: PGADMIN_CONFIG_CONFIG_DATABASE_URI
value: postgresql://[email protected]/pgadmin
- name: PGPASSFILE
value: /var/lib/pgadmin/storage/pgadmin/prd.pgpass
To Reproduce
Steps to reproduce the behavior:
- Mount the password into a pgpass file
- Set the env vars as above
- See the error in the log
Expected behavior
I expected the program to use the PGPASSFILE var to fetch the password.
Error message
postfix/postlog: starting the Postfix mail system
[2023-09-06 11:21:36 +0000] [1] [INFO] Starting gunicorn 20.1.0
[2023-09-06 11:21:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1)
[2023-09-06 11:21:36 +0000] [1] [INFO] Using worker: gthread
[2023-09-06 11:21:36 +0000] [94] [INFO] Booting worker with pid: 94
2023-09-06 11:21:44,786: INFO pgadmin: ########################################################
2023-09-06 11:21:44,786: INFO pgadmin: Starting pgAdmin 4 v7.6...
2023-09-06 11:21:44,786: INFO pgadmin: ########################################################
2023-09-06 11:21:44,786: DEBUG pgadmin: Python syspath: ['/pgadmin4', '/venv/bin', '/pgadmin4', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/venv/lib/python3.11/site-packages', '/usr/lib/python3.11/site-packages']
WARNING: password file "/var/lib/pgadmin/storage/pgadmin/prd.pgpass" has group or world access; permissions should be u=rw (0600) or less
WARNING: password file "/var/lib/pgadmin/storage/pgadmin/prd.pgpass" has group or world access; permissions should be u=rw (0600) or less
[2023-09-06 11:21:45 +0000] [94] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 145, in __init__
self._dbapi_connection = engine.raw_connection()
^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 3288, in raw_connection
return self.pool.connect()
^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 452, in connect
return _ConnectionFairy._checkout(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 1267, in _checkout
fairy = _ConnectionRecord.checkout(pool)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 716, in checkout
rec = pool._do_get()
^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/impl.py", line 284, in _do_get
return self._create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 393, in _create_connection
return _ConnectionRecord(self)
^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 678, in __init__
self.__connect()
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 902, in __connect
with util.safe_reraise():
File "/venv/lib/python3.11/site-packages/sqlalchemy/util/langhelpers.py", line 147, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 898, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 637, in connect
return dialect.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/default.py", line 615, in connect
return self.loaded_dbapi.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/psycopg/connection.py", line 728, in connect
raise ex.with_traceback(None)
psycopg.OperationalError: connection failed: fe_sendauth: no password supplied
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
worker.init_process()
File "/venv/lib/python3.11/site-packages/gunicorn/workers/gthread.py", line 92, in init_process
super().init_process()
File "/venv/lib/python3.11/site-packages/gunicorn/workers/base.py", line 134, in init_process
self.load_wsgi()
File "/venv/lib/python3.11/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
self.wsgi = self.app.wsgi()
^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
return self.load_wsgiapp()
^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
return util.import_app(self.app_uri)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/gunicorn/util.py", line 359, in import_app
mod = importlib.import_module(module)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/pgadmin4/run_pgadmin.py", line 4, in <module>
from pgAdmin4 import app
File "/pgadmin4/pgAdmin4.py", line 104, in <module>
app = create_app()
^^^^^^^^^^^^
File "/pgadmin4/pgadmin/__init__.py", line 475, in create_app
run_migration_for_others()
File "/pgadmin4/pgadmin/__init__.py", line 460, in run_migration_for_others
db_upgrade(app)
File "/pgadmin4/pgadmin/setup/db_upgrade.py", line 25, in db_upgrade
flask_migrate.upgrade(migration_folder)
File "/venv/lib/python3.11/site-packages/flask_migrate/__init__.py", line 111, in wrapped
f(*args, **kwargs)
File "/venv/lib/python3.11/site-packages/flask_migrate/__init__.py", line 200, in upgrade
command.upgrade(config, revision, sql=sql, tag=tag)
File "/venv/lib/python3.11/site-packages/alembic/command.py", line 385, in upgrade
script.run_env()
File "/venv/lib/python3.11/site-packages/alembic/script/base.py", line 578, in run_env
util.load_python_file(self.dir, "env.py")
File "/venv/lib/python3.11/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file
module = load_module_py(module_id, path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/alembic/util/pyfiles.py", line 109, in load_module_py
spec.loader.exec_module(module) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/pgadmin4/pgadmin/setup/../../migrations/env.py", line 95, in <module>
run_migrations_online()
File "/pgadmin4/pgadmin/setup/../../migrations/env.py", line 79, in run_migrations_online
connection = engine.connect()
^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 3264, in connect
return self._connection_cls(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 147, in __init__
Connection._handle_dbapi_exception_noconnection(
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 2426, in _handle_dbapi_exception_noconnection
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 145, in __init__
self._dbapi_connection = engine.raw_connection()
^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 3288, in raw_connection
return self.pool.connect()
^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 452, in connect
return _ConnectionFairy._checkout(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 1267, in _checkout
fairy = _ConnectionRecord.checkout(pool)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 716, in checkout
rec = pool._do_get()
^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/impl.py", line 284, in _do_get
return self._create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 393, in _create_connection
return _ConnectionRecord(self)
^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 678, in __init__
self.__connect()
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 902, in __connect
with util.safe_reraise():
File "/venv/lib/python3.11/site-packages/sqlalchemy/util/langhelpers.py", line 147, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/venv/lib/python3.11/site-packages/sqlalchemy/pool/base.py", line 898, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 637, in connect
return dialect.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/sqlalchemy/engine/default.py", line 615, in connect
return self.loaded_dbapi.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib/python3.11/site-packages/psycopg/connection.py", line 728, in connect
raise ex.with_traceback(None)
sqlalchemy.exc.OperationalError: (psycopg.OperationalError) connection failed: fe_sendauth: no password supplied
(Background on this error at: https://sqlalche.me/e/20/e3q8)
[2023-09-06 11:21:45 +0000] [94] [INFO] Worker exiting (pid: 94)
[2023-09-06 11:21:46 +0000] [1] [INFO] Shutting down: Master
[2023-09-06 11:21:46 +0000] [1] [INFO] Reason: Worker failed to boot.
System(please complete the following information): Azure kubernetes cluster, mounting a kubernetes secret as a file.
kubectl version output:
>kubectl version
WARNING: This version information is deprecated and will be replaced with the output from kubectl version --short. Use --output=yaml|json to get the full version.
Client Version: version.Info{Major:"1", Minor:"27", GitVersion:"v1.27.2", GitCommit:"7f6f68fdabc4df88cfea2dcf9a19b2b830f1e647", GitTreeState:"clean", BuildDate:"2023-05-17T14:20:07Z", GoVersion:"go1.20.4", Compiler:"gc", Platform:"linux/amd64"}
Kustomize Version: v5.0.1
Server Version: version.Info{Major:"1", Minor:"26", GitVersion:"v1.26.3", GitCommit:"f18584a06fc476806da2e340e2eed960659871e8", GitTreeState:"clean", BuildDate:"2023-06-12T18:45:20Z", GoVersion:"go1.19.7", Compiler:"gc", Platform:"linux/amd64"}
@bok11 ,
How are you passing papass file to container? If you are passing using volume, then change permission for source file to 600 & try again. Here is my docker-compose -
services:
pgadmin:
image: dpage/pgadmin4:7.6
container_name: pgadmin
restart: always
ports:
- "9000:80"
environment:
PGPASSFILE: '/var/lib/pgadmin/.pgpass'
PGADMIN_CONFIG_CONFIG_DATABASE_URI: '''postgresql://<dbname>@<host>:<db_port>/pgadmindbdockerdb'''
PGADMIN_DEFAULT_EMAIL: <user_name>
PGADMIN_DEFAULT_PASSWORD:<password>
PGADMIN_CONFIG_CONSOLE_LOG_LEVEL: 10
volumes:
- ./config/pgpass:/var/lib/pgadmin/.pgpass
Make sure ./config/pgpass has permission=600
I am on Kubernetes, and create the secret as a Kubernetes secret, which is then mounted as a file with the permissions 600. I have had issues with other programs trying to change the permissions, even if they are the right ones, which is not possible with mounted secrets.
For those who cannot make it work, I found a solution
Important surprises I found:
- Plain "PassFile" on the level of single server definition does not work.
- Developers recently added
"ConnectionParameters"where you can specify"passfile"and never wrote about it in - documentation.
- Value of recently added
"passfile"in"ConnectionParameters"is not an absolute path (even if it starts with root-like slash). It's relative. And in reality/.pgpassis actually/var/lib/pgadmin/storage/{normalized form of PGADMIN_DEFAULT_EMAIL with '@' replaced to '_'}/.pgpass. In my case because I setPGADMIN_DEFAULT_EMAIL="[email protected]", my path inside docker containerdpage/pgadmin4was/var/lib/pgadmin/storage/admin_hello.com/.pgpass - In docker container
dpage/pgadmin4userpgadminis not inpgadmingroup as you would expect. Userpgadminis inrootgroup. - Ownerships and permissions of files and directories inside docker container
dpage/pgadmin4are complete mess. For example: path/pgadmin4/hasroot:rootownership and mostly everything inside is the same,/pgadmin4/config_distro.pyfor some reason haspgadmin:rootownership, '/var/lib/pgadmin/' by itself hasroot:rootownership, but every file and dir inside it haspgadmin:rootownership. - in order to write to one of the dirs in
Dockerfileyou have to setUSERfirst. - THE MOST IMPORTANT (at least in my case). If you are trying to bind-mount (docker's term) file which didn't exist before, docker for some reason will always create directory as mountpoint, and then (I have no fucking idea how this bizarre shit works) it mounts your file in place of directory in container. And the shit is that pgadmin cannot read file and does not throw an error with message like this:
I've seen you passed "/.pgpass" in "ConnectionParameters"."passfile" but i failed to read it. Instead it throws completely useless and misleading error that looks likeyou provided empty password, try fucking again (connection failed: fe_sendauth: no password supplied) - In order to make mounting of passfile work, you have to:
9.1. prepare a mountpoint for passfile. For that I created new
Dockerfilewith following content:
9.2. build thisFROM dpage/pgadmin4:latest as base RUN touch /tmp/mountpoint.pgpass; \ chmod 600 /tmp/mountpoint.pgpass;Dockerfile9.3. mount original.pgpassfile from my filesystem to prepared mountpoint in my docker compose
9.4. modify (extend) entrypoint of the same container. (remember on this stage everything mounted already) 9.4.1. Here I create directory for my pgadmin account (it will be created anyway but we need it right now). 9.4.2. Then I copy mountedvolumes: ../pgadmin4/dev.passfile:/tmp/mountpoint.pgpass.pgpassfile into deeply nested destination directory. I'm not linking or moving it because I don't want to change properties of still mounted original file. 9.4.3. Then I set proper owners and permissions to this copy. 9.4.4. And then I call original entrypoint.shentrypoint: > /bin/sh -c " mkdir -p /var/lib/pgadmin/storage/admin_hello.com/; cp /tmp/mountpoint.pgpass /var/lib/pgadmin/storage/admin_hello.com/.pgpass; chown pgadmin:root /var/lib/pgadmin/storage/admin_hello.com/.pgpass; chmod 600 /var/lib/pgadmin/storage/admin_hello.com/.pgpass; /entrypoint.sh "
For those who cannot make it work, I found a solution ...
entrypoint: > /bin/sh -c " mkdir -p /var/lib/pgadmin/storage/admin_hello.com/; cp /tmp/mountpoint.pgpass /var/lib/pgadmin/storage/admin_hello.com/.pgpass; chown pgadmin:root /var/lib/pgadmin/storage/admin_hello.com/.pgpass; chmod 600 /var/lib/pgadmin/storage/admin_hello.com/.pgpass; /entrypoint.sh "
This solve my problem. @nikelborm THANK YOU A LOT!!!
btw, I mount the pgpasss file via docker secrets without writing the Dockerfile (in your step 9.1). And it also works fine.
entrypoint: >
/bin/sh -c "
mkdir -p /var/lib/pgadmin/storage/admin_hello.com;
cp /run/secrets/pgpass /var/lib/pgadmin/storage/admin_hello.com/pgpass;
chown pgadmin:root /var/lib/pgadmin/storage/admin_hello.com/pgpass;
chmod 600 /var/lib/pgadmin/storage/admin_hello.com/pgpass;
/entrypoint.sh;
"
Both solutions works fine for passing pgpass file for using external db as pgadmin db.
The solutions will definelty not work when mounting the files through kubernetes, as you cannot change permissions with chmod. We still rely on copy pasting in the password.
@bok11 Please find the attached config file where I have created pgpass secret and mounted in /tmp directory. In postStart hook, copied pgpass file to /var/lib/pgadmin.
apiVersion: v1
kind: Service
metadata:
name: pgadmin-service
spec:
ports:
- protocol: TCP
port: 80
selector:
app: pgadmin
type: NodePort
---
apiVersion: v1
kind: ConfigMap
metadata:
name: pgadmin-config
data:
servers.json: |
{
"Servers": {
"1": {
"Name": "PostgreSQL DB",
"Group": "Servers",
"Port": 5432,
"Username": "postgres",
"Host": "postgres.domain.com",
"SSLMode": "prefer",
"MaintenanceDB": "postgres"
}
}
}
---
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: pgadmin
data:
pgadmin-password: U3kalVwZXJTZWNyZXQ=
---
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: pgadmin-pgpass
data:
.pgpass: NDQuMjAxLjIwNi4xNjQ6NTQzMToqOnabqBvc3RncmVzOmVkYg==
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: pgadmin
spec:
serviceName: pgadmin-service
podManagementPolicy: Parallel
replicas: 1
updateStrategy:
type: RollingUpdate
selector:
matchLabels:
app: pgadmin
template:
metadata:
labels:
app: pgadmin
spec:
terminationGracePeriodSeconds: 10
hostname: pgadmin
containers:
- name: pgadmin
image: dpage/pgadmin4:7.7
imagePullPolicy: Always
lifecycle:
postStart:
exec:
command: [ "/bin/sh","-c","mkdir -p /var/lib/pgadmin/storage/user_domain.com;
cp /tmp/.pgpass /var/lib/pgadmin/storage/user_domain.com/.pgpass;
chown pgadmin:root /var/lib/pgadmin/storage/user_domain.com/.pgpass;
chmod 600 /var/lib/pgadmin/storage/user_domain.com/.pgpass;
cp /tmp/.pgpass /var/lib/pgadmin/.pgpass;
chown pgadmin:root /var/lib/pgadmin/.pgpass;
chmod 600 /var/lib/pgadmin/.pgpass;
"]
env:
- name: PGPASSFILE
value: '/var/lib/pgadmin/.pgpass'
- name: PGADMIN_DEFAULT_EMAIL
value: '[email protected]'
- name: PGADMIN_DEFAULT_PASSWORD
valueFrom:
secretKeyRef:
name: pgadmin
key: pgadmin-password
- name: PGADMIN_CONFIG_CONSOLE_LOG_LEVEL
value: '10'
- name: PGADMIN_CONFIG_CONFIG_DATABASE_URI
value: '''postgresql://<DB_USERNAME>@<DB_HOST>:<DB_PORT>/pgadmindbdockerdb2'''
ports:
- name: http
containerPort: 80
protocol: TCP
volumeMounts:
- name: pgpass1
mountPath: /tmp
- name: pgadmin-config
mountPath: /pgadmin4/servers.json
subPath: servers.json
readOnly: true
- name: pgadmin-data1
mountPath: /var/lib/pgadmin
volumes:
- name: pgadmin-config
configMap:
name: pgadmin-config
- name: pgpass1
secret:
secretName: pgadmin-pgpass
volumeClaimTemplates:
- metadata:
name: pgadmin-data1
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 3Gi
Thanks @yogeshmahajan-1903 I spent a good day trying to track down how to achieve this in k8s. In my case I wanted to copy it for all users so added the following:
command: ["/bin/sh", "-c", "for d in /storage/*/ ;
do cp /shared/pgpass $d/pgpass;
chown pgadmin:root $d/pgass;
chmod 600 $d/pgpass;
done"]
The problem of course is that it relies on the users already existing..
I reported the same concern here https://github.com/pgadmin-org/pgadmin4/issues/6257#issuecomment-2923536177