tls_certificates

Manage TLS certificates using the tls-certificates interface (V1).

This is a port of tls_certificates_interface.tls_certificates v4.22.

Learn more about how to use the TLS Certificates interface library by reading the usage documentation on Charmhub.

class Certificate(
raw: str | None = None,
common_name: str | None = None,
expiry_time: datetime | None = None,
validity_start_time: datetime | None = None,
is_ca: bool | None = None,
sans_dns: set[str] | None = None,
sans_ip: set[str] | None = None,
sans_oid: set[str] | None = None,
email_address: str | None = None,
organization: str | None = None,
organizational_unit: str | None = None,
country_name: str | None = None,
state_or_province_name: str | None = None,
locality_name: str | None = None,
x509_object: Certificate | None = None,
)

Bases: object

This class represents a certificate.

property raw: str

Return the PEM-formatted string representation of the certificate.

property common_name: str

Return the common name of the certificate.

property expiry_time: datetime

Return the expiry time of the certificate.

property validity_start_time: datetime

Return the validity start time of the certificate.

property is_ca: bool

Return whether the certificate is a CA certificate.

property sans_dns: set[str] | None

Return the DNS Subject Alternative Names of the certificate.

property sans_ip: set[str] | None

Return the IP Subject Alternative Names of the certificate.

property sans_oid: set[str] | None

Return the OID Subject Alternative Names of the certificate.

property email_address: str | None

Return the email address of the certificate.

property organization: str | None

Return the organization name of the certificate.

property organizational_unit: str | None

Return the organizational unit name of the certificate.

property country_name: str | None

Return the country name of the certificate.

property state_or_province_name: str | None

Return the state or province name of the certificate.

property locality_name: str | None

Return the locality name of the certificate.

classmethod from_string(
certificate: str,
) Certificate

Create a Certificate object from a certificate.

matches_private_key(
private_key: PrivateKey,
) bool

Check if this certificate matches a given private key.

Parameters:

private_key (PrivateKey) – The private key to validate against.

Returns:

True if the certificate matches the private key, False otherwise.

Return type:

bool

classmethod generate(
csr: CertificateSigningRequest,
ca: Certificate,
ca_private_key: PrivateKey,
validity: timedelta,
is_ca: bool = False,
) Certificate

Generate a certificate from a CSR signed by the given CA and CA private key.

Parameters:
  • csr – The certificate signing request.

  • ca – The CA certificate.

  • ca_private_key – The CA private key.

  • validity – The validity period of the certificate.

  • is_ca – Whether the generated certificate is a CA certificate.

Returns:

The generated certificate.

Return type:

Certificate

classmethod generate_self_signed_ca(
attributes: CertificateRequestAttributes,
private_key: PrivateKey,
validity: timedelta,
) Certificate

Generate a self-signed CA certificate.

Parameters:
  • attributes – The certificate request attributes.

  • private_key – The private key to sign the CA certificate.

  • validity – The validity period of the CA certificate.

Returns:

The generated CA certificate.

Return type:

Certificate

class CertificateAvailableEvent(
handle: Handle,
certificate: Certificate,
certificate_signing_request: CertificateSigningRequest,
ca: Certificate,
chain: list[Certificate],
)

Bases: EventBase

Charm Event triggered when a TLS certificate is available.

snapshot() dict[str, str]

Return snapshot.

restore(snapshot: dict[str, str])

Restore snapshot.

chain_as_pem() str

Return full certificate chain as a PEM string.

class CertificateDeniedEvent(
handle: Handle,
certificate_signing_request: CertificateSigningRequest,
error: CertificateError,
)

Bases: EventBase

Charm Event triggered when a TLS certificate cannot be issued for a CSR.

snapshot() dict[str, str]

Return snapshot.

restore(snapshot: dict[str, str])

Restore snapshot.

class CertificateError(
*,
code: int,
name: str,
message: str,
reason: str | None = None,
provider: str | None = None,
endpoint: str | None = None,
)

Bases: BaseModel

Error object reported by the provider for a CSR.

code: int
name: str
message: str
reason: str | None
provider: str | None
endpoint: str | None
class CertificateRequestAttributes(
common_name: str | None = None,
sans_dns: Collection[str] | None = None,
sans_ip: Collection[str] | None = None,
sans_oid: Collection[str] | None = None,
email_address: str | None = None,
organization: str | None = None,
organizational_unit: str | None = None,
country_name: str | None = None,
state_or_province_name: str | None = None,
locality_name: str | None = None,
is_ca: bool = False,
add_unique_id_to_subject_name: bool = True,
additional_critical_extensions: Collection[x509.ExtensionType] | None = None,
)

Bases: object

A representation of the certificate request attributes.

property common_name: str

Return the common name.

property sans_dns: set[str] | None

Return the DNS Subject Alternative Names.

property sans_ip: set[str] | None

Return the IP Subject Alternative Names.

property sans_oid: set[str] | None

Return the OID Subject Alternative Names.

property email_address: str | None

Return the email address.

property organization: str | None

Return the organization name.

property organizational_unit: str | None

Return the organizational unit name.

property country_name: str | None

Return the country name.

property state_or_province_name: str | None

Return the state or province name.

property locality_name: str | None

Return the locality name.

property is_ca: bool

Return whether the certificate is a CA certificate.

property add_unique_id_to_subject_name: bool

Return whether to add a unique identifier to the subject name.

property additional_critical_extensions: list[ExtensionType]

Return additional critical extensions to be added to the CSR.

classmethod from_csr(
csr: CertificateSigningRequest,
is_ca: bool,
) CertificateRequestAttributes

Create CertificateRequestAttributes from a CertificateSigningRequest.

Parameters:
  • csr – The CSR to extract attributes from.

  • is_ca – Whether a CA certificate is being requested.

Returns:

The extracted attributes.

Return type:

CertificateRequestAttributes

is_valid() bool

Validate the attributes of the certificate request.

Returns:

True if the attributes are valid, False otherwise.

Return type:

bool

generate_csr(
private_key: PrivateKey,
) CertificateSigningRequest

Generate a CSR using the current attributes and a private key.

Parameters:

private_key (PrivateKey) – Private key to sign the CSR.

Returns:

The generated CSR.

Return type:

CertificateSigningRequest

class CertificateRequestErrorCode(*values)

Bases: int, Enum

Error codes for failed certificate requests.

1XX: CSR errors - Errors related to the certificate request itself 2XX: Server errors - Server-related errors 9XX: Other errors - Other errors not covered by the above categories

IP_NOT_ALLOWED = 101
DOMAIN_NOT_ALLOWED = 102
WILDCARD_NOT_ALLOWED = 103
SERVER_NOT_AVAILABLE = 201
OTHER = 999
class CertificateSigningRequest(
raw: str | None = None,
common_name: str | None = None,
sans_dns: set[str] | None = None,
sans_ip: set[str] | None = None,
sans_oid: set[str] | None = None,
email_address: str | None = None,
organization: str | None = None,
organizational_unit: str | None = None,
country_name: str | None = None,
state_or_province_name: str | None = None,
locality_name: str | None = None,
has_unique_identifier: bool | None = None,
x509_object: CertificateSigningRequest | None = None,
)

Bases: object

A representation of the certificate signing request.

property common_name: str

Return the common name of the CSR.

property sans_dns: set[str]

Return the DNS Subject Alternative Names of the CSR.

property sans_ip: set[str]

Return the IP Subject Alternative Names of the CSR.

property sans_oid: set[str]

Return the OID Subject Alternative Names of the CSR.

property email_address: str | None

Return the email address of the CSR.

property organization: str | None

Return the organization name of the CSR.

property organizational_unit: str | None

Return the organizational unit name of the CSR.

property country_name: str | None

Return the country name of the CSR.

property state_or_province_name: str | None

Return the state or province name of the CSR.

property locality_name: str | None

Return the locality name of the CSR.

property has_unique_identifier: bool

Return whether the CSR has a unique identifier.

property raw: str

Return the PEM-formatted string representation of the CSR.

property additional_critical_extensions: list[ExtensionType]

Return additional critical extensions present on the CSR (excluding SAN).

classmethod from_string(
csr: str,
) CertificateSigningRequest

Create a CertificateSigningRequest object from a CSR.

classmethod from_csr(
csr: CertificateSigningRequest,
) CertificateSigningRequest

Create a CertificateSigningRequest object from a CSR.

matches_certificate(
certificate: Certificate,
) bool

Check if this CSR matches a given certificate.

Parameters:

certificate (Certificate) – The certificate to validate against.

Returns:

True if the CSR matches the certificate, False otherwise.

Return type:

bool

matches_private_key(
key: PrivateKey,
) bool

Check if a CSR matches a private key.

This function only works with RSA keys.

Parameters:

key (PrivateKey) – Private key

Returns:

True/False depending on whether the CSR matches the private key.

Return type:

bool

get_sha256_hex() str

Calculate the hash of the provided data and return the hexadecimal representation.

sign(
ca: Certificate,
ca_private_key: PrivateKey,
validity: timedelta,
is_ca: bool = False,
) Certificate

Sign this CSR with the given CA and CA private key.

Parameters:
  • ca – The CA certificate.

  • ca_private_key – The CA private key.

  • validity – The validity period of the certificate.

  • is_ca – Whether the generated certificate is a CA certificate.

Returns:

The signed certificate.

Return type:

Certificate

classmethod generate(
attributes: CertificateRequestAttributes,
private_key: PrivateKey,
) CertificateSigningRequest

Generate a CSR using the supplied attributes and private key.

Parameters:
Returns:

CSR

Return type:

CertificateSigningRequest

class CertificatesRequirerCharmEvents(
parent: Object | None = None,
key: str | None = None,
)

Bases: CharmEvents

List of events that the TLS Certificates requirer charm can leverage.

certificate_available

EventSource wraps an event type with a descriptor to facilitate observing and emitting.

It is generally used as:

class SomethingHappened(ops.EventBase):
    pass

class SomeObject(Object):
    something_happened = ops.EventSource(SomethingHappened)

With that, instances of that type will offer the someobj.something_happened attribute which is a BoundEvent, and may be used to emit and observe the event.

certificate_denied

EventSource wraps an event type with a descriptor to facilitate observing and emitting.

It is generally used as:

class SomethingHappened(ops.EventBase):
    pass

class SomeObject(Object):
    something_happened = ops.EventSource(SomethingHappened)

With that, instances of that type will offer the someobj.something_happened attribute which is a BoundEvent, and may be used to emit and observe the event.

exception DataValidationError

Bases: TLSCertificatesError

Raised when data validation fails.

class Mode(*values)

Bases: Enum

Enum representing the mode of the certificate request.

UNIT (default): Request a certificate for the unit.

Each unit will manage its private key, certificate signing request and certificate.

APP: Request a certificate for the application.

Only the leader unit will manage the private key, certificate signing request and certificate.

APP_AND_UNIT: Request certificates for the application and the unit.

Each unit will have its own private key and certificate, but the application will have a shared private key and certificate.

UNIT = 1
APP = 2
APP_AND_UNIT = 3
class PrivateKey(
raw: str | None = None,
x509_object: RSAPrivateKey | None = None,
)

Bases: object

This class represents a private key.

property raw: str

Return the PEM-formatted string representation of the private key.

classmethod from_string(
private_key: str,
) PrivateKey

Create a PrivateKey object from a private key.

is_valid() bool

Validate that the private key is PEM-formatted, RSA, and at least 2048 bits.

classmethod generate(
key_size: int = 2048,
public_exponent: int = 65537,
) PrivateKey

Generate a new RSA private key.

Parameters:
  • key_size – The size of the key in bits.

  • public_exponent – The public exponent of the key.

Returns:

The generated private key.

Return type:

PrivateKey

class ProviderCertificate(
relation_id: int,
certificate: Certificate,
certificate_signing_request: CertificateSigningRequest,
ca: Certificate,
chain: list[Certificate],
revoked: bool | None = None,
)

Bases: object

This class represents a certificate provided by the TLS provider.

relation_id: int
certificate: Certificate
certificate_signing_request: CertificateSigningRequest
ca: Certificate
chain: list[Certificate]
revoked: bool | None = None
to_json() str

Return the object as a JSON string.

Returns:

JSON representation of the object

Return type:

str

class ProviderCertificateError(
relation_id: int,
certificate_signing_request: CertificateSigningRequest,
error: CertificateError,
)

Bases: object

This class represents a failed issuance for a CSR reported by the TLS provider.

relation_id: int
certificate_signing_request: CertificateSigningRequest
error: CertificateError
class RequirerCertificateRequest(
relation_id: int,
certificate_signing_request: CertificateSigningRequest,
is_ca: bool,
)

Bases: object

This class represents a certificate signing request requested by a specific TLS requirer.

relation_id: int
certificate_signing_request: CertificateSigningRequest
is_ca: bool
exception TLSCertificatesError

Bases: Exception

Base class for custom errors raised by this library.

class TLSCertificatesProvidesV4(charm: CharmBase, relationship_name: str)

Bases: Object

TLS certificates provider class to be instantiated by TLS certificates providers.

get_certificate_requests(
relation_id: int | None = None,
) list[RequirerCertificateRequest]

Load certificate requests from the relation data.

revoke_all_certificates() None

Revoke all certificates of this provider.

This method is meant to be used when the Root CA has changed.

set_relation_certificate(
provider_certificate: ProviderCertificate,
) None

Add certificates to relation data.

Parameters:

provider_certificate (ProviderCertificate) – ProviderCertificate object

Returns:

None

set_relation_error(
provider_error: ProviderCertificateError,
) None

Record an error for a CSR when issuance fails.

Parameters:

provider_error – The error information to set for the certificate request.

get_issued_certificates(
relation_id: int | None = None,
) list[ProviderCertificate]

Return a List of issued (non revoked) certificates.

Returns:

List of ProviderCertificate objects

Return type:

List

get_provider_certificates(
relation_id: int | None = None,
) list[ProviderCertificate]

Return a List of issued certificates.

get_provider_certificate_errors(
relation_id: int | None = None,
) list[ProviderCertificateError]

Return provider certificate errors for the given relations.

Parameters:

relation_id – Optional relation ID to filter errors by specific relation. If None, returns errors from all relations.

Returns:

List of ProviderCertificateError objects representing failed certificate requests.

get_unsolicited_certificates(
relation_id: int | None = None,
) list[ProviderCertificate]

Return provider certificates for which no certificate requests exists.

Those certificates should be revoked.

get_outstanding_certificate_requests(
relation_id: int | None = None,
) list[RequirerCertificateRequest]

Return CSR’s for which no certificate has been issued.

Parameters:

relation_id (int) – Relation id

Returns:

List of RequirerCertificateRequest objects.

Return type:

list

class TLSCertificatesRequiresV4(
charm: CharmBase,
relationship_name: str,
certificate_requests: list[CertificateRequestAttributes] | None = None,
mode: Mode = Mode.UNIT,
refresh_events: list[BoundEvent] | None = None,
private_key: PrivateKey | None = None,
renewal_relative_time: float = 0.9,
certificate_requests_by_mode: dict[Literal[Mode.APP, Mode.UNIT], list[CertificateRequestAttributes]] | None = None,
)

Bases: Object

A class to manage the TLS certificates interface for a unit or app.

on

List of events that the TLS Certificates requirer charm can leverage.

sync() None

Sync TLS Certificates Relation Data.

This method allows the requirer to sync the TLS certificates relation data without waiting for the refresh events to be triggered.

renew_certificate(
certificate: ProviderCertificate,
) None

Request the renewal of the provided certificate.

property private_key: PrivateKey | None

Return the private key.

In APP_AND_UNIT mode, this property returns the UNIT private key. Use get_private_key(mode) to access the APP key.

get_private_key(
mode: Mode | None = None,
) PrivateKey | None

Get the private key for a specific mode.

Parameters:

mode – The mode to get the private key for. In APP_AND_UNIT mode: defaults to Mode.UNIT if not specified. In UNIT/APP mode: this parameter is ignored (uses self.mode).

Returns:

The private key for the specified mode, or None if not available.

get_private_key_secret_id(
mode: Mode | None = None,
) str | None

Get the secret ID for the library-generated private key.

This method provides access to the Juju secret ID containing the private key.

Returns:

The secret ID as a string if a library-generated private key secret exists, None otherwise.

Returns None in the following cases:
  • The private key was provided via the private_key parameter (no secret exists)

  • No private key has not been generated yet

  • In APP mode, when called from a non-leader unit

  • In APP_AND_UNIT mode, when mode is not provided

Note

The secret ID is an opaque identifier and does not reveal the private key material. However, it should still be treated as sensitive metadata - avoid logging it or placing it in public locations.

The returned ID is stable as long as the private key is not regenerated. If regenerate_private_key() is called, a new secret may be created and this ID may change.

The secret content or metadata must never be directly modified, Any modifications may lead to unexpected behavior.

regenerate_private_key(
mode: Mode | None = None,
) None

Regenerate the private key.

Generate a new private key, remove old certificate requests and send new ones.

Parameters:

mode – Optional mode when using APP_AND_UNIT. If None, regenerates both.

Raises:

TLSCertificatesError – If the private key is passed by the charm using the private_key parameter.

import_private_key(
private_key: PrivateKey,
mode: Mode | None = None,
) None

Import an external.

Generate a new private key, remove old certificate requests and send new ones. Replace library-managed keys with the provided external private key. This will store the key in secrets, clean up old certificate requests, and generate new CSRs with the imported key.

Parameters:
  • private_key – The private key to import. Must be a valid RSA key.

  • mode – Optional mode when using APP_AND_UNIT. If None both will be rotated.

Raises:

TLSCertificatesError – If private_key was provided during initialization, or if the provided key is invalid.

Note

After importing a key, the library will manage it like a library generated key.

get_csrs_from_requirer_relation_data() list[RequirerCertificateRequest]

Return list of requirer’s CSRs from relation data.

App csrs can only be accessed by the leader unit.

get_provider_certificates() list[ProviderCertificate]

Return list of certificates from the provider’s relation data.

get_request_errors() list[ProviderCertificateError]

Get all request errors from the provider’s relation data.

Returns:

List of ProviderCertificateError objects representing failed certificate requests.

get_request_error(
csr: CertificateSigningRequest,
) ProviderCertificateError | None

Get the request error for a specific CSR.

Parameters:

csr – The certificate signing request to look up.

Returns:

ProviderCertificateError if an error exists for this CSR, None otherwise.

get_assigned_certificate(
certificate_request: CertificateRequestAttributes,
) tuple[ProviderCertificate | None, PrivateKey | None]

Get the certificate that was assigned to the given certificate request.

get_assigned_certificates(
mode: Mode | None = None,
) tuple[list[ProviderCertificate], PrivateKey | None]

Get certificates for a specific mode with the appropriate private key.

Parameters:

mode – Which mode’s certificates to return. In APP_AND_UNIT mode: defaults to Mode.UNIT if not specified. Only returns certificates for the specified mode. In UNIT or APP mode: ignored (returns all certificates for self.mode).

Returns:

  • certificates: List of assigned certificates for the specified mode

  • private_key: The private key for those certificates

Return type:

A tuple of (certificates, private_key) where

Example usage in APP_AND_UNIT mode:

# Get UNIT certificates with UNIT private key
unit_certs, unit_key = self.tls.get_assigned_certificates(Mode.UNIT)

# Get APP certificates with APP private key (leader only)
app_certs, app_key = self.tls.get_assigned_certificates(Mode.APP)
calculate_relative_datetime(
target_time: datetime,
fraction: float,
) datetime

Calculate a datetime that is a given percentage from now to a target time.

Parameters:
  • target_time (datetime) – The future datetime to interpolate towards.

  • fraction (float) – Fraction of the interval from now to target_time (0.0-1.0). 1.0 means return target_time, 0.9 means return the time after 90% of the interval has passed, and 0.0 means return now.

chain_has_valid_order(chain: list[str]) bool

Check if the chain has a valid order.

Validates that each certificate in the chain is properly signed by the next certificate. The chain should be ordered from leaf to root, where each certificate is signed by the next one in the chain.

Parameters:

chain (List[str]) – List of certificates in PEM format, ordered from leaf to root

Returns:

True if the chain has a valid order, False otherwise.

Return type:

bool

generate_ca(
private_key: PrivateKey,
validity: timedelta,
common_name: str,
sans_dns: frozenset[str] | None = frozenset({}),
sans_ip: frozenset[str] | None = frozenset({}),
sans_oid: frozenset[str] | None = frozenset({}),
organization: str | None = None,
organizational_unit: str | None = None,
email_address: str | None = None,
country_name: str | None = None,
state_or_province_name: str | None = None,
locality_name: str | None = None,
) Certificate

Generate a self signed CA Certificate.

Parameters:
  • private_key – Private key

  • validity – Certificate validity time

  • common_name – Common Name that can be an IP or a Full Qualified Domain Name (FQDN).

  • sans_dns – DNS Subject Alternative Names

  • sans_ip – IP Subject Alternative Names

  • sans_oid – OID Subject Alternative Names

  • organization – Organization name

  • organizational_unit – Organizational unit name

  • email_address – Email address

  • country_name – Certificate Issuing country

  • state_or_province_name – Certificate Issuing state or province

  • locality_name – Certificate Issuing locality

Returns:

CA Certificate.

generate_certificate(
csr: CertificateSigningRequest,
ca: Certificate,
ca_private_key: PrivateKey,
validity: timedelta,
is_ca: bool = False,
) Certificate

Generate a TLS certificate based on a CSR.

Parameters:
Returns:

Certificate

Return type:

Certificate

generate_csr(
private_key: PrivateKey,
common_name: str,
sans_dns: frozenset[str] | None = frozenset({}),
sans_ip: frozenset[str] | None = frozenset({}),
sans_oid: frozenset[str] | None = frozenset({}),
organization: str | None = None,
organizational_unit: str | None = None,
email_address: str | None = None,
country_name: str | None = None,
locality_name: str | None = None,
state_or_province_name: str | None = None,
add_unique_id_to_subject_name: bool = True,
) CertificateSigningRequest

Generate a CSR using private key and subject.

Parameters:
  • private_key (PrivateKey) – Private key

  • common_name (str) – Common name

  • sans_dns (FrozenSet[str]) – DNS Subject Alternative Names

  • sans_ip (FrozenSet[str]) – IP Subject Alternative Names

  • sans_oid (FrozenSet[str]) – OID Subject Alternative Names

  • organization (Optional[str]) – Organization name

  • organizational_unit (Optional[str]) – Organizational unit name

  • email_address (Optional[str]) – Email address

  • country_name (Optional[str]) – Country name

  • state_or_province_name (Optional[str]) – State or province name

  • locality_name (Optional[str]) – Locality name

  • add_unique_id_to_subject_name (bool) – Whether a unique ID must be added to the CSR’s subject name. Always leave to “True” when the CSR is used to request certificates using the tls-certificates relation.

Returns:

CSR

Return type:

CertificateSigningRequest

generate_private_key(
key_size: int = 2048,
public_exponent: int = 65537,
) PrivateKey

Generate a private key with the RSA algorithm.

Parameters:
  • key_size (int) – Key size in bits, must be at least 2048 bits

  • public_exponent – Public exponent.

Returns:

Private Key

Return type:

PrivateKey