You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit b9a1379
Browse filesBrowse the repository at this point in the historyBrowse files
fix(auth): prevent TypeError and support home-dir cert fallback for X… (#18016)
….509 WIF on ECP machines
- Prevent TypeError crash in identity_pool.py by raising ClientCertError
if _get_mtls_cert_and_key_paths() returns None for the certificate path.
- Add fallback in _mtls_helper.py to check the default home directory
configuration ~/.config/gcloud/certificate_config.json if the
env-var-resolved config does not contain a workload block.
- Add unit tests to cover both behaviors and verify they function
correctly.
Fixes: b/542359992
## Bug / Context
Fixes the TypeError (NoneType) crash that occurs when developers attempt
X.509 Workload Identity Federation on ECP machines. (b/542359992)
## Changes
- **Fallback to user configuration:** In `_mtls_helper.py`, if the ECP
system-wide config lacks a `workload` block, fallback to check the home
folder's `~/.config/gcloud/certificate_config.json`.
- **TypeError Prevention:** In `identity_pool.py`, raise a clean
`ClientCertError` if no certificate path is configured, preventing a
generic `NoneType` crash in `open()`.
- **Defensive Check:** Defensively assert that loaded JSON config data
is a dictionary before accessing fields.
- **Unit Tests:** Added tests to cover these fallback and error handling
scenarios.
## Verification
You can verify the fix by running this python script with the local
packages loaded:
```python
import os
import sys
import json
from google.auth import identity_pool
from google.auth import exceptions
# Setup dummy config using default cert path config
cred_config = {
"type": "external_account",
"audience": "//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/test-pool/providers/test-provider",
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
"token_url": "https://sts.googleapis.com/v1/token",
"credential_source": {
"certificate": {
"use_default_certificate_config": True
}
}
}
config_file = "verify_cred_config.json"
with open(config_file, "w") as f:
json.dump(cred_config, f)
try:
credentials = identity_pool.Credentials.from_file(config_file)
cert_bytes = credentials._get_cert_bytes()
print("Success: Certificate read successfully.")
except exceptions.ClientCertError as e:
print(f"Verified: Prevented TypeError crash. Raised ClientCertError: {e}")
finally:
if os.path.exists(config_file):
os.remove(config_file)
These guidelines are automatically applied to Python development tasks within this repository.
4
+
5
+
---
6
+
7
+
## 1. Filesystem and Path Resolution
8
+
***Dynamic Configuration Directories:** Never hardcode paths like `~/.config/gcloud/` or standard user directories. Always utilize existing SDK helpers (such as `_cloud_sdk.get_config_path()`) to dynamically locate system and configuration files.
9
+
***Path Normalization:** When comparing path strings (especially paths retrieved from environment variables or dynamically built), always normalize them using `os.path.normpath` or `pathlib.Path` to prevent Windows vs Unix slash mismatch issues (`\` vs `/`).
10
+
11
+
## 2. Input Validation (Defensive Programming)
12
+
***Untrusted File Inputs:** Any data loaded from external configuration files (JSON, YAML, CSV) is untrusted. Always type-validate structure (e.g. check `isinstance(data, dict)` and `isinstance(data.get("sub_key"), dict)`) *before* indexing or calling dictionary lookup keys, avoiding `TypeError` exceptions.
13
+
14
+
## 3. Exception Contract Compliance
15
+
***Public Interface Contracts:** When introducing new exception pathways in internal helpers, always trace their propagation. If a public-facing API method (e.g. `refresh()`) is documented to raise a specific base exception class (like `RefreshError`), wrap lower-level custom exceptions (like `ClientCertError`) or system exceptions (like `OSError`) and re-raise them under the correct interface exception types.
16
+
***Self-Contained Fallbacks:** Fallback logic must be resilient and self-contained. Always wrap fallback configuration loading in try-except blocks to catch expected exceptions (like `ClientCertError` or `OSError`) and bypass failures gracefully.
17
+
18
+
## 4. Unit Testing and Mock Hygiene
19
+
***Localized Mocking:** When mocking standard functions or filesystem checks (like `path.exists`), mock the local module import path (e.g., `google.auth.transport._mtls_helper.path.exists`) instead of patching builtins globally (e.g., `os.path.exists`), ensuring mocks are isolated.
20
+
***Fallback Verification:** Fallback test cases must explicitly verify execution flow by asserting the expected call sequence and arguments of mocked helpers using `assert_called_once_with` or `assert_has_calls`.
0 commit comments