Apply scopes to explicitly provided credentials if needed (#4594)
diff --git a/google/api_core/grpc_helpers.py b/google/api_core/grpc_helpers.py
index 00eab92..784acf6 100644
--- a/google/api_core/grpc_helpers.py
+++ b/google/api_core/grpc_helpers.py
@@ -20,6 +20,7 @@
from google.api_core import exceptions
from google.api_core import general_helpers
import google.auth
+import google.auth.credentials
import google.auth.transport.grpc
import google.auth.transport.requests
@@ -127,6 +128,9 @@
"""
if credentials is None:
credentials, _ = google.auth.default(scopes=scopes)
+ else:
+ credentials = google.auth.credentials.with_scopes_if_required(
+ credentials, scopes)
request = google.auth.transport.requests.Request()
diff --git a/tests/unit/test_grpc_helpers.py b/tests/unit/test_grpc_helpers.py
index f0bb0ca..6ee4062 100644
--- a/tests/unit/test_grpc_helpers.py
+++ b/tests/unit/test_grpc_helpers.py
@@ -18,6 +18,7 @@
from google.api_core import exceptions
from google.api_core import grpc_helpers
+import google.auth.credentials
def test__patch_callable_name():
@@ -169,3 +170,19 @@
assert channel is secure_authorized_channel.return_value
secure_authorized_channel.assert_called_once_with(
mock.sentinel.credentials, mock.ANY, target)
+
+
+@mock.patch('google.auth.transport.grpc.secure_authorized_channel')
+def test_create_channel_explicit_scoped(unused_secure_authorized_channel):
+ scopes = ['1', '2']
+
+ credentials = mock.create_autospec(
+ google.auth.credentials.Scoped, instance=True)
+ credentials.requires_scopes = True
+
+ grpc_helpers.create_channel(
+ mock.sentinel.target,
+ credentials=credentials,
+ scopes=scopes)
+
+ credentials.with_scopes.assert_called_once_with(scopes)