0
# Security and Authentication
1
2
Comprehensive security framework providing SSL/TLS credentials, mutual authentication, OAuth2 integration, ALTS for GCP environments, local connections, and custom authentication plugins for enterprise security requirements.
3
4
## Capabilities
5
6
### Channel Credentials
7
8
Client-side credentials for establishing secure connections with various authentication mechanisms.
9
10
```python { .api }
11
def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None) -> ChannelCredentials:
12
"""
13
Creates a ChannelCredentials for use with an SSL-enabled Channel.
14
15
Parameters:
16
- root_certificates: PEM-encoded root certificates as bytes, or None for default
17
- private_key: PEM-encoded private key as bytes, or None if no client cert
18
- certificate_chain: PEM-encoded certificate chain as bytes, or None if no client cert
19
20
Returns:
21
ChannelCredentials: Credentials for use with secure_channel()
22
"""
23
24
def xds_channel_credentials(fallback_credentials=None) -> ChannelCredentials:
25
"""
26
Creates a ChannelCredentials for use with xDS (EXPERIMENTAL).
27
28
Parameters:
29
- fallback_credentials: Credentials to use if xDS connection fails
30
31
Returns:
32
ChannelCredentials: xDS-enabled credentials
33
"""
34
35
def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP) -> ChannelCredentials:
36
"""
37
Creates a local ChannelCredentials for local connections (EXPERIMENTAL).
38
39
Parameters:
40
- local_connect_type: Either LocalConnectionType.UDS or LocalConnectionType.LOCAL_TCP
41
42
Returns:
43
ChannelCredentials: Credentials for local connections
44
"""
45
46
def alts_channel_credentials(service_accounts=None) -> ChannelCredentials:
47
"""
48
Creates a ChannelCredentials for use with ALTS in GCP (EXPERIMENTAL).
49
50
Parameters:
51
- service_accounts: List of server identities accepted by the client
52
53
Returns:
54
ChannelCredentials: ALTS credentials for GCP environments
55
"""
56
57
def compute_engine_channel_credentials(call_credentials: CallCredentials) -> ChannelCredentials:
58
"""
59
Creates a compute engine channel credential for GCP.
60
61
Parameters:
62
- call_credentials: CallCredentials that authenticates the VM's service account
63
64
Returns:
65
ChannelCredentials: Compute Engine credentials
66
"""
67
```
68
69
**Usage Examples:**
70
71
```python
72
# Basic SSL/TLS (uses system root certificates)
73
credentials = grpc.ssl_channel_credentials()
74
channel = grpc.secure_channel('secure-server.com:443', credentials)
75
76
# SSL with custom root certificates
77
with open('ca-cert.pem', 'rb') as f:
78
root_certs = f.read()
79
credentials = grpc.ssl_channel_credentials(root_certificates=root_certs)
80
channel = grpc.secure_channel('internal-server.com:443', credentials)
81
82
# Mutual TLS (client certificate authentication)
83
with open('ca-cert.pem', 'rb') as f:
84
root_certs = f.read()
85
with open('client-key.pem', 'rb') as f:
86
private_key = f.read()
87
with open('client-cert.pem', 'rb') as f:
88
cert_chain = f.read()
89
90
credentials = grpc.ssl_channel_credentials(
91
root_certificates=root_certs,
92
private_key=private_key,
93
certificate_chain=cert_chain
94
)
95
channel = grpc.secure_channel('mtls-server.com:443', credentials)
96
97
# Local connections (Unix domain sockets)
98
local_creds = grpc.local_channel_credentials(grpc.LocalConnectionType.UDS)
99
channel = grpc.secure_channel('unix:///tmp/grpc.sock', local_creds)
100
101
# ALTS in Google Cloud Platform
102
alts_creds = grpc.alts_channel_credentials(['service-account@project.iam.gserviceaccount.com'])
103
channel = grpc.secure_channel('internal-service:443', alts_creds)
104
```
105
106
### Call Credentials
107
108
Per-call authentication credentials for OAuth2, access tokens, and custom authentication mechanisms.
109
110
```python { .api }
111
def metadata_call_credentials(metadata_plugin: AuthMetadataPlugin, name=None) -> CallCredentials:
112
"""
113
Construct CallCredentials from an AuthMetadataPlugin.
114
115
Parameters:
116
- metadata_plugin: An AuthMetadataPlugin for authentication
117
- name: Optional name for the plugin
118
119
Returns:
120
CallCredentials: Credentials from the metadata plugin
121
"""
122
123
def access_token_call_credentials(access_token: str) -> CallCredentials:
124
"""
125
Construct CallCredentials from an access token.
126
127
Parameters:
128
- access_token: String to place in authorization header
129
130
Returns:
131
CallCredentials: Credentials using the access token
132
"""
133
134
def composite_call_credentials(*call_credentials) -> CallCredentials:
135
"""
136
Compose multiple CallCredentials to make a new CallCredentials.
137
138
Parameters:
139
- call_credentials: At least two CallCredentials objects
140
141
Returns:
142
CallCredentials: Composed credentials
143
"""
144
145
def composite_channel_credentials(channel_credentials: ChannelCredentials, *call_credentials) -> ChannelCredentials:
146
"""
147
Compose a ChannelCredentials and one or more CallCredentials.
148
149
Parameters:
150
- channel_credentials: A ChannelCredentials object
151
- call_credentials: One or more CallCredentials objects
152
153
Returns:
154
ChannelCredentials: Composed credentials
155
"""
156
```
157
158
**Usage Examples:**
159
160
```python
161
# OAuth2 access token
162
access_token = "ya29.c.Kp6B9QEAAAExampleToken..."
163
call_creds = grpc.access_token_call_credentials(access_token)
164
165
# Custom authentication plugin
166
class CustomAuthPlugin(grpc.AuthMetadataPlugin):
167
def __call__(self, context, callback):
168
# Custom logic to get auth metadata
169
auth_metadata = [('authorization', 'Bearer custom-token')]
170
callback(auth_metadata, None)
171
172
custom_call_creds = grpc.metadata_call_credentials(CustomAuthPlugin())
173
174
# Composite credentials (SSL + OAuth2)
175
ssl_creds = grpc.ssl_channel_credentials()
176
oauth_creds = grpc.access_token_call_credentials(access_token)
177
composite_creds = grpc.composite_channel_credentials(ssl_creds, oauth_creds)
178
179
channel = grpc.secure_channel('api.example.com:443', composite_creds)
180
181
# Multiple call credentials
182
api_key_plugin = ApiKeyAuthPlugin()
183
oauth_plugin = OAuthPlugin()
184
185
api_key_creds = grpc.metadata_call_credentials(api_key_plugin)
186
oauth_creds = grpc.metadata_call_credentials(oauth_plugin)
187
combined_call_creds = grpc.composite_call_credentials(api_key_creds, oauth_creds)
188
189
ssl_creds = grpc.ssl_channel_credentials()
190
final_creds = grpc.composite_channel_credentials(ssl_creds, combined_call_creds)
191
```
192
193
### Server Credentials
194
195
Server-side credentials for accepting secure connections with certificate management and client authentication.
196
197
```python { .api }
198
def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False) -> ServerCredentials:
199
"""
200
Creates a ServerCredentials for use with an SSL-enabled Server.
201
202
Parameters:
203
- private_key_certificate_chain_pairs: List of (private_key, certificate_chain) pairs
204
- root_certificates: Optional PEM-encoded client root certificates for client auth
205
- require_client_auth: Whether to require clients to be authenticated
206
207
Returns:
208
ServerCredentials: Server credentials for add_secure_port()
209
210
Raises:
211
ValueError: If no certificate pairs provided or invalid client auth config
212
"""
213
214
def xds_server_credentials(fallback_credentials: ServerCredentials) -> ServerCredentials:
215
"""
216
Creates a ServerCredentials for use with xDS (EXPERIMENTAL).
217
218
Parameters:
219
- fallback_credentials: Credentials to use if xDS connection fails
220
221
Returns:
222
ServerCredentials: xDS-enabled server credentials
223
"""
224
225
def insecure_server_credentials() -> ServerCredentials:
226
"""
227
Creates a credentials object directing the server to use no credentials (EXPERIMENTAL).
228
For use with other credentials objects, not directly with add_secure_port.
229
230
Returns:
231
ServerCredentials: Insecure server credentials
232
"""
233
234
def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP) -> ServerCredentials:
235
"""
236
Creates a local ServerCredentials for local connections (EXPERIMENTAL).
237
238
Parameters:
239
- local_connect_type: Either LocalConnectionType.UDS or LocalConnectionType.LOCAL_TCP
240
241
Returns:
242
ServerCredentials: Credentials for local server connections
243
"""
244
245
def alts_server_credentials() -> ServerCredentials:
246
"""
247
Creates a ServerCredentials for use with ALTS in GCP (EXPERIMENTAL).
248
249
Returns:
250
ServerCredentials: ALTS credentials for GCP environments
251
"""
252
253
def dynamic_ssl_server_credentials(initial_certificate_configuration, certificate_configuration_fetcher, require_client_authentication=False) -> ServerCredentials:
254
"""
255
Creates a ServerCredentials with dynamic certificate updates.
256
257
Parameters:
258
- initial_certificate_configuration: Initial ServerCertificateConfiguration
259
- certificate_configuration_fetcher: Callable returning new certificate config
260
- require_client_authentication: Whether to require client authentication
261
262
Returns:
263
ServerCredentials: Dynamic SSL server credentials
264
"""
265
```
266
267
**Usage Examples:**
268
269
```python
270
# Basic SSL server
271
with open('server-key.pem', 'rb') as f:
272
private_key = f.read()
273
with open('server-cert.pem', 'rb') as f:
274
certificate = f.read()
275
276
server_creds = grpc.ssl_server_credentials([(private_key, certificate)])
277
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
278
server.add_secure_port('[::]:50051', server_creds)
279
280
# Mutual TLS server (client certificate required)
281
with open('ca-cert.pem', 'rb') as f:
282
root_certs = f.read()
283
284
server_creds = grpc.ssl_server_credentials(
285
[(private_key, certificate)],
286
root_certificates=root_certs,
287
require_client_auth=True
288
)
289
server.add_secure_port('[::]:50051', server_creds)
290
291
# Multiple certificate pairs (for different domains)
292
cert_pairs = [
293
(key1, cert1), # For domain1.com
294
(key2, cert2), # For domain2.com
295
]
296
server_creds = grpc.ssl_server_credentials(cert_pairs)
297
298
# Dynamic certificate updates
299
def cert_fetcher():
300
# Logic to fetch updated certificate
301
if should_update_cert():
302
return grpc.ssl_server_certificate_configuration([(new_key, new_cert)])
303
return None # No update needed
304
305
initial_config = grpc.ssl_server_certificate_configuration([(private_key, certificate)])
306
dynamic_creds = grpc.dynamic_ssl_server_credentials(
307
initial_config,
308
cert_fetcher,
309
require_client_authentication=True
310
)
311
```
312
313
### Certificate Configuration
314
315
Dynamic certificate management for servers requiring certificate rotation or multi-domain support.
316
317
```python { .api }
318
def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, root_certificates=None) -> ServerCertificateConfiguration:
319
"""
320
Creates a ServerCertificateConfiguration for use with a Server.
321
322
Parameters:
323
- private_key_certificate_chain_pairs: Collection of (private_key, certificate) pairs
324
- root_certificates: Optional PEM-encoded client root certificates
325
326
Returns:
327
ServerCertificateConfiguration: Configuration for certificate fetching callback
328
329
Raises:
330
ValueError: If no certificate pairs provided
331
"""
332
```
333
334
### Authentication Interfaces
335
336
Base interfaces for implementing custom authentication mechanisms.
337
338
```python { .api }
339
class AuthMetadataContext(abc.ABC):
340
"""
341
Provides information to call credentials metadata plugins.
342
343
Attributes:
344
- service_url: String URL of the service being called
345
- method_name: String of the fully qualified method name being called
346
"""
347
348
class AuthMetadataPluginCallback(abc.ABC):
349
"""Callback object received by a metadata plugin."""
350
351
def __call__(self, metadata, error):
352
"""
353
Passes authentication metadata for an RPC to the gRPC runtime.
354
355
Parameters:
356
- metadata: The metadata used to construct CallCredentials
357
- error: An Exception to indicate error or None for success
358
"""
359
360
class AuthMetadataPlugin(abc.ABC):
361
"""A specification for custom authentication."""
362
363
def __call__(self, context: AuthMetadataContext, callback: AuthMetadataPluginCallback):
364
"""
365
Implements authentication by passing metadata to a callback.
366
Called asynchronously in a separate thread.
367
368
Parameters:
369
- context: AuthMetadataContext providing information on the RPC
370
- callback: AuthMetadataPluginCallback to be invoked with auth metadata
371
"""
372
```
373
374
**Usage Example:**
375
376
```python
377
class JWTAuthPlugin(grpc.AuthMetadataPlugin):
378
def __init__(self, jwt_token):
379
self.jwt_token = jwt_token
380
381
def __call__(self, context, callback):
382
try:
383
# Validate token is still valid
384
if self.is_token_expired():
385
callback(None, Exception("JWT token expired"))
386
return
387
388
# Add authorization header
389
metadata = [('authorization', f'Bearer {self.jwt_token}')]
390
callback(metadata, None)
391
except Exception as e:
392
callback(None, e)
393
394
# Usage
395
jwt_plugin = JWTAuthPlugin("eyJ0eXAiOiJKV1QiLCJhbGciOi...")
396
call_creds = grpc.metadata_call_credentials(jwt_plugin)
397
398
ssl_creds = grpc.ssl_channel_credentials()
399
composite_creds = grpc.composite_channel_credentials(ssl_creds, call_creds)
400
channel = grpc.secure_channel('api.example.com:443', composite_creds)
401
```
402
403
## Types
404
405
```python { .api }
406
class ChannelCredentials:
407
"""
408
An encapsulation of the data required to create a secure Channel.
409
No public interface - instances exist to be passed to secure_channel().
410
"""
411
def __init__(self, credentials): ...
412
413
class CallCredentials:
414
"""
415
An encapsulation of the data required to assert an identity over a call.
416
Must be used with secure Channel, otherwise metadata will not be transmitted.
417
"""
418
def __init__(self, credentials): ...
419
420
class ServerCredentials:
421
"""
422
An encapsulation of the data required to open a secure port on a Server.
423
No public interface - instances exist to be passed to add_secure_port().
424
"""
425
def __init__(self, credentials): ...
426
427
class ServerCertificateConfiguration:
428
"""
429
A certificate configuration for use with an SSL-enabled Server.
430
Instances can be returned in certificate configuration fetching callback.
431
"""
432
def __init__(self, certificate_configuration): ...
433
434
class LocalConnectionType(enum.Enum):
435
"""Types of local connection for local credential creation."""
436
UDS = ... # Unix domain socket connections
437
LOCAL_TCP = ... # Local TCP connections
438
```