Skip to content

Commit da0510a

Browse files
Add mTLS support to generator (#359)
Add preliminary support for mTLS to the generated surface. mTLS provides mutual authentication between a client and a service using certificates. Unless an alternative or custom endpoint is provided, the client surface assumes that the mTLS endpoint for a service is the same as the non-mtls variant with the 'mtls' moniker prepended to the domain. Client certificates can be passed explicitly or yielded via a callback.
1 parent b95dcef commit da0510a

File tree

6 files changed

+332
-79
lines changed

6 files changed

+332
-79
lines changed

packages/gapic-generator/.circleci/config.yml

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ jobs:
253253
ln -s /usr/src/protoc/bin/protoc /usr/local/bin/protoc
254254
- run:
255255
name: Run showcase tests.
256-
command: nox -s showcase_alternative_templates
256+
command: nox -s showcase_alternative_templates
257257
showcase-unit-3.6:
258258
docker:
259259
- image: python:3.6-slim
@@ -263,7 +263,7 @@ jobs:
263263
name: Install system dependencies.
264264
command: |
265265
apt-get update
266-
apt-get install -y curl pandoc unzip
266+
apt-get install -y curl pandoc unzip git
267267
- run:
268268
name: Install protoc 3.7.1.
269269
command: |
@@ -287,7 +287,7 @@ jobs:
287287
name: Install system dependencies.
288288
command: |
289289
apt-get update
290-
apt-get install -y curl pandoc unzip
290+
apt-get install -y curl pandoc unzip git
291291
- run:
292292
name: Install protoc 3.7.1.
293293
command: |
@@ -311,7 +311,7 @@ jobs:
311311
name: Install system dependencies.
312312
command: |
313313
apt-get update
314-
apt-get install -y curl pandoc unzip
314+
apt-get install -y curl pandoc unzip git
315315
- run:
316316
name: Install protoc 3.7.1.
317317
command: |
@@ -335,7 +335,7 @@ jobs:
335335
name: Install system dependencies.
336336
command: |
337337
apt-get update
338-
apt-get install -y curl pandoc unzip
338+
apt-get install -y curl pandoc unzip git
339339
- run:
340340
name: Install protoc 3.7.1.
341341
command: |
@@ -359,7 +359,7 @@ jobs:
359359
name: Install system dependencies.
360360
command: |
361361
apt-get update
362-
apt-get install -y curl pandoc unzip
362+
apt-get install -y curl pandoc unzip git
363363
- run:
364364
name: Install protoc 3.7.1.
365365
command: |
@@ -383,7 +383,7 @@ jobs:
383383
name: Install system dependencies.
384384
command: |
385385
apt-get update
386-
apt-get install -y curl pandoc unzip
386+
apt-get install -y curl pandoc unzip git
387387
- run:
388388
name: Install protoc 3.7.1.
389389
command: |

packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
{% block content %}
44
from collections import OrderedDict
5-
from typing import Dict, {% if service.any_server_streaming %}Iterable, {% endif %}{% if service.any_client_streaming %}Iterator, {% endif %}Sequence, Tuple, Type, Union
5+
import re
6+
from typing import Callable, Dict, {% if service.any_server_streaming %}Iterable, {% endif %}{% if service.any_client_streaming %}Iterator, {% endif %}Sequence, Tuple, Type, Union
67
import pkg_resources
78

89
import google.api_core.client_options as ClientOptions # type: ignore
@@ -57,7 +58,40 @@ class {{ service.client_name }}Meta(type):
5758
class {{ service.client_name }}(metaclass={{ service.client_name }}Meta):
5859
"""{{ service.meta.doc|rst(width=72, indent=4) }}"""
5960

60-
DEFAULT_OPTIONS = ClientOptions.ClientOptions({% if service.host %}api_endpoint='{{ service.host }}'{% endif %})
61+
@staticmethod
62+
def _get_default_mtls_endpoint(api_endpoint):
63+
"""Convert api endpoint to mTLS endpoint.
64+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
65+
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
66+
Args:
67+
api_endpoint (Optional[str]): the api endpoint to convert.
68+
Returns:
69+
str: converted mTLS api endpoint.
70+
"""
71+
if not api_endpoint:
72+
return api_endpoint
73+
74+
mtls_endpoint_re = re.compile(
75+
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
76+
)
77+
78+
m = mtls_endpoint_re.match(api_endpoint)
79+
name, mtls, sandbox, googledomain = m.groups()
80+
if mtls or not googledomain:
81+
return api_endpoint
82+
83+
if sandbox:
84+
return api_endpoint.replace(
85+
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
86+
)
87+
88+
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
89+
90+
DEFAULT_ENDPOINT = {% if service.host %}'{{ service.host }}'{% else %}None{% endif %}
91+
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
92+
DEFAULT_ENDPOINT
93+
)
94+
DEFAULT_OPTIONS = ClientOptions.ClientOptions(api_endpoint=DEFAULT_ENDPOINT)
6195

6296
@classmethod
6397
def from_service_account_file(cls, filename: str, *args, **kwargs):
@@ -106,23 +140,56 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta):
106140
transport to use. If set to None, a transport is chosen
107141
automatically.
108142
client_options (ClientOptions): Custom options for the client.
143+
(1) The ``api_endpoint`` property can be used to override the
144+
default endpoint provided by the client.
145+
(2) If ``transport`` argument is None, ``client_options`` can be
146+
used to create a mutual TLS transport. If ``api_endpoint`` is
147+
provided and different from the default endpoint, or the
148+
``client_cert_source`` property is provided, mutual TLS
149+
transport will be created if client SSL credentials are found.
150+
Client SSL credentials are obtained from ``client_cert_source``
151+
or application default SSL credentials.
152+
153+
Raises:
154+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
155+
creation failed for any reason.
109156
"""
110157
if isinstance(client_options, dict):
111158
client_options = ClientOptions.from_dict(client_options)
112159

160+
# Set default api endpoint if not set.
161+
if client_options.api_endpoint is None:
162+
client_options.api_endpoint = self.DEFAULT_ENDPOINT
163+
113164
# Save or instantiate the transport.
114165
# Ordinarily, we provide the transport, but allowing a custom transport
115166
# instance provides an extensibility point for unusual situations.
116167
if isinstance(transport, {{ service.name }}Transport):
168+
# transport is a {{ service.name }}Transport instance.
117169
if credentials:
118170
raise ValueError('When providing a transport instance, '
119171
'provide its credentials directly.')
120172
self._transport = transport
121-
else:
173+
elif transport is not None or (
174+
client_options.api_endpoint == self.DEFAULT_ENDPOINT
175+
and client_options.client_cert_source is None
176+
):
177+
# Don't trigger mTLS.
122178
Transport = type(self).get_transport_class(transport)
123179
self._transport = Transport(
180+
credentials=credentials, host=client_options.api_endpoint
181+
)
182+
else:
183+
# Trigger mTLS. If the user overrides endpoint, use it as the mTLS
184+
# endpoint, otherwise use the default mTLS endpoint.
185+
option_endpoint = client_options.api_endpoint
186+
api_mtls_endpoint = self.DEFAULT_MTLS_ENDPOINT if option_endpoint == self.DEFAULT_ENDPOINT else option_endpoint
187+
188+
self._transport = {{ service.name }}GrpcTransport(
124189
credentials=credentials,
125-
host=client_options.api_endpoint{% if service.host %} or '{{ service.host }}'{% endif %},
190+
host=client_options.api_endpoint,
191+
api_mtls_endpoint=api_mtls_endpoint,
192+
client_cert_source=client_options.client_cert_source,
126193
)
127194

128195
{% for method in service.methods.values() -%}

packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
{% extends '_base.py.j2' %}
22

33
{% block content %}
4-
from typing import Callable, Dict
4+
from typing import Callable, Dict, Tuple
55

66
from google.api_core import grpc_helpers # type: ignore
77
{%- if service.has_lro %}
88
from google.api_core import operations_v1 # type: ignore
99
{%- endif %}
1010
from google.auth import credentials # type: ignore
11+
from google.auth.transport.grpc import SslCredentials # type: ignore
12+
1113

1214
import grpc # type: ignore
1315

@@ -35,7 +37,9 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport):
3537
def __init__(self, *,
3638
host: str{% if service.host %} = '{{ service.host }}'{% endif %},
3739
credentials: credentials.Credentials = None,
38-
channel: grpc.Channel = None) -> None:
40+
channel: grpc.Channel = None,
41+
api_mtls_endpoint: str = None,
42+
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None) -> None:
3943
"""Instantiate the transport.
4044

4145
Args:
@@ -49,19 +53,51 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport):
4953
This argument is ignored if ``channel`` is provided.
5054
channel (Optional[grpc.Channel]): A ``Channel`` instance through
5155
which to make calls.
56+
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
57+
provided, it overrides the ``host`` argument and tries to create
58+
a mutual TLS channel with client SSL credentials from
59+
``client_cert_source`` or applicatin default SSL credentials.
60+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
61+
callback to provide client SSL certificate bytes and private key
62+
bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
63+
is None.
64+
65+
Raises:
66+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
67+
creation failed for any reason.
5268
"""
53-
# Sanity check: Ensure that channel and credentials are not both
54-
# provided.
5569
if channel:
70+
# Sanity check: Ensure that channel and credentials are not both
71+
# provided.
5672
credentials = False
5773

74+
# If a channel was explicitly provided, set it.
75+
self._grpc_channel = channel
76+
elif api_mtls_endpoint:
77+
host = api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443"
78+
79+
# Create SSL credentials with client_cert_source or application
80+
# default SSL credentials.
81+
if client_cert_source:
82+
cert, key = client_cert_source()
83+
ssl_credentials = grpc.ssl_channel_credentials(
84+
certificate_chain=cert, private_key=key
85+
)
86+
else:
87+
ssl_credentials = SslCredentials().ssl_credentials
88+
89+
# create a new channel. The provided one is ignored.
90+
self._grpc_channel = grpc_helpers.create_channel(
91+
host,
92+
credentials=credentials,
93+
ssl_credentials=ssl_credentials,
94+
scopes=self.AUTH_SCOPES,
95+
)
96+
5897
# Run the base constructor.
5998
super().__init__(host=host, credentials=credentials)
6099
self._stubs = {} # type: Dict[str, Callable]
61100

62-
# If a channel was explicitly provided, set it.
63-
if channel:
64-
self._grpc_channel = channel
65101

66102
@classmethod
67103
def create_channel(cls,

packages/gapic-generator/gapic/templates/setup.py.j2

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ setuptools.setup(
1616
platforms='Posix; MacOS X; Windows',
1717
include_package_data=True,
1818
install_requires=(
19+
'google-auth >= 1.13.1',
1920
'google-api-core >= 1.8.0, < 2.0.0dev',
2021
'googleapis-common-protos >= 1.5.8',
2122
'grpcio >= 1.10.0',

0 commit comments

Comments
 (0)