Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions googleapiclient/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,20 +689,6 @@ def build_from_document(
client_cert_to_use = mtls.default_client_encrypted_cert_source(
adc_cert_path, adc_key_path
)
if client_cert_to_use:
cert_path, key_path, passphrase = client_cert_to_use()

# The http object we built could be google_auth_httplib2.AuthorizedHttp
# or httplib2.Http. In the first case we need to extract the wrapped
# httplib2.Http object from google_auth_httplib2.AuthorizedHttp.
http_channel = (
http.http
if google_auth_httplib2
and isinstance(http, google_auth_httplib2.AuthorizedHttp)
else http
)
http_channel.add_certificate(key_path, cert_path, "", passphrase)

# If user doesn't provide api endpoint via client options, decide which
# api endpoint to use.
if "mtlsRootUrl" in service and (
Expand All @@ -728,6 +714,25 @@ def build_from_document(
f"mTLS is not supported in any universe other than {DEFAULT_UNIVERSE}."
)
base = mtls_endpoint

if client_cert_to_use:
parsed_base = urllib.parse.urlsplit(base)
cert_domain = parsed_base.netloc.lower()
if parsed_base.scheme.lower() == "https" and cert_domain:
cert_path, key_path, passphrase = client_cert_to_use()

# The http object we built could be google_auth_httplib2.AuthorizedHttp
# or httplib2.Http. In the first case we need to extract the wrapped
# httplib2.Http object from google_auth_httplib2.AuthorizedHttp.
http_channel = (
http.http
if google_auth_httplib2
and isinstance(http, google_auth_httplib2.AuthorizedHttp)
else http
)
http_channel.add_certificate(
key_path, cert_path, cert_domain, passphrase
)
else:
# Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com".
http_credentials = getattr(http, "credentials", None)
Expand Down
94 changes: 89 additions & 5 deletions tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,11 +844,20 @@ class DiscoveryFromDocumentMutualTLS(unittest.TestCase):
ADC_KEY_PATH = "adc_key_path"
ADC_PASSPHRASE = "adc_passphrase"

def check_http_client_cert(self, resource, has_client_cert="false"):
if isinstance(resource._http, google_auth_httplib2.AuthorizedHttp):
certs = list(resource._http.http.certificates.iter(""))
else:
certs = list(resource._http.certificates.iter(""))
def check_http_client_cert(
self, resource, has_client_cert="false", expected_domain=None
):
http_channel = (
resource._http.http
if isinstance(resource._http, google_auth_httplib2.AuthorizedHttp)
else resource._http
)
if expected_domain is None:
expected_domain = urllib.parse.urlsplit(resource._baseUrl).netloc.lower()
# Never attach a wildcard domain ("") that matches unrelated hosts.
self.assertEqual(list(http_channel.certificates.iter("")), [])
self.assertEqual(list(http_channel.certificates.iter("other.example.com")), [])
certs = list(http_channel.certificates.iter(expected_domain))
if has_client_cert == "true":
self.assertEqual(len(certs), 1)
self.assertEqual(
Expand Down Expand Up @@ -1214,6 +1223,81 @@ def test_mtls_with_no_client_cert(
self.check_http_client_cert(plus, has_client_cert="false")
self.assertEqual(plus._baseUrl, base_url)

def test_mtls_client_cert_scoped_to_mtls_host(self):
discovery = read_datafile("plus.json")

with mock.patch.dict(
"os.environ",
{
"GOOGLE_API_USE_MTLS_ENDPOINT": "auto",
"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true",
},
):
plus = build_from_document(
discovery,
credentials=self.MOCK_CREDENTIALS,
client_options={
"client_encrypted_cert_source": self.client_encrypted_cert_source
},
)
self.assertEqual(plus._baseUrl, MTLS_ENDPOINT)
self.check_http_client_cert(
plus, has_client_cert="true", expected_domain="www.mtls.googleapis.com"
)
# Standard non-mTLS host must not match the mTLS certificate scope.
self.assertEqual(
list(plus._http.http.certificates.iter("www.googleapis.com")), []
)

def test_mtls_client_cert_scoped_to_custom_endpoint_with_port(self):
discovery = read_datafile("plus.json")

with mock.patch.dict(
"os.environ",
{
"GOOGLE_API_USE_MTLS_ENDPOINT": "auto",
"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true",
},
):
plus = build_from_document(
discovery,
credentials=self.MOCK_CREDENTIALS,
client_options={
"api_endpoint": "https://Custom.Example.com:8443/v1/",
"client_encrypted_cert_source": self.client_encrypted_cert_source,
},
)
self.check_http_client_cert(
plus,
has_client_cert="true",
expected_domain="custom.example.com:8443",
)
self.assertEqual(
list(plus._http.http.certificates.iter("custom.example.com")), []
)

def test_mtls_client_cert_not_added_for_non_https_endpoint(self):
discovery = read_datafile("plus.json")
cert_source = mock.Mock(side_effect=self.client_encrypted_cert_source)

with mock.patch.dict(
"os.environ",
{
"GOOGLE_API_USE_MTLS_ENDPOINT": "auto",
"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true",
},
):
plus = build_from_document(
discovery,
credentials=self.MOCK_CREDENTIALS,
client_options={
"api_endpoint": "http://localhost:8080/v1/",
"client_encrypted_cert_source": cert_source,
},
)
cert_source.assert_not_called()
self.assertEqual(plus._http.http.certificates.credentials, [])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using plus._http.http directly assumes that plus._http is always an instance of AuthorizedHttp. If the test is refactored in the future to use a different transport or if credentials are not provided, this will raise an AttributeError. It is safer and more consistent to use the helper method self.check_http_client_cert(plus, has_client_cert="false") which already handles unwrapping the HTTP channel safely.

Suggested change
self.assertEqual(plus._http.http.certificates.credentials, [])
self.check_http_client_cert(plus, has_client_cert="false")



class DiscoveryFromHttp(unittest.TestCase):
def setUp(self):
Expand Down
Loading