Skip to content

Commit aef52be

Browse files
authored
fix: Correctly catch DefaultCredentialsError when looking up project_id (#720)
* Added additional exception catching with unit tests * lint: fixed spacing * fix: explicitly force exception raise in unit test
1 parent 59a22b3 commit aef52be

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

firebase_admin/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import os
1919
import threading
2020

21+
from google.auth.exceptions import DefaultCredentialsError
2122
from firebase_admin import credentials
2223
from firebase_admin.__about__ import __version__
2324

@@ -257,7 +258,7 @@ def _lookup_project_id(self):
257258
if not project_id:
258259
try:
259260
project_id = self._credential.project_id
260-
except AttributeError:
261+
except (AttributeError, DefaultCredentialsError):
261262
pass
262263
if not project_id:
263264
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT',

tests/test_app.py

+22
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import os
1818

1919
import pytest
20+
from google.auth.exceptions import DefaultCredentialsError
2021

2122
import firebase_admin
2223
from firebase_admin import credentials
@@ -315,6 +316,27 @@ def evaluate():
315316
assert app.project_id is None
316317
testutils.run_without_project_id(evaluate)
317318

319+
def test_no_project_id_from_environment(self, app_credential):
320+
default_env = 'GOOGLE_APPLICATION_CREDENTIALS'
321+
gcloud_env = 'CLOUDSDK_CONFIG'
322+
def evaluate():
323+
app = firebase_admin.initialize_app(app_credential, name='myApp')
324+
app._credential._g_credential = None
325+
old_gcloud_var = os.environ.get(gcloud_env)
326+
os.environ[gcloud_env] = ''
327+
old_default_var = os.environ.get(default_env)
328+
if old_default_var:
329+
del os.environ[default_env]
330+
with pytest.raises((AttributeError, DefaultCredentialsError)):
331+
project_id = app._credential.project_id
332+
project_id = app.project_id
333+
if old_default_var:
334+
os.environ[default_env] = old_default_var
335+
if old_gcloud_var:
336+
os.environ[gcloud_env] = old_gcloud_var
337+
assert project_id is None
338+
testutils.run_without_project_id(evaluate)
339+
318340
def test_non_string_project_id(self):
319341
options = {'projectId': {'key': 'not a string'}}
320342
with pytest.raises(ValueError):

0 commit comments

Comments
 (0)