gh-144249: Report filename in SSLContext.load_cert_chain errors (#144250)
When user tries to load a certificate chain, attach the related
filename to the exception being raised. Improving user experience.
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
index 9dc99fb..6023c89 100644
--- a/Lib/test/test_ssl.py
+++ b/Lib/test/test_ssl.py
@@ -131,6 +131,7 @@ def data_file(*name):
EMPTYCERT = data_file("nullcert.pem")
BADCERT = data_file("badcert.pem")
NONEXISTINGCERT = data_file("XXXnonexisting.pem")
+NONEXISTINGKEY = data_file("XXXnonexistingkey.pem")
BADKEY = data_file("badkey.pem")
NOKIACERT = data_file("nokia.pem")
NULLBYTECERT = data_file("nullbytecert.pem")
@@ -1229,6 +1230,11 @@ def test_load_cert_chain(self):
with self.assertRaises(OSError) as cm:
ctx.load_cert_chain(NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
+ self.assertEqual(cm.exception.filename, NONEXISTINGCERT)
+ with self.assertRaises(OSError) as cm:
+ ctx.load_cert_chain(CERTFILE, keyfile=NONEXISTINGKEY)
+ self.assertEqual(cm.exception.errno, errno.ENOENT)
+ self.assertEqual(cm.exception.filename, NONEXISTINGKEY)
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"):
ctx.load_cert_chain(BADCERT)
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"):
diff --git a/Misc/NEWS.d/next/Library/2026-01-27-09-58-52.gh-issue-144249.mCIy95.rst b/Misc/NEWS.d/next/Library/2026-01-27-09-58-52.gh-issue-144249.mCIy95.rst
new file mode 100644
index 0000000..52f27ce
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-01-27-09-58-52.gh-issue-144249.mCIy95.rst
@@ -0,0 +1,2 @@
+Add filename context to :exc:`OSError` exceptions raised by
+:func:`ssl.SSLContext.load_cert_chain`, allowing users to have more context.
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
index 22865bd..66d699b 100644
--- a/Modules/_ssl.c
+++ b/Modules/_ssl.c
@@ -4517,7 +4517,8 @@ load_cert_chain_lock_held(PySSLContext *self, _PySSLPasswordInfo *pw_info,
/* the password callback has already set the error information */
}
else if (errno != 0) {
- PyErr_SetFromErrno(PyExc_OSError);
+ PyErr_SetFromErrnoWithFilename(PyExc_OSError,
+ PyBytes_AS_STRING(certfile_bytes));
ERR_clear_error();
}
else {
@@ -4537,7 +4538,8 @@ load_cert_chain_lock_held(PySSLContext *self, _PySSLPasswordInfo *pw_info,
/* the password callback has already set the error information */
}
else if (errno != 0) {
- PyErr_SetFromErrno(PyExc_OSError);
+ PyErr_SetFromErrnoWithFilename(PyExc_OSError,
+ PyBytes_AS_STRING(keyfile_bytes ? keyfile_bytes : certfile_bytes));
ERR_clear_error();
}
else {