CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-auth

Google Authentication Library providing comprehensive authentication mechanisms for Google APIs and services including OAuth 2.0, JWT, and service account credentials

Pending
Overview
Eval results
Files

crypt.mddocs/

Cryptographic Utilities

Token signing and verification utilities supporting RSA and ECDSA algorithms. Provides the cryptographic foundation for JWT token creation, service account authentication, and credential verification.

Capabilities

Base Signer Interface

Abstract base class for cryptographic signers used in JWT token creation and service account authentication.

class Signer(abc.ABC):
    """Abstract base class for cryptographic signers."""
    
    @property
    @abc.abstractmethod
    def key_id(self):
        """
        Optional[str]: The key ID used to identify the private key.
        """
    
    @abc.abstractmethod
    def sign(self, message):
        """
        Sign a message.
        
        Args:
            message (Union[str, bytes]): The message to sign
            
        Returns:
            bytes: The signature
        """

class Verifier(abc.ABC):
    """Abstract base class for cryptographic verifiers."""
    
    @abc.abstractmethod
    def verify(self, message, signature):
        """
        Verify a signature.
        
        Args:
            message (Union[str, bytes]): The message that was signed
            signature (bytes): The signature to verify
            
        Returns:
            bool: True if the signature is valid, False otherwise
        """

RSA Signers and Verifiers

RSA-based cryptographic operations for JWT signing and verification, supporting PKCS#1 v1.5 and PSS padding.

class RSASigner(google.auth.crypt.Signer):
    """RSA-based signer for JWT tokens."""
    
    def __init__(self, private_key, key_id=None):
        """
        Initialize RSA signer.
        
        Args:
            private_key (Union[str, bytes, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey]):
                The RSA private key in PEM format or as a cryptography object
            key_id (str): Optional key identifier
        """
    
    @property
    def key_id(self):
        """Optional[str]: The key ID for this signer."""
    
    def sign(self, message):
        """
        Sign a message using RSA-SHA256.
        
        Args:
            message (Union[str, bytes]): The message to sign
            
        Returns:
            bytes: The RSA signature
        """
    
    @classmethod
    def from_string(cls, key, key_id=None):
        """
        Create an RSA signer from a PEM-encoded key string.
        
        Args:
            key (Union[str, bytes]): The private key in PEM format
            key_id (str): Optional key identifier
            
        Returns:
            RSASigner: The constructed signer
        """

class RSAVerifier(google.auth.crypt.Verifier):
    """RSA-based verifier for JWT tokens."""
    
    def __init__(self, public_key):
        """
        Initialize RSA verifier.
        
        Args:
            public_key (Union[str, bytes, cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey]):
                The RSA public key in PEM format or as a cryptography object
        """
    
    def verify(self, message, signature):
        """
        Verify an RSA signature.
        
        Args:
            message (Union[str, bytes]): The message that was signed
            signature (bytes): The signature to verify
            
        Returns:
            bool: True if signature is valid, False otherwise
        """
    
    @classmethod
    def from_string(cls, key):
        """
        Create an RSA verifier from a PEM-encoded key string.
        
        Args:
            key (Union[str, bytes]): The public key in PEM format
            
        Returns:
            RSAVerifier: The constructed verifier
        """

Usage example:

from google.auth import crypt

# Create RSA signer from PEM key
private_key_pem = """-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
-----END PRIVATE KEY-----"""

signer = crypt.RSASigner.from_string(private_key_pem, key_id='key-1')

# Sign a message
message = b"Hello, World!"
signature = signer.sign(message)

# Verify signature
public_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----"""

verifier = crypt.RSAVerifier.from_string(public_key_pem)
is_valid = verifier.verify(message, signature)
print(f"Signature valid: {is_valid}")

ECDSA Signers and Verifiers

ECDSA P-256 (ES256) cryptographic operations for JWT signing and verification.

class ES256Signer(google.auth.crypt.Signer):
    """ECDSA P-256 signer for JWT tokens."""
    
    def __init__(self, private_key, key_id=None):
        """
        Initialize ECDSA P-256 signer.
        
        Args:
            private_key (Union[str, bytes, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey]):
                The ECDSA private key in PEM format or as a cryptography object
            key_id (str): Optional key identifier
        """
    
    @property
    def key_id(self):
        """Optional[str]: The key ID for this signer."""
    
    def sign(self, message):
        """
        Sign a message using ECDSA P-256 with SHA-256.
        
        Args:
            message (Union[str, bytes]): The message to sign
            
        Returns:
            bytes: The ECDSA signature
        """
    
    @classmethod
    def from_string(cls, key, key_id=None):
        """
        Create an ECDSA signer from a PEM-encoded key string.
        
        Args:
            key (Union[str, bytes]): The private key in PEM format
            key_id (str): Optional key identifier
            
        Returns:
            ES256Signer: The constructed signer
        """

class ES256Verifier(google.auth.crypt.Verifier):
    """ECDSA P-256 verifier for JWT tokens."""
    
    def __init__(self, public_key):
        """
        Initialize ECDSA P-256 verifier.
        
        Args:
            public_key (Union[str, bytes, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey]):
                The ECDSA public key in PEM format or as a cryptography object
        """
    
    def verify(self, message, signature):
        """
        Verify an ECDSA signature.
        
        Args:
            message (Union[str, bytes]): The message that was signed
            signature (bytes): The signature to verify
            
        Returns:
            bool: True if signature is valid, False otherwise
        """
    
    @classmethod
    def from_string(cls, key):
        """
        Create an ECDSA verifier from a PEM-encoded key string.
        
        Args:
            key (Union[str, bytes]): The public key in PEM format
            
        Returns:
            ES256Verifier: The constructed verifier
        """

Usage example:

from google.auth import crypt

# Create ECDSA signer
ecdsa_private_key = """-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg...
-----END PRIVATE KEY-----"""

signer = crypt.ES256Signer.from_string(ecdsa_private_key, key_id='ecdsa-key-1')

# Sign message
message = "Authentication request"
signature = signer.sign(message)

# Verify with corresponding public key
ecdsa_public_key = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----"""

verifier = crypt.ES256Verifier.from_string(ecdsa_public_key)
is_valid = verifier.verify(message, signature)

Certificate Utilities

Utilities for working with X.509 certificates and extracting cryptographic information.

def decode_key_id(key_id):
    """
    Decode a key ID from a certificate or JWK.
    
    Args:
        key_id (Union[str, bytes]): The key ID to decode
        
    Returns:
        str: The decoded key ID
    """

def load_public_key_from_cert(cert_data):
    """
    Load a public key from X.509 certificate data.
    
    Args:
        cert_data (Union[str, bytes]): The certificate in PEM or DER format
        
    Returns:
        Union[RSAPublicKey, EllipticCurvePublicKey]: The extracted public key
    """

def extract_subject_from_cert(cert_data):
    """
    Extract the subject information from an X.509 certificate.
    
    Args:
        cert_data (Union[str, bytes]): The certificate in PEM or DER format
        
    Returns:
        Mapping[str, str]: The subject information
    """

Service Account Key Utilities

Utilities for working with Google service account keys and extracting signers.

def load_signer_from_info(info, require=None):
    """
    Load a signer from service account info.
    
    Args:
        info (Mapping[str, str]): The service account info dictionary
        require (Sequence[str]): Required fields in the info
        
    Returns:
        Tuple[google.auth.crypt.Signer, str]: The signer and service account email
        
    Raises:
        ValueError: If required fields are missing or invalid
    """

def load_signer_from_file(filename, require=None):
    """
    Load a signer from a service account JSON file.
    
    Args:
        filename (str): Path to the service account JSON file
        require (Sequence[str]): Required fields in the file
        
    Returns:
        Tuple[google.auth.crypt.Signer, str]: The signer and service account email
    """

Usage example:

from google.auth import crypt
import json

# Load signer from service account file
signer, email = crypt.load_signer_from_file('/path/to/service-account.json')
print(f"Loaded signer for: {email}")
print(f"Key ID: {signer.key_id}")

# Load from info dictionary
with open('/path/to/service-account.json') as f:
    info = json.load(f)

signer, email = crypt.load_signer_from_info(info)

# Use signer for JWT creation
from google.auth import jwt
import time

payload = {
    'iss': email,
    'sub': email,
    'aud': 'https://example.googleapis.com/',
    'iat': int(time.time()),
    'exp': int(time.time()) + 3600
}

token = jwt.encode(payload, signer)

Error Handling

class MalformedError(google.auth.exceptions.GoogleAuthError):
    """Raised when cryptographic data is malformed."""
    
class InvalidKeyError(google.auth.exceptions.GoogleAuthError):
    """Raised when a cryptographic key is invalid."""

Common cryptographic error scenarios:

  • Invalid or malformed private/public keys
  • Unsupported key formats or algorithms
  • Key size or curve parameter mismatches
  • Signature verification failures
  • Missing or invalid key IDs
  • Certificate parsing errors
  • Incompatible cryptographic library versions

Install with Tessl CLI

npx tessl i tessl/pypi-google-auth

docs

adc.md

async.md

crypt.md

external-accounts.md

index.md

jwt.md

oauth2-users.md

service-accounts.md

transport.md

tile.json