CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-certbot-nginx

Nginx plugin for Certbot that enables automated SSL/TLS certificate management and deployment for Nginx web servers.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

objects.mddocs/

Virtual Host Objects

Object models for representing nginx virtual hosts and network addresses. These classes provide structured access to nginx configuration elements with comprehensive attribute management and manipulation methods.

Capabilities

Virtual Host Representation

The VirtualHost class represents an nginx server block with all its configuration details.

class VirtualHost:
    """Represents an nginx virtual host (server block).
    
    Args:
        filep: File path of virtual host
        addrs: Virtual host addresses
        ssl: SSLEngine enabled status
        enabled: Virtual host enabled status  
        names: Server names/aliases
        raw: Raw parsed server block
        path: Indices into parsed file for server block access
        
    Attributes:
        filep: str - File path of VH
        addrs: Sequence[Addr] - Virtual host addresses
        names: set[str] - Server names/aliases of vhost
        ssl: bool - SSL enabled in vhost
        enabled: bool - Virtual host is enabled
        raw: list[Any] - Raw form of parsed server block
        path: list[int] - Indices for accessing server block
    """
    
    def __init__(self, filep: str, addrs: Sequence[Addr], ssl: bool, 
                 enabled: bool, names: set[str], raw: list[Any], 
                 path: list[int]) -> None:
        """Initialize a virtual host."""

Virtual Host Network Configuration

Methods for checking IPv4/IPv6 support and network configuration.

def ipv4_enabled(self) -> bool:
    """Check if IPv4 is enabled for this virtual host.
    
    Returns:
        True if any address supports IPv4
    """

def ipv6_enabled(self) -> bool:
    """Check if IPv6 is enabled for this virtual host.
    
    Returns:
        True if any address supports IPv6
    """

Virtual Host Content Analysis

Analyze virtual host configuration content and structure.

def contains_list(self, test_list: list[Any]) -> bool:
    """Check if server block contains specified directive list.
    
    Args:
        test_list: List structure to search for
        
    Returns:
        True if directive list is found in server block
    """

def has_header(self, header_substring: str) -> bool:
    """Check if server has specific header directive.
    
    Args:
        header_substring: Header name to search for
        
    Returns:
        True if header directive is present
    """

Virtual Host Display

Methods for displaying virtual host information.

def display_repr(self) -> str:
    """Get display representation of virtual host.
    
    Returns:
        Human-readable string representation
    """

def __str__(self) -> str:
    """String representation of virtual host.
    
    Returns:
        Formatted string with file, addresses, names, SSL status
    """

Address Representation

The Addr class represents nginx listen directive addresses with full attribute support.

class Addr:
    """Represents nginx listen directive address.
    
    Args:
        host: Address part (hostname, IPv4, IPv6, "", or "*") 
        port: Port number or "*" or ""
        ssl: Whether directive includes 'ssl'
        default: Whether directive includes 'default_server'
        ipv6: Whether this is IPv6 address
        ipv6only: Whether directive includes 'ipv6only=on'
        
    Attributes:
        ssl: bool - SSL enabled on address
        default: bool - Default server designation
        ipv6: bool - IPv6 address flag
        ipv6only: bool - IPv6-only flag
        unspecified_address: bool - Address is unspecified
    """
    
    UNSPECIFIED_IPV4_ADDRESSES: tuple[str, ...] = ('', '*', '0.0.0.0')
    CANONICAL_UNSPECIFIED_ADDRESS: str = ''
    
    def __init__(self, host: str, port: str, ssl: bool, default: bool,
                 ipv6: bool, ipv6only: bool) -> None:
        """Initialize address with parameters."""

Address Construction and Parsing

Create Addr objects from string representations and convert back to strings.

@classmethod
def fromstring(cls, str_addr: str) -> "Addr":
    """Initialize Addr from string representation.
    
    Args:
        str_addr: Nginx address string (e.g., "80", "127.0.0.1:443 ssl")
        
    Returns:
        Parsed nginx address object
        
    Raises:
        SocketAddrError: If UNIX-domain socket address is given
    """

def to_string(self, include_default: bool = True) -> str:
    """Convert address to string representation.
    
    Args:
        include_default: Include default_server in output
        
    Returns:
        String representation of address
    """

def __str__(self) -> str:
    """String representation of address."""

Address Information Access

Access individual components of the address.

def get_addr(self) -> str:
    """Get address part of listen directive.
    
    Returns:
        Address component (host/IP)
    """

def get_port(self) -> str:
    """Get port part of listen directive.
    
    Returns:
        Port component
    """

def get_ipv6_exploded(self) -> str:
    """Get exploded IPv6 address representation.
    
    Returns:
        Exploded IPv6 address string
    """

def normalized_tuple(self) -> tuple[str, str]:
    """Get normalized (address, port) tuple.
    
    Returns:
        Normalized address and port tuple
    """

Address Comparison

Compare addresses with IPv6 support and unspecified address handling.

def super_eq(self, other: "Addr") -> bool:
    """Check IP/port equality with IPv6 support.
    
    Args:
        other: Address to compare with
        
    Returns:
        True if addresses are equivalent
    """

def __eq__(self, other: Any) -> bool:
    """Full equality comparison including SSL and default status.
    
    Args:
        other: Object to compare with
        
    Returns:
        True if addresses are fully equal
    """

Exception Classes

class SocketAddrError(Exception):
    """Raised when UNIX-domain socket address is encountered.
    
    UNIX-domain sockets are not supported by the nginx plugin.
    """

Usage Examples

Working with Virtual Hosts

from certbot_nginx._internal.parser import NginxParser

# Get virtual hosts from parser
parser = NginxParser('/etc/nginx')
vhosts = parser.get_vhosts()

# Examine virtual host properties
for vhost in vhosts:
    print(f"File: {vhost.filep}")
    print(f"Server names: {vhost.names}")
    print(f"SSL enabled: {vhost.ssl}")
    print(f"IPv4 enabled: {vhost.ipv4_enabled()}")
    print(f"IPv6 enabled: {vhost.ipv6_enabled()}")
    
    # Check for specific headers
    has_hsts = vhost.has_header('Strict-Transport-Security')
    print(f"Has HSTS header: {has_hsts}")
    
    # Display representation
    print(f"Display: {vhost.display_repr()}")

Working with Addresses

from certbot_nginx._internal.obj import Addr

# Parse address from string
addr1 = Addr.fromstring('80')
addr2 = Addr.fromstring('443 ssl default_server')
addr3 = Addr.fromstring('[::]:443 ssl ipv6only=on')

# Examine address properties
print(f"Address 1: {addr1.get_addr()}:{addr1.get_port()}, SSL: {addr1.ssl}")
print(f"Address 2: {addr2.get_addr()}:{addr2.get_port()}, SSL: {addr2.ssl}, Default: {addr2.default}")
print(f"Address 3: IPv6: {addr3.ipv6}, IPv6-only: {addr3.ipv6only}")

# Convert back to string
print(f"String representation: {addr2.to_string()}")

# Compare addresses
print(f"Addresses equal: {addr1 == addr2}")
print(f"IP/port equal: {addr1.super_eq(addr2)}")

Address Construction Examples

# Different address string formats
addresses = [
    '80',                           # Port only
    '127.0.0.1:8080',              # Host and port
    '443 ssl',                     # Port with SSL
    '192.168.1.1:443 ssl default_server',  # Full specification
    '[::]:80',                     # IPv6 address
    '[2001:db8::1]:443 ssl ipv6only=on'   # IPv6 with options
]

for addr_str in addresses:
    try:
        addr = Addr.fromstring(addr_str)
        print(f"'{addr_str}' -> {addr}")
        print(f"  Host: '{addr.get_addr()}', Port: '{addr.get_port()}'")
        print(f"  SSL: {addr.ssl}, Default: {addr.default}, IPv6: {addr.ipv6}")
    except Exception as e:
        print(f"Error parsing '{addr_str}': {e}")

Virtual Host Analysis

# Find virtual hosts with specific characteristics
ssl_vhosts = [vhost for vhost in vhosts if vhost.ssl]
ipv6_vhosts = [vhost for vhost in vhosts if vhost.ipv6_enabled()]
default_vhosts = [vhost for vhost in vhosts 
                  if any(addr.default for addr in vhost.addrs)]

print(f"SSL virtual hosts: {len(ssl_vhosts)}")
print(f"IPv6 virtual hosts: {len(ipv6_vhosts)}")  
print(f"Default virtual hosts: {len(default_vhosts)}")

# Check for security headers
security_headers = ['Strict-Transport-Security', 'X-Frame-Options', 'X-Content-Type-Options']
for vhost in vhosts:
    headers_present = [header for header in security_headers 
                      if vhost.has_header(header)]
    if headers_present:
        print(f"VHost {vhost.filep} has headers: {headers_present}")

Install with Tessl CLI

npx tessl i tessl/pypi-certbot-nginx

docs

configurator.md

constants.md

display-ops.md

http-01.md

index.md

nginxparser.md

objects.md

parser.md

tile.json