CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-keyvault-certificates

Microsoft Corporation Key Vault Certificates Client Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

policy-management.mddocs/

Policy Management

Certificate policy configuration and management for controlling certificate properties, key specifications, lifetime actions, and issuer settings. Policies define how certificates are created, renewed, and managed throughout their lifecycle.

Capabilities

Certificate Policy Retrieval

Get the current policy for a certificate to understand its configuration and management settings.

def get_certificate_policy(certificate_name: str, **kwargs: Any) -> CertificatePolicy:
    """
    Get the policy for a certificate.

    Parameters:
    - certificate_name: The name of the certificate

    Returns:
    CertificatePolicy: The certificate's management policy

    Raises:
    ResourceNotFoundError: If the certificate doesn't exist
    HttpResponseError: For service-side errors
    """

Certificate Policy Updates

Update the management policy for an existing certificate. Policy changes affect future operations and renewals.

def update_certificate_policy(
    certificate_name: str, 
    policy: CertificatePolicy, 
    **kwargs: Any
) -> CertificatePolicy:
    """
    Update the policy for a certificate.

    Parameters:
    - certificate_name: The name of the certificate
    - policy: The updated certificate policy

    Returns:
    CertificatePolicy: The updated policy

    Raises:
    ResourceNotFoundError: If the certificate doesn't exist
    ValidationError: If the policy is invalid
    HttpResponseError: For service-side errors
    """

Policy Configuration

Default Policy Creation

from azure.keyvault.certificates import CertificatePolicy

# Get default policy
default_policy = CertificatePolicy.get_default()
print(f"Default issuer: {default_policy.issuer_name}")
print(f"Default key type: {default_policy.key_type}")
print(f"Default validity: {default_policy.validity_in_months} months")

Custom Policy Creation

from azure.keyvault.certificates import (
    CertificatePolicy, 
    KeyType, 
    CertificateContentType,
    KeyUsageType,
    CertificatePolicyAction,
    LifetimeAction,
    WellKnownIssuerNames
)

# Create custom policy
custom_policy = CertificatePolicy(
    issuer_name=WellKnownIssuerNames.self,
    subject="CN=myapp.example.com",
    san_dns_names=["myapp.example.com", "www.myapp.example.com"],
    exportable=True,
    key_type=KeyType.rsa,
    key_size=2048,
    reuse_key=False,
    content_type=CertificateContentType.pkcs12,
    validity_in_months=12,
    key_usage=[
        KeyUsageType.digital_signature,
        KeyUsageType.key_encipherment
    ]
)

# Add lifetime action for auto-renewal
lifetime_action = LifetimeAction(
    action=CertificatePolicyAction.auto_renew,
    days_before_expiry=30
)
custom_policy.lifetime_actions = [lifetime_action]

Subject Alternative Names (SAN) Configuration

# DNS names
policy = CertificatePolicy.get_default()
policy.san_dns_names = [
    "api.example.com",
    "www.api.example.com", 
    "staging.api.example.com"
]

# Email addresses
policy.san_emails = [
    "admin@example.com",
    "security@example.com"
]

# User Principal Names (for internal certificates)
policy.san_upns = [
    "service@company.com",
    "app@company.com"
]

Key Configuration

# RSA key configuration
policy = CertificatePolicy.get_default()
policy.key_type = KeyType.rsa
policy.key_size = 4096  # Higher security
policy.reuse_key = False  # Generate new key for each renewal

# Elliptic Curve key configuration
from azure.keyvault.certificates import KeyCurveName

policy.key_type = KeyType.ec
policy.key_curve_name = KeyCurveName.p_384
policy.key_usage = [
    KeyUsageType.digital_signature,
    KeyUsageType.key_agreement
]

# HSM-backed keys (for enhanced security)
policy.key_type = KeyType.rsa_hsm
policy.key_size = 2048

Lifetime Actions Configuration

# Auto-renewal 30 days before expiry
auto_renew_action = LifetimeAction(
    action=CertificatePolicyAction.auto_renew,
    days_before_expiry=30
)

# Email notification 60 days before expiry  
email_action = LifetimeAction(
    action=CertificatePolicyAction.email_contacts,
    days_before_expiry=60
)

# Percentage-based trigger (e.g., at 80% of certificate lifetime)
percentage_action = LifetimeAction(
    action=CertificatePolicyAction.email_contacts,
    percentage_before_expiry=20  # 20% remaining = 80% expired
)

policy.lifetime_actions = [email_action, auto_renew_action]

Usage Examples

Complete Policy Management Workflow

from azure.keyvault.certificates import CertificateClient, CertificatePolicy

# Create comprehensive policy
def create_production_policy(domain_name, additional_domains=None):
    """Create a production-ready certificate policy."""
    
    policy = CertificatePolicy(
        issuer_name=WellKnownIssuerNames.self,  # Or external issuer
        subject=f"CN={domain_name}",
        exportable=True,
        key_type=KeyType.rsa,
        key_size=2048,
        reuse_key=False,
        content_type=CertificateContentType.pkcs12,
        validity_in_months=12,
        key_usage=[
            KeyUsageType.digital_signature,
            KeyUsageType.key_encipherment
        ]
    )
    
    # Configure SAN
    san_domains = [domain_name]
    if additional_domains:
        san_domains.extend(additional_domains)
    policy.san_dns_names = san_domains
    
    # Configure lifetime actions
    policy.lifetime_actions = [
        LifetimeAction(
            action=CertificatePolicyAction.email_contacts,
            days_before_expiry=60
        ),
        LifetimeAction(
            action=CertificatePolicyAction.auto_renew,
            days_before_expiry=30
        )
    ]
    
    return policy

# Create and apply policy
production_policy = create_production_policy(
    "myapp.example.com",
    ["api.myapp.example.com", "www.myapp.example.com"]
)

# Create certificate with custom policy
create_poller = client.begin_create_certificate(
    certificate_name="production-cert",
    policy=production_policy
)
certificate = create_poller.result()

Policy Inspection and Updates

# Get and inspect current policy
current_policy = client.get_certificate_policy("production-cert")

print(f"Current issuer: {current_policy.issuer_name}")
print(f"Key type: {current_policy.key_type}")
print(f"Key size: {current_policy.key_size}")
print(f"Validity period: {current_policy.validity_in_months} months")
print(f"SAN DNS names: {current_policy.san_dns_names}")
print(f"Lifetime actions: {len(current_policy.lifetime_actions)}")

# Update policy to extend validity
current_policy.validity_in_months = 24  # 2 years

# Add email notification earlier
early_warning = LifetimeAction(
    action=CertificatePolicyAction.email_contacts,
    days_before_expiry=90
)
current_policy.lifetime_actions.insert(0, early_warning)

# Apply updated policy
updated_policy = client.update_certificate_policy(
    certificate_name="production-cert",
    policy=current_policy
)

print("Policy updated successfully")

Policy Templates

class CertificatePolicyTemplates:
    """Common certificate policy templates."""
    
    @staticmethod
    def web_server_ssl(domain, additional_domains=None):
        """Policy for web server SSL certificates."""
        policy = CertificatePolicy.get_default()
        policy.subject = f"CN={domain}"
        policy.san_dns_names = [domain] + (additional_domains or [])
        policy.key_type = KeyType.rsa
        policy.key_size = 2048
        policy.validity_in_months = 12
        policy.key_usage = [
            KeyUsageType.digital_signature,
            KeyUsageType.key_encipherment
        ]
        return policy
    
    @staticmethod
    def code_signing():
        """Policy for code signing certificates."""
        policy = CertificatePolicy.get_default()
        policy.key_type = KeyType.rsa
        policy.key_size = 4096
        policy.validity_in_months = 36
        policy.key_usage = [KeyUsageType.digital_signature]
        policy.enhanced_key_usage = ["1.3.6.1.5.5.7.3.3"]  # Code signing OID
        return policy
    
    @staticmethod
    def client_authentication(user_principal_name):
        """Policy for client authentication certificates."""
        policy = CertificatePolicy.get_default()
        policy.subject = f"CN={user_principal_name}"
        policy.san_upns = [user_principal_name]
        policy.key_type = KeyType.rsa
        policy.key_size = 2048
        policy.validity_in_months = 12
        policy.key_usage = [
            KeyUsageType.digital_signature,
            KeyUsageType.key_agreement
        ]
        return policy

# Usage
ssl_policy = CertificatePolicyTemplates.web_server_ssl(
    "myapp.com", 
    ["www.myapp.com", "api.myapp.com"]
)

code_sign_policy = CertificatePolicyTemplates.code_signing()

client_policy = CertificatePolicyTemplates.client_authentication(
    "user@company.com"
)

Policy Validation

def validate_policy(policy):
    """Validate certificate policy configuration."""
    issues = []
    
    # Check required fields
    if not policy.subject and not policy.san_dns_names:
        issues.append("Either subject or SAN DNS names must be specified")
    
    # Check key configuration
    if policy.key_type == KeyType.rsa and policy.key_size < 2048:
        issues.append("RSA key size should be at least 2048 bits")
    
    # Check validity period
    if policy.validity_in_months > 39:
        issues.append("Validity period over 39 months may not be supported by some CAs")
    
    # Check lifetime actions
    if policy.lifetime_actions:
        for action in policy.lifetime_actions:
            if (action.days_before_expiry and 
                action.days_before_expiry > policy.validity_in_months * 30):
                issues.append(f"Lifetime action triggers before certificate is issued")
    
    return issues

# Validate before applying
issues = validate_policy(custom_policy)
if issues:
    print("Policy validation issues:")
    for issue in issues:
        print(f"- {issue}")
else:
    print("Policy validation passed")

Install with Tessl CLI

npx tessl i tessl/pypi-azure-keyvault-certificates

docs

async-operations.md

certificate-operations.md

contact-management.md

import-export.md

index.md

issuer-management.md

listing-operations.md

operation-management.md

policy-management.md

recovery-operations.md

tile.json