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:
objectThis class represents a certificate.
- classmethod from_string(
- certificate: str,
Create a Certificate object from a certificate.
- matches_private_key(
- private_key: PrivateKey,
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:
- classmethod generate(
- csr: CertificateSigningRequest,
- ca: Certificate,
- ca_private_key: PrivateKey,
- validity: timedelta,
- is_ca: bool = False,
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:
- classmethod generate_self_signed_ca(
- attributes: CertificateRequestAttributes,
- private_key: PrivateKey,
- validity: timedelta,
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:
- class CertificateAvailableEvent(
- handle: Handle,
- certificate: Certificate,
- certificate_signing_request: CertificateSigningRequest,
- ca: Certificate,
- chain: list[Certificate],
Bases:
EventBaseCharm Event triggered when a TLS certificate is available.
- class CertificateDeniedEvent(
- handle: Handle,
- certificate_signing_request: CertificateSigningRequest,
- error: CertificateError,
Bases:
EventBaseCharm Event triggered when a TLS certificate cannot be issued for a CSR.
- class CertificateError(
- *,
- code: int,
- name: str,
- message: str,
- reason: str | None = None,
- provider: str | None = None,
- endpoint: str | None = None,
Bases:
BaseModelError object reported by the provider for a CSR.
- 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:
objectA representation of the certificate request attributes.
- 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,
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:
- is_valid() bool¶
Validate the attributes of the certificate request.
- Returns:
True if the attributes are valid, False otherwise.
- Return type:
- generate_csr(
- private_key: PrivateKey,
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:
- class CertificateRequestErrorCode(*values)¶
-
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:
objectA representation of the certificate signing request.
- property additional_critical_extensions: list[ExtensionType]¶
Return additional critical extensions present on the CSR (excluding SAN).
- classmethod from_string(
- csr: str,
Create a CertificateSigningRequest object from a CSR.
- classmethod from_csr(
- csr: CertificateSigningRequest,
Create a CertificateSigningRequest object from a CSR.
- matches_certificate(
- certificate: Certificate,
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:
- matches_private_key(
- key: PrivateKey,
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:
- 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,
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:
- classmethod generate(
- attributes: CertificateRequestAttributes,
- private_key: PrivateKey,
Generate a CSR using the supplied attributes and private key.
- Parameters:
attributes (CertificateRequestAttributes) – Certificate request attributes
private_key (PrivateKey) – Private key
- Returns:
CSR
- Return type:
- class CertificatesRequirerCharmEvents( )¶
Bases:
CharmEventsList 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_happenedattribute which is aBoundEvent, 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_happenedattribute which is aBoundEvent, and may be used to emit and observe the event.
- exception DataValidationError¶
Bases:
TLSCertificatesErrorRaised when data validation fails.
- class Mode(*values)¶
Bases:
EnumEnum 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( )¶
Bases:
objectThis class represents a private key.
- classmethod from_string(
- private_key: str,
Create a PrivateKey object from a private key.
- classmethod generate( ) 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:
- class ProviderCertificate(
- relation_id: int,
- certificate: Certificate,
- certificate_signing_request: CertificateSigningRequest,
- ca: Certificate,
- chain: list[Certificate],
- revoked: bool | None = None,
Bases:
objectThis class represents a certificate provided by the TLS provider.
- certificate: Certificate¶
- certificate_signing_request: CertificateSigningRequest¶
- ca: Certificate¶
- chain: list[Certificate]¶
- class ProviderCertificateError(
- relation_id: int,
- certificate_signing_request: CertificateSigningRequest,
- error: CertificateError,
Bases:
objectThis class represents a failed issuance for a CSR reported by the TLS provider.
- certificate_signing_request: CertificateSigningRequest¶
- error: CertificateError¶
- class RequirerCertificateRequest(
- relation_id: int,
- certificate_signing_request: CertificateSigningRequest,
- is_ca: bool,
Bases:
objectThis class represents a certificate signing request requested by a specific TLS requirer.
- certificate_signing_request: CertificateSigningRequest¶
- exception TLSCertificatesError¶
Bases:
ExceptionBase class for custom errors raised by this library.
- class TLSCertificatesProvidesV4(charm: CharmBase, relationship_name: str)¶
Bases:
ObjectTLS certificates provider class to be instantiated by TLS certificates providers.
- get_certificate_requests( ) 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,
Add certificates to relation data.
- Parameters:
provider_certificate (ProviderCertificate) – ProviderCertificate object
- Returns:
None
- set_relation_error(
- provider_error: ProviderCertificateError,
Record an error for a CSR when issuance fails.
- Parameters:
provider_error – The error information to set for the certificate request.
- get_issued_certificates( ) list[ProviderCertificate]¶
Return a List of issued (non revoked) certificates.
- Returns:
List of ProviderCertificate objects
- Return type:
List
- get_provider_certificates( ) list[ProviderCertificate]¶
Return a List of issued certificates.
- get_provider_certificate_errors( ) 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( ) list[ProviderCertificate]¶
Return provider certificates for which no certificate requests exists.
Those certificates should be revoked.
- 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:
ObjectA 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,
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( ) 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( ) 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( ) 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,
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( ) 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,
Get the certificate that was assigned to the given certificate request.
- get_assigned_certificates( ) 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_UNITmode: defaults toMode.UNITif not specified. Only returns certificates for the specified mode. InUNITorAPPmode: ignored (returns all certificates forself.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_UNITmode:# 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( ) 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.
- 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,
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,
Generate a TLS certificate based on a CSR.
- Parameters:
csr (CertificateSigningRequest) – CSR
ca (Certificate) – CA Certificate
ca_private_key (PrivateKey) – CA private key
validity (timedelta) – Certificate validity time
is_ca (bool) – Whether the certificate is a CA certificate
- Returns:
Certificate
- Return type:
- 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,
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:
- generate_private_key( ) 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: