@@ -249,8 +249,13 @@ def _parse_tls_version(tls_version):
249249 )
250250
251251
252- def _dot_postgresql_path (filename ) -> pathlib .Path :
253- return (pathlib .Path .home () / '.postgresql' / filename ).resolve ()
252+ def _dot_postgresql_path (filename ) -> typing .Optional [pathlib .Path ]:
253+ try :
254+ homedir = pathlib .Path .home ()
255+ except (RuntimeError , KeyError ):
256+ return None
257+
258+ return (homedir / '.postgresql' / filename ).resolve ()
254259
255260
256261def _parse_connect_dsn_and_args (* , dsn , host , port , user ,
@@ -501,11 +506,16 @@ def _parse_connect_dsn_and_args(*, dsn, host, port, user,
501506 ssl .load_verify_locations (cafile = sslrootcert )
502507 ssl .verify_mode = ssl_module .CERT_REQUIRED
503508 else :
504- sslrootcert = _dot_postgresql_path ('root.crt' )
505509 try :
510+ sslrootcert = _dot_postgresql_path ('root.crt' )
511+ assert sslrootcert is not None
506512 ssl .load_verify_locations (cafile = sslrootcert )
507- except FileNotFoundError :
513+ except ( AssertionError , FileNotFoundError ) :
508514 if sslmode > SSLMode .require :
515+ if sslrootcert is None :
516+ raise RuntimeError (
517+ 'Cannot determine home directory'
518+ )
509519 raise ValueError (
510520 f'root certificate file "{ sslrootcert } " does '
511521 f'not exist\n Either provide the file or '
@@ -526,18 +536,20 @@ def _parse_connect_dsn_and_args(*, dsn, host, port, user,
526536 ssl .verify_flags |= ssl_module .VERIFY_CRL_CHECK_CHAIN
527537 else :
528538 sslcrl = _dot_postgresql_path ('root.crl' )
529- try :
530- ssl .load_verify_locations (cafile = sslcrl )
531- except FileNotFoundError :
532- pass
533- else :
534- ssl .verify_flags |= ssl_module .VERIFY_CRL_CHECK_CHAIN
539+ if sslcrl is not None :
540+ try :
541+ ssl .load_verify_locations (cafile = sslcrl )
542+ except FileNotFoundError :
543+ pass
544+ else :
545+ ssl .verify_flags |= \
546+ ssl_module .VERIFY_CRL_CHECK_CHAIN
535547
536548 if sslkey is None :
537549 sslkey = os .getenv ('PGSSLKEY' )
538550 if not sslkey :
539551 sslkey = _dot_postgresql_path ('postgresql.key' )
540- if not sslkey .exists ():
552+ if sslkey is not None and not sslkey .exists ():
541553 sslkey = None
542554 if not sslpassword :
543555 sslpassword = ''
@@ -549,12 +561,15 @@ def _parse_connect_dsn_and_args(*, dsn, host, port, user,
549561 )
550562 else :
551563 sslcert = _dot_postgresql_path ('postgresql.crt' )
552- try :
553- ssl .load_cert_chain (
554- sslcert , keyfile = sslkey , password = lambda : sslpassword
555- )
556- except FileNotFoundError :
557- pass
564+ if sslcert is not None :
565+ try :
566+ ssl .load_cert_chain (
567+ sslcert ,
568+ keyfile = sslkey ,
569+ password = lambda : sslpassword
570+ )
571+ except FileNotFoundError :
572+ pass
558573
559574 # OpenSSL 1.1.1 keylog file, copied from create_default_context()
560575 if hasattr (ssl , 'keylog_filename' ):
0 commit comments