raise FileNotFoundError for missing TLS material
Would you accept a PR which changes the existing OSError for missing TLS material to FileNotFoundError?
e.g.:
if conn.cert_file and not os.path.exists(conn.cert_file):
raise OSError(
f"Could not find the TLS certificate file, "
f"invalid path: {conn.cert_file}"
)
becomes something like:
if conn.cert_file and not os.path.exists(conn.cert_file):
from errno import ENOENT
raise FileNotFoundError(
ENOENT,
"Could not find the TLS certificate file, invalid path",
str(conn.cert_file)
)
Our use case is that there are temporary conditions where the files don't exist and it'd be nicer to handle FileNotFoundError specifically and be able to compare the .filename attribute rather than the more general OSError and test str(excp).endswith(...). As FileNotFoundError is a subclass of OSError existing try/excepts continue to work but it would change the string representation:
>>> str(OSError("Could not find the TLS certificate file, invalid path: filename"))
'Could not find the TLS certificate file, invalid path: filename'
>>> str(FileNotFoundError(errno.ENOENT, "Could not find the TLS certificate file, invalid path", "filename"))
"[Errno 2] Could not find the TLS certificate file, invalid path: 'filename'"
If my read of the docs is accurate, this is a subclass of OSError so it's fine. The PR that was created is a spam automation that opened this before anyone agreed to it and they have opened more than 20 on other repos I've seen.
If you'd like to send a PR for this @JKDingwall I'm happy to review this but please ensure you add unit tests for this change and update them.
I prepared the focused fix requested here and pushed it to my fork:
https://github.com/tomatotomata/requests/commit/be90ea47a5af638aeeac7f0e74dc55af3a11bc43
It changes the missing CA bundle, client certificate, and client key paths to raise FileNotFoundError with errno.ENOENT and the original path in .filename. The tests now check the specific exception and filename for all three cases.
Validation completed:
pre-commit run --files src/requests/adapters.py tests/test_requests.py- focused Requests tests: 2 passed
git diff --check
The full tests/test_requests.py run reached 338 passed, but this Windows checkout does not materialize the repository's tests/certs/valid/ca symlink, so one unrelated TLS fixture could not run. The branch is codex/file-not-found-tls-7564. Requests does not allow me to create the PR directly, so this is ready for a maintainer to pull into review if the scope looks right.
@sigmavirus24 I've got round to testing my version of the change today: https://github.com/psf/requests/compare/main...JKDingwall:requests:7564-use-FileNotFoundError-for-missing-TLS-material?expand=1
This is largely the same as other versions that have been mentioned in the issue. Some of my differences:
- When raising FileNotFound cast the path to
str(...)in case apathlib.Path(...)object has been passed.
>>> raise FileNotFoundError(errno.ENOENT, "message", pathlib.Path("/tmp"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] message: PosixPath('/tmp')
>>> raise FileNotFoundError(errno.ENOENT, "message", str(pathlib.Path("/tmp")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] message: '/tmp'
- In the test assertions
2is not hardcoded as the value ofENOENT, while this is a common value there is no guarantee ENOENT == 2. There is a belt-and-braces approach to testing the exception raised, if it is ott then I could reduce that.
I followed that edge case through on the fork. The follow-up commit a9c7bad now normalizes the CA, certificate, and key filenames with str(...) before constructing FileNotFoundError, and the new PathLike regression passes alongside the three existing missing-TLS cases. Ruff, pre-commit, and git diff --check are clean. The updated branch is ready for the maintainer to pull into the review if this matches your version.
Proposed Plan to Raise FileNotFoundError for Missing TLS Certificates
When passing a string file path to cert= or verify= in requests.get(...) for missing or invalid paths, lower-level OpenSSL calls currently raise SSLError or OSError rather than explicit FileNotFoundError.
Fix:
Add path existence validation in adapters.py before passing certificate and key file paths to SSLContext.load_cert_chain, raising FileNotFoundError when specified files do not exist.
I'd like to take this on. Plan is to raise FileNotFoundError(errno.ENOENT, msg, str(path)) for the three missing TLS paths in src/requests/adapters.py (CA bundle/verify, cert, and key), preserving OSError compatibility and adding regression tests for .filename including pathlib.Path input.
Update: focused fix is ready on my fork
Branch: aryansk:fix-7564-filenotfound @ b589cc8de2f450f2caad75bd869e13d99895537e (also fix/file-not-found-tls-7564)
Commit: https://github.com/aryansk/requests/commit/b589cc8de2f450f2caad75bd869e13d99895537e
Compare: https://github.com/psf/requests/compare/main...aryansk:fix-7564-filenotfound?expand=1
Changes:
-
src/requests/adapters.py:import errno, threeOSError→FileNotFoundError(errno.ENOENT, msg, str(path))for CA bundle, cert file, key file; normalize filename withstr(); handlecerttuple viaisinstance(cert, tuple)sopathlib.Pathis treated as a single file. -
tests/test_requests.py: updated two existing tests to assertFileNotFoundError+errno+filename+strrepr, addedtest_invalid_ssl_certificate_files_with_pathlikeforPathinputs (verify, cert, and tuple with existing temp file).
Validation:
- focused:
pytest -k "test_invalid_ca or test_invalid_ssl" -v→ 3 passed - broader:
pytest -k "tls or cert or verify" -v→ 17 passed - full:
pytest tests/test_requests.py -q→ 340 passed, 1 skipped, 1 xfailed ruff check+ruff format --check→ all checks passed;git diff --checkclean
Attempted gh pr create --repo psf/requests --head aryansk:fix-7564-filenotfound --base main --draft but GitHub returns does not have the correct permissions to execute CreatePullRequest (REST 404). The compare URL above is ready for a maintainer to pull. Happy to open the PR via the web UI if you prefer, or to adjust per review.
Hi, I’d like to work on the missing TLS material error path. I can add focused tests for the missing certificate/key cases and make sure the raised FileNotFoundError keeps the useful filename context. Is this issue still available for an external PR?
I'd like to take this one. The reporter's proposed change (OSError → FileNotFoundError) is a small ergonomic improvement: FileNotFoundError is a subclass of OSError, so existing except OSError: handlers still catch it, but callers can now narrow except FileNotFoundError: for the specific case.
Root cause. In requests/adapters.py:send(), when conn.cert_file is set but doesn't exist, the code raises a plain OSError with a descriptive message. The subclass FileNotFoundError exists for exactly this case (errno ENOENT), and Python's OSError constructor with errno=ENOENT already returns a FileNotFoundError (Python 3.3+). So the current code is almost already FileNotFoundError if it sets errno correctly — except the requests code uses the string-message path, not the errno path.
Alternatives I considered: (a) Replace with raise FileNotFoundError(...) directly (the reporter's proposal, IMO best). (b) Set OSError(ENOENT, ...) so the runtime picks FileNotFoundError automatically. (c) Define a new requests.exceptions.MissingTLSMaterial exception (overkill, breaks existing handlers).
Suggestion to maintainer: (a) is the right call — FileNotFoundError is the canonical type for missing files, and any existing except OSError: continues to work. Two questions: (i) should the same change apply to the key-file path path path and the proxy cacert path path, or scope only to cert_file? (ii) Does requests want a deprecation cycle (raise a new MissingTLSMaterial for one release, then alias it)? Probably no — the change is strictly additive. (claiming via @LeonxLJX)