CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-grpcio

HTTP/2-based RPC framework with synchronous and asynchronous APIs for building distributed systems

Pending
Overview
Eval results
Files

security-authentication.mddocs/

Security and Authentication

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.

Capabilities

Channel Credentials

Client-side credentials for establishing secure connections with various authentication mechanisms.

def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None) -> ChannelCredentials:
    """
    Creates a ChannelCredentials for use with an SSL-enabled Channel.

    Parameters:
    - root_certificates: PEM-encoded root certificates as bytes, or None for default
    - private_key: PEM-encoded private key as bytes, or None if no client cert
    - certificate_chain: PEM-encoded certificate chain as bytes, or None if no client cert

    Returns:
    ChannelCredentials: Credentials for use with secure_channel()
    """

def xds_channel_credentials(fallback_credentials=None) -> ChannelCredentials:
    """
    Creates a ChannelCredentials for use with xDS (EXPERIMENTAL).

    Parameters:
    - fallback_credentials: Credentials to use if xDS connection fails

    Returns:
    ChannelCredentials: xDS-enabled credentials
    """

def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP) -> ChannelCredentials:
    """
    Creates a local ChannelCredentials for local connections (EXPERIMENTAL).

    Parameters:
    - local_connect_type: Either LocalConnectionType.UDS or LocalConnectionType.LOCAL_TCP

    Returns:
    ChannelCredentials: Credentials for local connections
    """

def alts_channel_credentials(service_accounts=None) -> ChannelCredentials:
    """
    Creates a ChannelCredentials for use with ALTS in GCP (EXPERIMENTAL).

    Parameters:
    - service_accounts: List of server identities accepted by the client

    Returns:
    ChannelCredentials: ALTS credentials for GCP environments
    """

def compute_engine_channel_credentials(call_credentials: CallCredentials) -> ChannelCredentials:
    """
    Creates a compute engine channel credential for GCP.

    Parameters:
    - call_credentials: CallCredentials that authenticates the VM's service account

    Returns:
    ChannelCredentials: Compute Engine credentials
    """

Usage Examples:

# Basic SSL/TLS (uses system root certificates)
credentials = grpc.ssl_channel_credentials()
channel = grpc.secure_channel('secure-server.com:443', credentials)

# SSL with custom root certificates
with open('ca-cert.pem', 'rb') as f:
    root_certs = f.read()
credentials = grpc.ssl_channel_credentials(root_certificates=root_certs)
channel = grpc.secure_channel('internal-server.com:443', credentials)

# Mutual TLS (client certificate authentication)
with open('ca-cert.pem', 'rb') as f:
    root_certs = f.read()
with open('client-key.pem', 'rb') as f:
    private_key = f.read()
with open('client-cert.pem', 'rb') as f:
    cert_chain = f.read()

credentials = grpc.ssl_channel_credentials(
    root_certificates=root_certs,
    private_key=private_key,
    certificate_chain=cert_chain
)
channel = grpc.secure_channel('mtls-server.com:443', credentials)

# Local connections (Unix domain sockets)
local_creds = grpc.local_channel_credentials(grpc.LocalConnectionType.UDS)
channel = grpc.secure_channel('unix:///tmp/grpc.sock', local_creds)

# ALTS in Google Cloud Platform
alts_creds = grpc.alts_channel_credentials(['service-account@project.iam.gserviceaccount.com'])
channel = grpc.secure_channel('internal-service:443', alts_creds)

Call Credentials

Per-call authentication credentials for OAuth2, access tokens, and custom authentication mechanisms.

def metadata_call_credentials(metadata_plugin: AuthMetadataPlugin, name=None) -> CallCredentials:
    """
    Construct CallCredentials from an AuthMetadataPlugin.

    Parameters:
    - metadata_plugin: An AuthMetadataPlugin for authentication
    - name: Optional name for the plugin

    Returns:
    CallCredentials: Credentials from the metadata plugin
    """

def access_token_call_credentials(access_token: str) -> CallCredentials:
    """
    Construct CallCredentials from an access token.

    Parameters:
    - access_token: String to place in authorization header

    Returns:
    CallCredentials: Credentials using the access token
    """

def composite_call_credentials(*call_credentials) -> CallCredentials:
    """
    Compose multiple CallCredentials to make a new CallCredentials.

    Parameters:
    - call_credentials: At least two CallCredentials objects

    Returns:
    CallCredentials: Composed credentials
    """

def composite_channel_credentials(channel_credentials: ChannelCredentials, *call_credentials) -> ChannelCredentials:
    """
    Compose a ChannelCredentials and one or more CallCredentials.

    Parameters:
    - channel_credentials: A ChannelCredentials object
    - call_credentials: One or more CallCredentials objects

    Returns:
    ChannelCredentials: Composed credentials
    """

Usage Examples:

# OAuth2 access token
access_token = "ya29.c.Kp6B9QEAAAExampleToken..."
call_creds = grpc.access_token_call_credentials(access_token)

# Custom authentication plugin
class CustomAuthPlugin(grpc.AuthMetadataPlugin):
    def __call__(self, context, callback):
        # Custom logic to get auth metadata
        auth_metadata = [('authorization', 'Bearer custom-token')]
        callback(auth_metadata, None)

custom_call_creds = grpc.metadata_call_credentials(CustomAuthPlugin())

# Composite credentials (SSL + OAuth2)
ssl_creds = grpc.ssl_channel_credentials()
oauth_creds = grpc.access_token_call_credentials(access_token)
composite_creds = grpc.composite_channel_credentials(ssl_creds, oauth_creds)

channel = grpc.secure_channel('api.example.com:443', composite_creds)

# Multiple call credentials
api_key_plugin = ApiKeyAuthPlugin()
oauth_plugin = OAuthPlugin()

api_key_creds = grpc.metadata_call_credentials(api_key_plugin)
oauth_creds = grpc.metadata_call_credentials(oauth_plugin)
combined_call_creds = grpc.composite_call_credentials(api_key_creds, oauth_creds)

ssl_creds = grpc.ssl_channel_credentials()
final_creds = grpc.composite_channel_credentials(ssl_creds, combined_call_creds)

Server Credentials

Server-side credentials for accepting secure connections with certificate management and client authentication.

def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False) -> ServerCredentials:
    """
    Creates a ServerCredentials for use with an SSL-enabled Server.

    Parameters:
    - private_key_certificate_chain_pairs: List of (private_key, certificate_chain) pairs
    - root_certificates: Optional PEM-encoded client root certificates for client auth
    - require_client_auth: Whether to require clients to be authenticated

    Returns:
    ServerCredentials: Server credentials for add_secure_port()

    Raises:
    ValueError: If no certificate pairs provided or invalid client auth config
    """

def xds_server_credentials(fallback_credentials: ServerCredentials) -> ServerCredentials:
    """
    Creates a ServerCredentials for use with xDS (EXPERIMENTAL).

    Parameters:
    - fallback_credentials: Credentials to use if xDS connection fails

    Returns:
    ServerCredentials: xDS-enabled server credentials
    """

def insecure_server_credentials() -> ServerCredentials:
    """
    Creates a credentials object directing the server to use no credentials (EXPERIMENTAL).
    For use with other credentials objects, not directly with add_secure_port.

    Returns:
    ServerCredentials: Insecure server credentials
    """

def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP) -> ServerCredentials:
    """
    Creates a local ServerCredentials for local connections (EXPERIMENTAL).

    Parameters:
    - local_connect_type: Either LocalConnectionType.UDS or LocalConnectionType.LOCAL_TCP

    Returns:
    ServerCredentials: Credentials for local server connections
    """

def alts_server_credentials() -> ServerCredentials:
    """
    Creates a ServerCredentials for use with ALTS in GCP (EXPERIMENTAL).

    Returns:
    ServerCredentials: ALTS credentials for GCP environments
    """

def dynamic_ssl_server_credentials(initial_certificate_configuration, certificate_configuration_fetcher, require_client_authentication=False) -> ServerCredentials:
    """
    Creates a ServerCredentials with dynamic certificate updates.

    Parameters:
    - initial_certificate_configuration: Initial ServerCertificateConfiguration
    - certificate_configuration_fetcher: Callable returning new certificate config
    - require_client_authentication: Whether to require client authentication

    Returns:
    ServerCredentials: Dynamic SSL server credentials
    """

Usage Examples:

# Basic SSL server
with open('server-key.pem', 'rb') as f:
    private_key = f.read()
with open('server-cert.pem', 'rb') as f:
    certificate = f.read()

server_creds = grpc.ssl_server_credentials([(private_key, certificate)])
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
server.add_secure_port('[::]:50051', server_creds)

# Mutual TLS server (client certificate required)
with open('ca-cert.pem', 'rb') as f:
    root_certs = f.read()

server_creds = grpc.ssl_server_credentials(
    [(private_key, certificate)],
    root_certificates=root_certs,
    require_client_auth=True
)
server.add_secure_port('[::]:50051', server_creds)

# Multiple certificate pairs (for different domains)
cert_pairs = [
    (key1, cert1),  # For domain1.com
    (key2, cert2),  # For domain2.com
]
server_creds = grpc.ssl_server_credentials(cert_pairs)

# Dynamic certificate updates
def cert_fetcher():
    # Logic to fetch updated certificate
    if should_update_cert():
        return grpc.ssl_server_certificate_configuration([(new_key, new_cert)])
    return None  # No update needed

initial_config = grpc.ssl_server_certificate_configuration([(private_key, certificate)])
dynamic_creds = grpc.dynamic_ssl_server_credentials(
    initial_config,
    cert_fetcher,
    require_client_authentication=True
)

Certificate Configuration

Dynamic certificate management for servers requiring certificate rotation or multi-domain support.

def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, root_certificates=None) -> ServerCertificateConfiguration:
    """
    Creates a ServerCertificateConfiguration for use with a Server.

    Parameters:
    - private_key_certificate_chain_pairs: Collection of (private_key, certificate) pairs
    - root_certificates: Optional PEM-encoded client root certificates

    Returns:
    ServerCertificateConfiguration: Configuration for certificate fetching callback

    Raises:
    ValueError: If no certificate pairs provided
    """

Authentication Interfaces

Base interfaces for implementing custom authentication mechanisms.

class AuthMetadataContext(abc.ABC):
    """
    Provides information to call credentials metadata plugins.
    
    Attributes:
    - service_url: String URL of the service being called
    - method_name: String of the fully qualified method name being called
    """

class AuthMetadataPluginCallback(abc.ABC):
    """Callback object received by a metadata plugin."""
    
    def __call__(self, metadata, error):
        """
        Passes authentication metadata for an RPC to the gRPC runtime.

        Parameters:
        - metadata: The metadata used to construct CallCredentials
        - error: An Exception to indicate error or None for success
        """

class AuthMetadataPlugin(abc.ABC):
    """A specification for custom authentication."""
    
    def __call__(self, context: AuthMetadataContext, callback: AuthMetadataPluginCallback):
        """
        Implements authentication by passing metadata to a callback.
        Called asynchronously in a separate thread.

        Parameters:
        - context: AuthMetadataContext providing information on the RPC
        - callback: AuthMetadataPluginCallback to be invoked with auth metadata
        """

Usage Example:

class JWTAuthPlugin(grpc.AuthMetadataPlugin):
    def __init__(self, jwt_token):
        self.jwt_token = jwt_token
    
    def __call__(self, context, callback):
        try:
            # Validate token is still valid
            if self.is_token_expired():
                callback(None, Exception("JWT token expired"))
                return
            
            # Add authorization header
            metadata = [('authorization', f'Bearer {self.jwt_token}')]
            callback(metadata, None)
        except Exception as e:
            callback(None, e)

# Usage
jwt_plugin = JWTAuthPlugin("eyJ0eXAiOiJKV1QiLCJhbGciOi...")
call_creds = grpc.metadata_call_credentials(jwt_plugin)

ssl_creds = grpc.ssl_channel_credentials()
composite_creds = grpc.composite_channel_credentials(ssl_creds, call_creds)
channel = grpc.secure_channel('api.example.com:443', composite_creds)

Types

class ChannelCredentials:
    """
    An encapsulation of the data required to create a secure Channel.
    No public interface - instances exist to be passed to secure_channel().
    """
    def __init__(self, credentials): ...

class CallCredentials:
    """
    An encapsulation of the data required to assert an identity over a call.
    Must be used with secure Channel, otherwise metadata will not be transmitted.
    """
    def __init__(self, credentials): ...

class ServerCredentials:
    """
    An encapsulation of the data required to open a secure port on a Server.
    No public interface - instances exist to be passed to add_secure_port().
    """
    def __init__(self, credentials): ...

class ServerCertificateConfiguration:
    """
    A certificate configuration for use with an SSL-enabled Server.
    Instances can be returned in certificate configuration fetching callback.
    """
    def __init__(self, certificate_configuration): ...

class LocalConnectionType(enum.Enum):
    """Types of local connection for local credential creation."""
    UDS = ...       # Unix domain socket connections
    LOCAL_TCP = ... # Local TCP connections

Install with Tessl CLI

npx tessl i tessl/pypi-grpcio

docs

async-api.md

channel-management.md

error-handling.md

index.md

interceptors.md

protobuf-integration.md

rpc-patterns.md

security-authentication.md

server-implementation.md

tile.json