gh-76912: Raise OSError from any failure in getpass.getuser() (#29739)

* bpo-32731: Raise OSError from any failure in getpass.getuser()
Previously, if the username was not set in certain environment variables, ImportError escaped on Windows systems, and it was possible for KeyError to escape on other systems if getpwuid() failed.
This commit is contained in:
Jacob Walls 2023-11-27 13:05:55 -05:00 committed by GitHub
parent 936c503a44
commit 99a73c3465
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 24 additions and 7 deletions

View file

@ -156,7 +156,11 @@ def getuser():
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
Any failure to find a username raises OSError.
.. versionchanged:: 3.13
Previously, various exceptions beyond just :exc:`OSError`
were raised.
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
@ -164,9 +168,12 @@ def getuser():
if user:
return user
# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
try:
import pwd
return pwd.getpwuid(os.getuid())[0]
except (ImportError, KeyError) as e:
raise OSError('No username set in the environment') from e
# Bind the name getpass to the appropriate function
try: