Skip to content

Commit 31ae507

Browse files
committed
refactor(auth): simplify fallback logic using custom exception and clean standard with block
1 parent 7b77812 commit 31ae507

2 files changed

Lines changed: 29 additions & 24 deletions

File tree

packages/google-auth/google/auth/transport/_mtls_helper.py

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@
7070
)
7171

7272

73+
class _MemfdCreationError(OSError):
74+
"""Raised when Linux in-memory virtual file creation (memfd) fails."""
75+
76+
pass
77+
78+
7379
@contextlib.contextmanager
7480
def secure_cert_key_paths(
7581
cert: Union[bytes, str, None],
@@ -114,13 +120,8 @@ def secure_cert_key_paths(
114120
# the bytes to anonymous in-memory files using memfd_create. This yields
115121
# /proc/self/fd/... paths, keeping the private key entirely in memory.
116122
if sys.platform == "linux" and hasattr(os, "memfd_create"):
117-
cm = _memfd_cert_key_paths(cert_bytes, key_bytes)
118123
try:
119-
cert_path, key_path = cm.__enter__()
120-
except OSError:
121-
pass # Fallback to Tier 3 on failure.
122-
else:
123-
try:
124+
with _memfd_cert_key_paths(cert_bytes, key_bytes) as (cert_path, key_path):
124125
# Handle cases where path exists but might be restricted.
125126
if (cert_path is None or os.path.exists(cert_path)) and (
126127
key_path is None or os.path.exists(key_path)
@@ -129,9 +130,8 @@ def secure_cert_key_paths(
129130
str, key_path or key
130131
), passphrase
131132
return
132-
finally:
133-
cm.__exit__(*sys.exc_info())
134-
# If verification failed, fall through to Tier 3.
133+
except _MemfdCreationError:
134+
pass # Fallback to Tier 3 on failure.
135135

136136
# Tier 3: Fallback Encrypted Temp Files. If in-memory files are not supported
137137
# (macOS/Windows), we write to disk. To protect the key, we encrypt plaintext
@@ -213,20 +213,24 @@ def _memfd_cert_key_paths(
213213
the active descriptors (e.g., '/proc/self/fd/3').
214214
"""
215215
cleanup_fds = []
216-
print("--- in memfd_cert_key_paths")
217216
paths = []
218217

219218
try:
220-
for data, name in [(cert_bytes, "mtls_cert"), (key_bytes, "mtls_key")]:
221-
if data is not None:
222-
# MFD_CLOEXEC prevents FD leaks to spawned subprocesses.
223-
fd = os.memfd_create(name, os.MFD_CLOEXEC) # type: ignore[attr-defined]
224-
cleanup_fds.append(fd)
225-
with os.fdopen(fd, "wb", closefd=False) as f:
226-
f.write(data)
227-
paths.append(f"/proc/self/fd/{fd}")
228-
else:
229-
paths.append(None)
219+
try:
220+
for data, name in [(cert_bytes, "mtls_cert"), (key_bytes, "mtls_key")]:
221+
if data is not None:
222+
# MFD_CLOEXEC prevents FD leaks to spawned subprocesses.
223+
fd = os.memfd_create(name, os.MFD_CLOEXEC) # type: ignore[attr-defined]
224+
cleanup_fds.append(fd)
225+
with os.fdopen(fd, "wb", closefd=False) as f:
226+
f.write(data)
227+
paths.append(f"/proc/self/fd/{fd}")
228+
else:
229+
paths.append(None)
230+
except OSError as exc:
231+
raise _MemfdCreationError(
232+
"Failed to create in-memory virtual files"
233+
) from exc
230234

231235
cert_path, key_path = paths
232236
yield cert_path, key_path
@@ -258,7 +262,6 @@ def _tempfile_cert_key_paths(
258262
else None
259263
)
260264
cleanup_files = []
261-
print("--- in _tempfile_cert_key_paths")
262265
new_passphrase = passphrase
263266
cert_data = cert_bytes
264267
key_data = None

packages/google-auth/tests/transport/test__mtls_helper.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,7 +1069,9 @@ def test_tier2_fallback_to_tier3_on_oserror(
10691069
self, mock_tempfile_cm, mock_memfd_cm, mock_memfd_create
10701070
):
10711071
mock_memfd_ctx = mock.MagicMock()
1072-
mock_memfd_ctx.__enter__.side_effect = OSError("memfd failed")
1072+
mock_memfd_ctx.__enter__.side_effect = _mtls_helper._MemfdCreationError(
1073+
"memfd failed"
1074+
)
10731075
mock_memfd_cm.return_value = mock_memfd_ctx
10741076

10751077
mock_tempfile_ctx = mock.MagicMock()
@@ -1205,7 +1207,7 @@ def test_success_shm(
12051207

12061208
with mock.patch.object(os, "remove") as mock_remove, mock.patch.object(
12071209
os.path, "exists", return_value=True
1208-
):
1210+
), mock.patch.object(os, "access", return_value=True):
12091211
with _mtls_helper._tempfile_cert_key_paths(b"cert", b"key", b"pass") as (
12101212
cert_path,
12111213
key_path,
@@ -1244,7 +1246,7 @@ def test_permission_error_loop_resilience(
12441246

12451247
with mock.patch.object(os, "remove") as mock_remove, mock.patch.object(
12461248
os.path, "exists", return_value=True
1247-
):
1249+
), mock.patch.object(os, "access", return_value=True):
12481250
with _mtls_helper._tempfile_cert_key_paths(b"cert", b"key", b"pass"):
12491251
pass
12501252
mock_remove.assert_called_once_with("/shm/cert")

0 commit comments

Comments
 (0)