tiny_ca.managers package¶
- class tiny_ca.managers.CertLifecycleManager(storage=<tiny_ca.storage.local_storage.LocalStorage object>, factory=None, db_handler=None, logger=None)[source]¶
Bases:
objectOrchestrates the full lifecycle of X.509 certificates.
CertLifecycleManageris the facade that application code interacts with. It coordinates four collaborators through dependency injection:CertificateFactory— cryptographic generation of certificates and CRLs.BaseStorage— persistent storage of PEM/key/CSR/CRL files.BaseDB— registration, lookup, revocation, and rotationrecords in a relational database.
Logger— structured operational logging.
All three external collaborators are optional at construction time, but specific operations will raise
ValueErrororDBNotInitedErrorif a required collaborator is absent when that operation is invoked.- Parameters:
storage (BaseStorage) – File storage backend. Defaults to
LocalStorage()which writes to./certsrelative to the working directory.factory (CertificateFactory | None) – Cryptographic factory. Must be set before calling
issue_certificate,generate_crl, orverify_certificate. Can be set after construction via thefactoryproperty setter.db_handler (BaseDB | None) – Database adapter. When
None, all operations that require persistence (status lookup, revocation, rotation) will raiseDBNotInitedError.logger (Logger | None) – Logger for operational messages. Falls back to
DEFAULT_LOGGER.
- Raises:
- __init__(storage=<tiny_ca.storage.local_storage.LocalStorage object>, factory=None, db_handler=None, logger=None)[source]¶
- Parameters:
storage (BaseStorage)
factory (CertificateFactory | None)
db_handler (BaseDB | None)
logger (Logger | None)
- Return type:
None
- create_self_signed_ca(config, cert_path=None, uuid_str=None, is_overwrite=False)[source]¶
Generate a self-signed root CA certificate and persist both artefacts.
Delegates cryptographic generation to
CertificateFactory.build_self_signed_caand then saves the certificate and private key through the configuredBaseStorage. When adb_handleris present the certificate is also registered in the database.- Parameters:
config (CAConfig) – Pydantic model carrying
common_name,organization,country,key_size, anddays_valid.cert_path (str | None) – Sub-directory under the storage base folder.
Noneplaces the files directly in the base folder.uuid_str (str | None) – Explicit UUID for the storage sub-directory.
Nonecauses the storage layer to generate one automatically.is_overwrite (bool) – When
True, any existing certificate with the same CN is revoked and its files are deleted before the new one is saved. WhenFalse(default),NotUniqueCertOwneris raised if a conflict exists.
- Returns:
(path_to_cert_pem, path_to_key_pem)as returned by the storage layer.- Return type:
- delete_certificate(serial, cert_path=None)[source]¶
Hard-delete a certificate from the DB and its artefact folder from storage.
Returns True if the DB row was deleted (storage deletion is best-effort).
- export_pkcs12(cert, private_key, password=None, name=None)[source]¶
Pack cert + key into a PKCS#12 bundle. Delegates to CertificateFactory.export_pkcs12.
- Return type:
- Parameters:
cert (Certificate)
private_key (RSAPrivateKey)
password (bytes | None)
name (str | None)
- property factory: CertificateFactory | None¶
The active
CertificateFactoryused for certificate issuance.- Returns:
The current factory, or
Noneif not yet initialised.- Return type:
CertificateFactory | None
- generate_crl(cert_path=None, days_valid=1)[source]¶
Build, sign, and persist a fresh Certificate Revocation List.
Retrieves all currently-revoked certificates from the database, passes them to
CertificateFactory.build_crl, and writes the resulting CRL to storage ascrl.pem(overwriting any previous version — CRLs are always regenerated in-place).- Parameters:
- Returns:
The signed CRL object (also persisted to storage).
- Return type:
x509.CertificateRevocationList
- Raises:
DBNotInitedError – If no
db_handlerwas provided.ValueError – If
self.factoryhas not been initialised.
- get_cert_chain(cert)[source]¶
Return [cert, ca_cert] chain. Delegates to CertificateFactory.get_cert_chain.
- Return type:
list[Certificate]- Parameters:
cert (Certificate)
- get_certificate_status(serial)[source]¶
Determine the current status of the certificate identified by serial.
Looks up the certificate record in the database and evaluates its state in the following priority order: 1. Not found →
UNKNOWN2. Revocation date is set →REVOKED3.not_valid_afteris in the past →EXPIRED4. Otherwise →VALID- Parameters:
serial (int) – Integer serial number of the certificate to check.
- Returns:
One of
VALID,REVOKED,EXPIRED, orUNKNOWN.- Return type:
- Raises:
DBNotInitedError – If no
db_handlerwas provided.
- get_expiring_soon(within_days=30)[source]¶
Return VALID certs expiring within within_days days. Requires db_handler.
- Return type:
- Parameters:
within_days (int)
- issue_certificate(config, cert_path=None, uuid_str=None, is_overwrite=False)[source]¶
Issue a new end-entity certificate and persist all three artefacts.
The method generates the certificate, private key, and CSR via the configured
CertificateFactory, then saves each file throughBaseStorage. If adb_handleris configured the certificate metadata is also written to the database.Artefacts written to storage¶
<file_name>.pem— the signed certificate.<file_name>.key— the private key (unencrypted by default).<file_name>.csr— the certificate signing request (for audit).
- type config:
- param config:
Pydantic model containing all certificate parameters:
common_name,serial_type,key_size,days_valid,email,is_server_cert,is_client_cert,san_dns,san_ip, and an optionalnamefor the output file basename.- type config:
ClientConfig
- type cert_path:
- param cert_path:
Sub-directory under the storage base folder.
- type cert_path:
str | None
- type uuid_str:
- param uuid_str:
Explicit UUID;
Noneauto-generates one.- type uuid_str:
str | None
- type is_overwrite:
- param is_overwrite:
Allow replacing an existing certificate with the same CN.
- type is_overwrite:
bool
- returns:
(certificate, private_key, csr)in-memory objects.- rtype:
tuple[x509.Certificate, rsa.RSAPrivateKey, x509.CertificateSigningRequest]
- raises ValueError:
If
self.factoryhas not been initialised.- raises NotUniqueCertOwner:
If is_overwrite is
Falseand a certificate with the same CN already exists in the database.
- issue_intermediate_ca(common_name, key_size=4096, days_valid=1825, valid_from=None, path_length=0, organization=None, country=None, cert_path=None, uuid_str=None)[source]¶
Issue a subordinate CA cert signed by this CA and save artefacts.
Returns (cert, private_key). The cert is NOT registered in the DB automatically — call
register_cert_in_dbif persistence is needed.
- list_certificates(status=None, key_type=None, limit=100, offset=0)[source]¶
Return paginated certificate records. Requires db_handler.
- refresh_expired_statuses()[source]¶
Bulk-mark expired certificates. Returns count of updated rows.
- Return type:
- renew_certificate(serial, days_valid=365, valid_from=None)[source]¶
Renew the certificate identified by serial: same key, new validity window.
Fetches the certificate PEM from the database, deserialises it, and delegates to
CertificateFactory.renew_certificate.- Raises:
DBNotInitedError – If no
db_handlerwas provided.CertNotFound – If no record exists for serial.
ValueError – If
self.factoryhas not been initialised.
- Return type:
Certificate- Parameters:
- revoke_certificate(serial, reason)[source]¶
Revoke the certificate identified by serial.
Delegates to
BaseDB.revoke_certificate. The record is updated in-place (status → REVOKED, revocation date and reason stored); no file is deleted. Callgenerate_crlafterwards to publish the updated revocation list.- Parameters:
serial (int) – Integer serial number of the certificate to revoke.
reason (x509.ReasonFlags) – RFC 5280 revocation reason code (e.g.
x509.ReasonFlags.key_compromise).
- Returns:
Trueif the revocation was recorded successfully;Falseif the operation failed (see logs for details).- Return type:
- Raises:
DBNotInitedError – If no
db_handlerwas provided at construction time.
- rotate_certificate(serial, config)[source]¶
Revoke an existing certificate and issue a replacement in a single operation.
The old certificate is revoked with reason
supersededbefore the new one is issued. Both operations are performed against the configureddb_handler; if the revocation fails an exception is propagated and the new certificate is not issued.- Parameters:
serial (int) – Serial number of the certificate to replace.
config (ClientConfig) – Parameters for the replacement certificate. The CN may differ from the original.
- Returns:
(new_certificate, new_private_key, new_csr).- Return type:
tuple[x509.Certificate, rsa.RSAPrivateKey, x509.CertificateSigningRequest]
- Raises:
DBNotInitedError – If no
db_handlerwas provided.CertNotFound – If no certificate with serial exists in the database.
ValueError – If
self.factoryhas not been initialised.
- verify_certificate(cert)[source]¶
Perform a full verification of cert: chain, signature, and revocation.
Combines cryptographic validation (via
CertificateFactory.validate_cert) with a database revocation check (viaget_certificate_status).Validation steps¶
Issuer field matches the CA subject.
Current UTC time is within the validity window.
Cryptographic signature is valid.
Certificate is not listed as revoked in the database.
- type cert:
Certificate- param cert:
The certificate object to verify.
- type cert:
x509.Certificate
- returns:
Truewhen all checks pass.- rtype:
bool
- raises ValueError:
If
self.factoryhas not been initialised.- raises ValidationCertError:
If the certificate fails any cryptographic check or is revoked.
- Parameters:
cert (Certificate)
- Return type:
Submodules¶
- tiny_ca.managers.async_lifecycle_manager module
AsyncCertLifecycleManagerAsyncCertLifecycleManager.__init__()AsyncCertLifecycleManager.cosign_certificate()AsyncCertLifecycleManager.create_self_signed_ca()AsyncCertLifecycleManager.delete_certificate()AsyncCertLifecycleManager.export_pkcs12()AsyncCertLifecycleManager.factoryAsyncCertLifecycleManager.generate_crl()AsyncCertLifecycleManager.get_cert_chain()AsyncCertLifecycleManager.get_certificate_status()AsyncCertLifecycleManager.get_expiring_soon()AsyncCertLifecycleManager.inspect_certificate()AsyncCertLifecycleManager.issue_certificate()AsyncCertLifecycleManager.issue_intermediate_ca()AsyncCertLifecycleManager.list_certificates()AsyncCertLifecycleManager.refresh_expired_statuses()AsyncCertLifecycleManager.renew_certificate()AsyncCertLifecycleManager.revoke_certificate()AsyncCertLifecycleManager.rotate_certificate()AsyncCertLifecycleManager.verify_certificate()AsyncCertLifecycleManager.verify_crl()
- tiny_ca.managers.sync_lifecycle_manager module
- SOLID notes
CertLifecycleManagerCertLifecycleManager.__init__()CertLifecycleManager.cosign_certificate()CertLifecycleManager.create_self_signed_ca()CertLifecycleManager.delete_certificate()CertLifecycleManager.export_pkcs12()CertLifecycleManager.factoryCertLifecycleManager.generate_crl()CertLifecycleManager.get_cert_chain()CertLifecycleManager.get_certificate_status()CertLifecycleManager.get_expiring_soon()CertLifecycleManager.inspect_certificate()CertLifecycleManager.issue_certificate()CertLifecycleManager.issue_intermediate_ca()CertLifecycleManager.list_certificates()CertLifecycleManager.refresh_expired_statuses()CertLifecycleManager.renew_certificate()CertLifecycleManager.revoke_certificate()CertLifecycleManager.rotate_certificate()CertLifecycleManager.verify_certificate()CertLifecycleManager.verify_crl()