django_ca.models - django-ca models

django-ca uses three classes, called “models” in Django terminology, to store everything in the database. They are the core classes for this project, if you want to use this project programmatically, you’ll have to use these classes:

  • CertificateAuthority is used to store certificate authorities.

  • Certificate is used to store certificates.

  • Finally, Watcher stores email addresses for who should be notified if certificates expire.

Note that both CertificateAuthority and Certificate inherit from X509CertMixin, which provides many common convenience methods.

CertificateAuthority

class django_ca.models.CertificateAuthority(*args, **kwargs)[source]

Model representing a x509 Certificate Authority.

property allows_intermediate_ca: bool

Whether this CA allows creating intermediate CAs.

property bundle: List[CertificateAuthority]

A list of any parent CAs, including this CA.

The list is ordered so the Root CA will be the first.

cache_crls(key_backend_options: BaseModel) None[source]

Function to cache all CRLs for this CA.

Changed in version 1.25.0: Support for passing a custom hash algorithm to this function was removed.

check_usable(options: BaseModel) None[source]

Shortcut determining if the key is usable and raise ValueError otherwise.

property extensions_for_certificate: Dict[ObjectIdentifier, Extension[ExtensionType]]

Get a list of extensions to use for the certificate.

generate_ocsp_key(key_backend_options: BaseModel, profile: str = 'ocsp', expires: int | datetime | timedelta | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, key_size: int | None = None, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] | None = None, elliptic_curve: EllipticCurve | None = None, autogenerated: bool = True, force: bool = False) Tuple[str, str, Certificate] | None[source]

Generate OCSP authorized responder certificate.

By default, the certificate will have the same private and public key types as the signing certificate authority. The certificate’s subject will be the common name of the certificate authority with the suffix OCSP responder delegate certificate added, all other subject fields are discarded.

RFC 6960 does not specify much about how a certificate for an authorized responder should look like. The default ocsp profile will create a valid certificate that is usable for all known applications, but you a different profile can be used to add any extension values to the certificate.

Changed in version 1.26.0:

Changed in version 1.23.0:

  • The ecc_curve option was renamed to elliptic_curve.

  • The key_type, key_size, elliptic_curve and algorithm parameters now default to what was used in the certificate authority.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

profilestr, optional

The profile to use for generating the certificate. The default is "ocsp".

expiresint or datetime, optional

Number of days or datetime when this certificate expires. The default is 3 (OCSP certificates are usually renewed frequently).

algorithmHashAlgorithm, optional

Hash algorithm used for signing the OCSP key. Defaults to the algorithm the certificate authority was signed with.

passwordbytes, optional

The password to the CA as bytes, if its private key is encrypted.

key_sizeint, optional

The key size of the private key, defaults to CA_DEFAULT_KEY_SIZE.

key_type{“RSA”, “DSA”, “EC”, “Ed25519”, “Ed448”}, optional

The private key type to use. The default is to use the same key type as the signing CA.

elliptic_curveEllipticCurve, optional

An elliptic curve to use for EC keys. This parameter is ignored if key_type is not "EC". Defaults to the CA_DEFAULT_ELLIPTIC_CURVE.

autogeneratedbool, optional

Set the autogenerated flag of the certificate. True by default, since this method is usually automatically invoked on a regular basis.

forcebool, optional

Set to True to force regeneration of keys. By default, keys are only regenerated if they expire within CA_OCSP_RESPONDER_CERTIFICATE_RENEWAL.

get_authority_key_identifier() AuthorityKeyIdentifier[source]

Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.

get_authority_key_identifier_extension() Extension[AuthorityKeyIdentifier][source]

Get the AuthorityKeyIdentifier extension to use in certificates signed by this CA.

get_crl(key_backend_options: BaseModel, expires: int = 86400, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, scope: Literal['ca', 'user', 'attribute'] | None = None, counter: str | None = None, full_name: Iterable[GeneralName] | None = None, relative_name: RelativeDistinguishedName | None = None, include_issuing_distribution_point: bool | None = None) CertificateRevocationList[source]

Generate a Certificate Revocation List (CRL).

The full_name and relative_name parameters describe how to retrieve the CRL and are used in the Issuing Distribution Point extension. The former defaults to the crl_url field, pass None to not include the value. At most one of the two may be set.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

expiresint

The time in seconds when this CRL expires. Note that you should generate a new CRL until then.

algorithmHashAlgorithm, optional

The hash algorithm used to generate the signature of the CRL. By default, the algorithm used for signing the CA is used. If a value is passed for an Ed25519/Ed448 CA, ValueError is raised.

scope{None, ‘ca’, ‘user’, ‘attribute’}, optional

What to include in the CRL: Use "ca" to include only revoked certificate authorities and "user" to include only certificates or None (the default) to include both. "attribute" is reserved for future use and always produces an empty CRL.

counterstr, optional

Override the counter-variable for the CRL Number extension. Passing the same key to multiple invocations will yield a different sequence then what would ordinarily be returned. The default is to use the scope as the key.

full_namelist of GeneralName, optional

List of general names to use in the Issuing Distribution Point extension. If not passed, use the full names of the first distribution point in sign_crl_distribution_points (if present) that has full names set.

relative_nameRelativeDistinguishedName, optional

Used in Issuing Distribution Point extension, retrieve the CRL relative to the issuer.

include_issuing_distribution_point: bool, optional

Force the inclusion/exclusion of the IssuingDistributionPoint extension. By default, the inclusion is automatically determined.

Returns:
bytes

The CRL in the requested format.

get_crl_certs(scope: Literal[None, 'ca', 'user', 'attribute'], now: datetime) Iterable[X509CertMixin][source]

Get CRLs for the given scope.

property is_openssh_ca: bool

True if this CA is an OpenSSH CA.

is_usable(options: BaseModel | None = None) bool[source]

Shortcut determining if the certificate authority can be used for signing.

property key_backend: KeyBackend[BaseModel, BaseModel, BaseModel]

The key backend that can be used to use the private key.

property key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448']

The type of key as a string, e.g. “RSA” or “Ed448”.

property max_path_length: int | None

The maximum path length for any intermediate CAs signed by this CA.

This value is either None, if this and all parent CAs don’t have a path_length attribute, or an int if any parent CA has the attribute.

property ocsp_responder_certificate: Certificate

The certificate currently used in the automatically configured OCSP responder.

This property raises FileNotFoundError if no key has (yet) been generated.

property path_length: int | None

The path_length attribute of the BasicConstraints extension.

property root: CertificateAuthority

Get the root CA for this CA.

sign(key_backend_options: BaseModel, csr: CertificateSigningRequest, subject: Name, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, expires: datetime | None = None, extensions: Iterable[Extension[ExtensionType]] | None = None, password: str | bytes | None = None) Certificate[source]

Create a signed certificate.

This function is a low-level signing function, with optional values taken from the configuration.

Required extensions are added if not provided. Unless already included in extensions, this function will add the AuthorityKeyIdentifier, BasicConstraints and SubjectKeyIdentifier extensions with values coming from the certificate authority.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

csrCertificateSigningRequest

The certificate signing request to sign.

subjectName

Subject for the certificate

algorithmHashAlgorithm, optional

Hash algorithm used for signing the certificate, defaults to the algorithm used in the CA.

expiresdatetime, optional

When the certificate expires. If not provided, the CA_DEFAULT_EXPIRES setting will be used.

extensionslist of Extension, optional

List of extensions to add to the certificates. The function will add some extensions unless provided here, see above for details.

passwordstr or bytes, optional

Password for loading the private key of the CA, if any.

property usable: bool

True if the CA is currently usable or not.

Creating CAs

Use CertificateAuthority.objects.init() to create new certificate authorities. The method has many options but is designed to provide defaults that work in most cases:

>>> from cryptography.x509.oid import NameOID
>>> from django_ca.key_backends import key_backends
>>> from django_ca.key_backends.storages import CreatePrivateKeyOptions, UsePrivateKeyOptions
>>> from django_ca.models import CertificateAuthority
>>> key_backend = key_backends["default"]
>>> key_backend_options = CreatePrivateKeyOptions(
...     key_type="RSA", key_size=1024, password=None, path="ca"
... )
>>> ca = CertificateAuthority.objects.init(
...     name='ca',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "example.com")]),
...     path_length=1  # so we can create one level of intermediate CAs
... )
>>> ca
<CertificateAuthority: ca>

This CA will contain all properties and X509 extensions to be a fully functioning CA. To create an intermediate CA, simply pass the parent:

>>> child = CertificateAuthority.objects.init(
...     name='child',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     use_parent_private_key_options=UsePrivateKeyOptions(password=None),
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "child.example.com")]),
...     parent=ca
... )
>>> child.parent
<CertificateAuthority: ca>
>>> ca.children.all()
<CertificateAuthorityQuerySet [<CertificateAuthority: child>]>

Or to create a CA with all extensions that live CAs have, you can pass many more parameters:

>>> from cryptography import x509
>>> from cryptography.x509.oid import AuthorityInformationAccessOID, ExtensionOID
>>> full = CertificateAuthority.objects.init(
...     name='full',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "full.example.com")]),
...     parent=ca,  # some extensions are only valid for intermediate CAs
...     use_parent_private_key_options=UsePrivateKeyOptions(password=None),
...
...     # Extensions for the certificate authority itself
...     extensions=[
...         x509.Extension(
...             oid=ExtensionOID.NAME_CONSTRAINTS,
...             critical=True,
...             value=x509.NameConstraints(
...                 permitted_subtrees=[x509.DNSName('.com')],
...                 excluded_subtrees=None
...             ),
...         ),
...         x509.Extension(
...             oid=ExtensionOID.INHIBIT_ANY_POLICY,
...             critical=True,
...             value=x509.InhibitAnyPolicy(0)
...         )
...     ],
... )

You can also add extensions to be added to certificates when they are signed by this CA. These parameters can always be added later (but of course, only new certificates will have the changed values).

Note

The Authority Information Access extension and the CRL Distribution Points extension are added automatically if you have the CA_DEFAULT_HOSTNAME setting configured. If you still give the parameters to init(), the default values will be overwritten.

>>> from cryptography import x509
>>> from cryptography.x509.oid import AuthorityInformationAccessOID, CertificatePoliciesOID, ExtensionOID
>>> authority_information_access = x509.Extension(
...     oid=ExtensionOID.AUTHORITY_INFORMATION_ACCESS,
...     critical=False,  # RFC 5280 says it should not be critical
...     value=x509.AuthorityInformationAccess(
...         [
...             x509.AccessDescription(
...                 access_method=AuthorityInformationAccessOID.OCSP,
...                 access_location=x509.UniformResourceIdentifier("http://ca.example.com/ocsp")
...             )
...         ]
...     )
... )
>>> certificate_policies = x509.Extension(
...     oid=ExtensionOID.CERTIFICATE_POLICIES,
...     critical=False,  # RFC 5280 says it should not be critical
...     value=x509.CertificatePolicies(
...          [
...              x509.PolicyInformation(
...                  policy_identifier=CertificatePoliciesOID.CPS_USER_NOTICE,
...                  policy_qualifiers=["https://ca.example.com/cps"]
...              )
...          ]
...     )
... )
>>> crl_distribution_points = x509.Extension(
...     oid=ExtensionOID.CRL_DISTRIBUTION_POINTS,
...     critical=False,
...     value=x509.CRLDistributionPoints(
...         [
...             x509.DistributionPoint(
...                 full_name=[x509.UniformResourceIdentifier("http://ca.example.com/crl")],
...                 relative_name=None,
...                 crl_issuer=None,
...                 reasons=None
...             )
...         ]
...     )
... )
>>> issuer_alternative_name = x509.Extension(
...     oid=ExtensionOID.ISSUER_ALTERNATIVE_NAME,
...     critical=False,
...     value=x509.IssuerAlternativeName(
...         [
...             x509.UniformResourceIdentifier("https://ca.example.com")
...         ]
...     )
... )
>>> CertificateAuthority.objects.init(
...     name='add-extensions',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "add-extensions")]),
...     sign_authority_information_access=authority_information_access,
...     sign_certificate_policies=certificate_policies,
...     sign_crl_distribution_points=crl_distribution_points,
...     sign_issuer_alternative_name=None,
... )
<CertificateAuthority: add-extensions>

There are some more parameters to configure how the CA will be signed:

>>> from cryptography.hazmat.primitives.asymmetric import ec
>>> from cryptography.hazmat.primitives import hashes
>>> key_backend_options = CreatePrivateKeyOptions(
...     key_type="EC", elliptic_curve=ec.SECP256R1(), password=b"secret", path="ca"
... )
>>> CertificateAuthority.objects.init(
...     name="props",
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "child.example.com")]),
...     algorithm=hashes.SHA256(),  # SHA512 would be the default
...     path_length=3,  # three levels of intermediate CAs allowed,
...     key_type='EC',  # create a private key using Elliptic Curve cryptography
... )
<CertificateAuthority: props>

Here are all parameters for creating CAs:

CertificateAuthorityManager.init(name: str, key_backend: KeyBackend[Any, Any, Any], key_backend_options: BaseModel, subject: Name, expires: int | datetime | timedelta | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, parent: CertificateAuthority | None = None, use_parent_private_key_options: BaseModel | None = None, default_hostname: bool | str | None = None, path_length: int | None = None, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] = 'RSA', extensions: Iterable[Extension[ExtensionType]] | None = None, caa: str = '', website: str = '', terms_of_service: str = '', acme_enabled: bool = False, acme_registration: bool = True, acme_requires_contact: bool = True, acme_profile: str | None = None, openssh_ca: bool = False, sign_authority_information_access: Extension[AuthorityInformationAccess] | None = None, sign_certificate_policies: Extension[CertificatePolicies] | None = None, sign_crl_distribution_points: Extension[CRLDistributionPoints] | None = None, sign_issuer_alternative_name: Extension[IssuerAlternativeName] | None = None, ocsp_responder_key_validity: int | None = None, ocsp_response_validity: int | None = None, api_enabled: bool | None = None) CertificateAuthority[source]

Create a new certificate authority.

Changed in version 1.28.0:

  • The key_backend and key_backend_options parameters where added.

  • The path, password, key_size and elliptic_curve parameters where removed, they are now part of key_backend.

  • The parent_password parameter was removed, it is now part of the backend loaded for the parent.

  • The issuer_alt_name parameter was renamed to sign_issuer_alternative_name.

  • The crl_url option was removed in favor of sign_crl_distribution_points.

  • The issuer_url and ocsp_url options where removed in favor of sign_authority_information_access.

Changed in version 1.26.0:

  • The permitted_subtrees and excluded_subtrees subtrees where removed. Pass a NameConstraints extension in extensions instead.

  • Added the acme_registration option.

Parameters:
namestr

The name of the CA. This is a human-readable string and is used for administrative purposes only.

key_backendKeyBackend

A subclass of KeyBackend to use for storing the private key.

key_backend_optionsBaseModel

Parameters required for creating the private key using key_backend.

subjectcryptography.x509.Name

The desired subject for the certificate.

expiresint or datetime or timedelta, optional

When this certificate authority will expire, defaults to CA_DEFAULT_EXPIRES.

algorithmHashAlgorithm, optional

Hash algorithm used when signing the certificate, defaults to CA_DEFAULT_SIGNATURE_HASH_ALGORITHM for RSA/EC keys, and CA_DEFAULT_DSA_SIGNATURE_HASH_ALGORITHM for DSA keys. Passing an algorithm for Ed448/Ed25519 keys is an error.

parentCertificateAuthority, optional

Parent certificate authority for the new CA. Passing this value makes the CA an intermediate authority. Let unset if this CA will be used for OpenSSH.

use_parent_private_key_optionsBaseModel, optional

Transient parameters required for signing certificates with parent (e.g. a password). This argument is required if parent is given.

default_hostnamestr, optional

Override the URL configured with CA_DEFAULT_HOSTNAME with a different hostname. Set to False to disable the hostname.

path_lengthint, optional

Value of the path length attribute for the Basic Constraints extension.

key_type: str, optional

The type of private key to generate, must be one of "RSA", "DSA", "EC", or "Ed25519" , with "RSA" being the default.

extensionslist of cryptography.x509.Extension

An optional list of additional extensions to add to the certificate.

caastr, optional

CAA identity. Note that this field is not yet currently used.

websitestr, optional

URL to a human-readable website.

terms_of_servicestr, optional

URL to the terms of service for the CA.

acme_enabledbool, optional

Set to True to enable ACMEv2 support for this CA.

acme_registrationbool, optional

Whether to allow ACMEv2 clients to register new ACMEv2 accounts (if support is enabled in the first place). By default, account registration is enabled.

acme_profilestr, optional

The profile to use when issuing certificates via ACMEv2. Defaults to the CA_DEFAULT_PROFILE.

acme_requires_contactbool, optional

Set to False if you do not want to force clients to register with an email address.

openssh_cabool, optional

Set to True if you want to use this to use this CA for signing OpenSSH certs.

sign_authority_information_accessExtension, optional

Add the given Authority Information Access extension when signing certificates.

sign_certificate_policiesExtension, optional

Add the given Certificate Policies extension when signing certificates.

sign_crl_distribution_pointsExtension, optional

Add the given CRL Distribution Points extension when signing certificates.

sign_issuer_alternative_nameExtension, optional

Add the given Issuer Alternative Name extension when signing certificates.

ocsp_responder_key_validityint, optional

How long (in days) OCSP responder keys should be valid.

ocsp_response_validityint, optional

How long (in seconds) OCSP responses should be valid.

api_enabledbool, optional

If the REST API shall be enabled.

Raises:
ValueError

For various cases of wrong input data (e.g. extensions of invalid type).

Certificate

class django_ca.models.Certificate(*args, **kwargs)[source]

Model representing a x509 Certificate.

property bundle: List[X509CertMixin]

The complete certificate bundle. This includes all CAs as well as the certificates itself.

property root: CertificateAuthority

Get the root CA for this certificate.

Manager methods

CertificateManager is the default manager for Certificate, meaning you can access it using Certificate.objects, e.g.:

>>> csr  
<...CertificateSigningRequest object at ...>
>>> from django_ca.models import Certificate
>>> Certificate.objects.create_cert(
...     ca=ca,
...     key_backend_options=UsePrivateKeyOptions(password=None),
...     csr=csr,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "example.com")])
... )
<Certificate: example.com>
class django_ca.managers.CertificateManager(*args, **kwargs)[source]

Model manager for the Certificate model.

create_cert(ca: CertificateAuthority, key_backend_options: BaseModel, csr: CertificateSigningRequest, profile: Profile | None = None, autogenerated: bool | None = None, subject: Name | None = None, expires: int | datetime | timedelta | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, extensions: Iterable[Extension[ExtensionType]] | None = None, add_crl_url: bool | None = None, add_ocsp_url: bool | None = None, add_issuer_url: bool | None = None, add_issuer_alternative_name: bool | None = None) Certificate[source]

Create and sign a new certificate based on the given profile.

Parameters:
caCertificateAuthority

The certificate authority to sign the certificate with.

key_backend_optionsBaseModel

Transient parameters required for signing certificates with ca (e.g. a password).

csrCertificateSigningRequest

The certificate signing request to use when signing a certificate. Passing a str or bytes is deprecated and will be removed in django-ca 1.20.0.

profileProfile, optional

The name of a profile or a manually created Profile instance. If not given, the profile configured by CA_DEFAULT_PROFILE is used.

autogeneratedbool, optional

Override the profiles autogenerated flag.

subjectName, optional

Passed to Profiles.create_cert().

expiresint or datetime or timedelta, optional

Passed to Profiles.create_cert().

algorithmHashAlgorithm, optional

Passed to Profiles.create_cert().

extensionslist or of Extension

Passed to Profiles.create_cert().

add_crl_urlbool, optional

Passed to Profiles.create_cert().

add_ocsp_urlbool, optional

Passed to Profiles.create_cert().

add_issuer_urlbool, optional

Passed to Profiles.create_cert().

add_issuer_alternative_namebool, optional

Passed to Profiles.create_cert().

X509CertMixin

X509CertMixin is a common base class to both CertificateAuthority and Certificate and provides many convenience attributes.

class django_ca.models.X509CertMixin(*args, **kwargs)[source]

Mixin class with common attributes for Certificates and Certificate Authorities.

property algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None

A shortcut for signature_hash_algorithm.

property bundle_as_pem: str

Get the bundle as PEM.

extensions

All extensions of this certificate in a dict.

The key is the OID for the respective extension, allowing easy to look up a particular extension.

get_compromised_time() datetime | None[source]

Return when this certificate was compromised as a naive datetime.

Returns None if the time is not known or if the certificate is not revoked.

get_fingerprint(algorithm: HashAlgorithm) str[source]

Get the digest for a certificate as string, including colons.

get_revocation() RevokedCertificate[source]

Get the RevokedCertificate instance for this certificate for CRLs.

This function is just a shortcut for RevokedCertificateBuilder.

Returns:
RevokedCertificate
Raises:
ValueError

If the certificate is not revoked.

get_revocation_reason() ReasonFlags | None[source]

Get the revocation reason of this certificate.

get_revocation_time() datetime | None[source]

Get the revocation time as naive datetime.

property issuer: Name

The certificate issuer field as Name.

property jwk: JWKRSA | JWKEC

Get a JOSE JWK public key for this certificate.

Note

josepy (the underlying library) does not currently support loading Ed448 or Ed25519 public keys. This property will raise ValueError if called for a public key based on those algorithms. The issue is addressed in this pull request.

property not_after: datetime

A timezone-aware datetime representing the end of the validity period.

property not_before: datetime

A timezone-aware datetime representing the beginning of the validity period.

revoke(reason: ReasonFlags = ReasonFlags.unspecified, compromised: datetime | None = None) None[source]

Revoke the current certificate.

This function emits the pre_revoke_cert and post_revoke_cert signals.

Parameters:
reasonReasonFlags, optional

The reason for revocation, defaults to ReasonFlags.unspecified.

compromiseddatetime, optional

When this certificate was compromised.

sorted_extensions

List of extensions sorted by their human-readable name.

This property is used for display purposes, where a reproducible output is desired.

property subject: Name

The certificate subject field as Name.

update_certificate(value: Certificate) None[source]

Update this instance with data from a cryptography.x509.Certificate.

This function will also populate the cn, serial, `expires and valid_from fields.

Watchers

class django_ca.models.Watcher(*args, **kwargs)[source]

A watcher represents an email address that will receive notifications about expiring certificates.

classmethod from_addr(addr: str) Watcher[source]

Class constructor that creates an instance from an email address.

ACME

class django_ca.models.AcmeAccount(*args, **kwargs)[source]

Implements an ACME account object.

See also

RFC 8555, 7.1.2

property serial: str

Serial of the CA for this account.

set_kid(request: HttpRequest) None[source]

Set the ACME kid based on this accounts CA and slug.

Note that slug and ca must be already set when using this method.

property usable: bool

Boolean if the account is currently usable.

An account is usable if the terms of service have been agreed, the status is “valid” and the associated CA is usable.

class django_ca.models.AcmeOrder(*args, **kwargs)[source]

Implements an ACME order object.

See also

RFC 8555, 7.1.3

property acme_finalize_url: str

Get the ACME “finalize” URL path for this order.

property acme_url: str

Get the ACME URL path for this order.

add_authorizations(identifiers: Iterable[Identifier]) List[AcmeAuthorization][source]

Add AcmeAuthorization instances for the given identifiers.

Note that this method already adds the account authorization to the database. It does not verify if it already exists and will raise an IntegrityError if it does.

Example:

>>> from acme import messages
>>> identifier = messages.Identifier(typ=messages.IDENTIFIER_FQDN, value='example.com')
>>> order.add_authorizations([identifier])  
Parameters:
identifierslist of acme.messages.Identifier

The identifiers for this order.

Returns:
list of AcmeAuthorization
property serial: str

Serial of the CA for this order.

property usable: bool

Boolean defining if an order is “usable”, meaning it can be used to issue a certificate.

An order is usable if it is in the “pending” status, has not expired and the account is usable.

class django_ca.models.AcmeAuthorization(*args, **kwargs)[source]

Implements an ACME authorization object.

See also

RFC 8555, 7.1.4

property account: AcmeAccount

Account that this authorization belongs to.

property acme_url: str

Get the ACME URL path for this account authorization.

property expires: datetime

When this authorization expires.

property general_name: GeneralName

Get the GeneralName instance for this instance.

get_challenges() List[AcmeChallenge][source]

Get list of AcmeChallenge objects for this authorization.

Note that challenges will be created if they don’t exist.

property identifier: Identifier

Get ACME identifier for this object.

Returns:
identifieracme.messages.Identifier
property serial: str

Serial of the CA for this authorization.

property subject_alternative_name: str

Get the domain for this challenge as prefixed SubjectAlternativeName.

This method is intended to be used when creating the django_ca.extensions.SubjectAlternativeName extension for a certificate to be signed.

property usable: bool

Boolean defining if an authentication can still can be used in order validation.

An order is usable if it is in the “pending” or “invalid” status, the order is usable. An authorization that is in the “invalid” status is eligible to be retried by the client.

class django_ca.models.AcmeChallenge(*args, **kwargs)[source]

Implements an ACME Challenge Object.

property account: AcmeAccount

Account that this challenge belongs to.

property acme_challenge: KeyAuthorizationChallenge

Challenge as ACME challenge object.

Returns:
acme.challenges.Challenge

The acme representation of this class.

property acme_url: str

Get the ACME URL path for this challenge.

property acme_validated: datetime | None

Timestamp when this challenge was validated.

This property is a wrapper around the validated field. It always returns None if the challenge is not marked as valid (even if it had a timestamp), and the timestamp will always have a timezone, even if USE_TZ=False.

property encoded_token: bytes

Token in base64url encoded form.

property expected: bytes

Expected value for the challenge based on its type.

get_challenge(request: HttpRequest) ChallengeBody[source]

Get the ACME challenge body for this challenge.

Returns:
acme.messages.ChallengeBody

The acme representation of this class.

property serial: str

Serial of the CA for this challenge.

property usable: bool

Boolean defining if a challenge is “usable”, meaning it still can be used in order validation.

A challenge is usable if it is in the “pending” or “invalid status and the authorization is usable.

class django_ca.models.AcmeCertificate(*args, **kwargs)[source]

Intermediate model for certificates to be issued via ACME.

property acme_url: str

Get the ACME URL path for this certificate.

parse_csr() CertificateSigningRequest[source]

Load the CSR into a cryptography object.

Returns:
CertificateSigningRequest

The CSR as used by cryptography.

property usable: bool

Boolean defining if this instance is “usable”, meaning we can use it to issue a certificate.

An ACME certificate is considered usable if no actual certificate has yet been issued, the order is not expired and in the “processing” state.