class Meta(jose.JSONObjectWithFields): """Directory Meta.""" _terms_of_service: str = jose.field('terms-of-service', omitempty=True) _terms_of_service_v2: str = jose.field('termsOfService', omitempty=True) website: str = jose.field('website', omitempty=True) caa_identities: List[str] = jose.field('caaIdentities', omitempty=True) external_account_required: bool = jose.field('externalAccountRequired', omitempty=True) def __init__(self, **kwargs: Any) -> None: kwargs = {self._internal_name(k): v for k, v in kwargs.items()} super().__init__(**kwargs) @property def terms_of_service(self) -> str: """URL for the CA TOS""" return self._terms_of_service or self._terms_of_service_v2 def __iter__(self) -> Iterator[str]: # When iterating over fields, use the external name 'terms_of_service' instead of # the internal '_terms_of_service'. for name in super().__iter__(): yield name[1:] if name == '_terms_of_service' else name def _internal_name(self, name: str) -> str: return '_' + name if name == 'terms_of_service' else name
class Error(jose.JSONObjectWithFields, errors.Error): """ACME error. https://tools.ietf.org/html/draft-ietf-appsawg-http-problem-00 :ivar str typ: :ivar str title: :ivar str detail: """ typ: str = jose.field('type', omitempty=True, default='about:blank') title: str = jose.field('title', omitempty=True) detail: str = jose.field('detail', omitempty=True) @classmethod def with_code(cls, code: str, **kwargs: Any) -> 'Error': """Create an Error instance with an ACME Error code. :str code: An ACME error code, like 'dnssec'. :kwargs: kwargs to pass to Error. """ if code not in ERROR_CODES: raise ValueError("The supplied code: %s is not a known ACME error" " code" % code) typ = ERROR_PREFIX + code # Mypy will not understand that the Error constructor accepts a named argument # "typ" because of josepy magic. Let's ignore the type check here. return cls(typ=typ, **kwargs) @property def description(self) -> Optional[str]: """Hardcoded error description based on its type. :returns: Description if standard ACME error or ``None``. :rtype: str """ return ERROR_TYPE_DESCRIPTIONS.get(self.typ) @property def code(self) -> Optional[str]: """ACME error code. Basically self.typ without the ERROR_PREFIX. :returns: error code if standard ACME code or ``None``. :rtype: str """ code = str(self.typ).rsplit(':', maxsplit=1)[-1] if code in ERROR_CODES: return code return None def __str__(self) -> str: return b' :: '.join( part.encode('ascii', 'backslashreplace') for part in (self.typ, self.description, self.detail, self.title) if part is not None).decode()
class Authorization(ResourceBody): """Authorization Resource Body. :ivar acme.messages.Identifier identifier: :ivar list challenges: `list` of `.ChallengeBody` :ivar tuple combinations: Challenge combinations (`tuple` of `tuple` of `int`, as opposed to `list` of `list` from the spec). :ivar acme.messages.Status status: :ivar datetime.datetime expires: """ identifier: Identifier = jose.field('identifier', decoder=Identifier.from_json, omitempty=True) challenges: List[ChallengeBody] = jose.field('challenges', omitempty=True) combinations: Tuple[Tuple[int, ...], ...] = jose.field('combinations', omitempty=True) status: Status = jose.field('status', omitempty=True, decoder=Status.from_json) # TODO: 'expires' is allowed for Authorization Resources in # general, but for Key Authorization '[t]he "expires" field MUST # be absent'... then acme-spec gives example with 'expires' # present... That's confusing! expires: datetime.datetime = fields.rfc3339('expires', omitempty=True) wildcard: bool = jose.field('wildcard', omitempty=True) # Mypy does not understand the josepy magic happening here, and falsely claims # that challenge is redefined. Let's ignore the type check here. @challenges.decoder # type: ignore def challenges(value: List[Dict[str, Any]]) -> Tuple[ChallengeBody, ...]: # type: ignore[misc] # pylint: disable=no-self-argument,missing-function-docstring return tuple(ChallengeBody.from_json(chall) for chall in value) @property def resolved_combinations(self) -> Tuple[Tuple[ChallengeBody, ...], ...]: """Combinations with challenges instead of indices.""" return tuple(tuple(self.challenges[idx] for idx in combo) for combo in self.combinations) # pylint: disable=not-an-iterable
class Identifier(jose.JSONObjectWithFields): """ACME identifier. :ivar IdentifierType typ: :ivar str value: """ typ: IdentifierType = jose.field('type', decoder=IdentifierType.from_json) value: str = jose.field('value')
class AuthorizationResource(ResourceWithURI): """Authorization Resource. :ivar acme.messages.Authorization body: :ivar str new_cert_uri: Deprecated. Do not use. """ body: Authorization = jose.field('body', decoder=Authorization.from_json) new_cert_uri: str = jose.field('new_cert_uri', omitempty=True)
class CertificateResource(ResourceWithURI): """Certificate Resource. :ivar josepy.util.ComparableX509 body: `OpenSSL.crypto.X509` wrapped in `.ComparableX509` :ivar str cert_chain_uri: URI found in the 'up' ``Link`` header :ivar tuple authzrs: `tuple` of `AuthorizationResource`. """ cert_chain_uri: str = jose.field('cert_chain_uri') authzrs: Tuple[AuthorizationResource, ...] = jose.field('authzrs')
class RegistrationResource(ResourceWithURI): """Registration Resource. :ivar acme.messages.Registration body: :ivar str new_authzr_uri: Deprecated. Do not use. :ivar str terms_of_service: URL for the CA TOS. """ body: Registration = jose.field('body', decoder=Registration.from_json) new_authzr_uri: str = jose.field('new_authzr_uri', omitempty=True) terms_of_service: str = jose.field('terms_of_service', omitempty=True)
class Revocation(ResourceMixin, jose.JSONObjectWithFields): """Revocation message. :ivar jose.ComparableX509 certificate: `OpenSSL.crypto.X509` wrapped in `jose.ComparableX509` """ resource_type = 'revoke-cert' resource: str = fields.resource(resource_type) certificate: jose.ComparableX509 = jose.field( 'certificate', decoder=jose.decode_cert, encoder=jose.encode_cert) reason: int = jose.field('reason')
class ChallengeResource(Resource): """Challenge Resource. :ivar acme.messages.ChallengeBody body: :ivar str authzr_uri: URI found in the 'up' ``Link`` header. """ body: ChallengeBody = jose.field('body', decoder=ChallengeBody.from_json) authzr_uri: str = jose.field('authzr_uri') @property def uri(self) -> str: """The URL of the challenge body.""" return self.body.uri # pylint: disable=no-member
class Meta(jose.JSONObjectWithFields): """Account metadata :ivar datetime.datetime creation_dt: Creation date and time (UTC). :ivar str creation_host: FQDN of host, where account has been created. :ivar str register_to_eff: If not None, Certbot will register the provided email during the account registration. .. note:: ``creation_dt`` and ``creation_host`` are useful in cross-machine migration scenarios. """ creation_dt: datetime.datetime = acme_fields.rfc3339("creation_dt") creation_host: str = jose.field("creation_host") register_to_eff: str = jose.field("register_to_eff", omitempty=True)
class ResourceWithURI(Resource): """ACME Resource with URI. :ivar str uri: Location of the resource. """ uri: str = jose.field('uri') # no ChallengeResource.uri
class _TokenChallenge(Challenge): """Challenge with token. :ivar bytes token: """ TOKEN_SIZE = 128 / 8 # Based on the entropy value from the spec """Minimum size of the :attr:`token` in bytes.""" # TODO: acme-spec doesn't specify token as base64-encoded value token: bytes = jose.field("token", encoder=jose.encode_b64jose, decoder=functools.partial(jose.decode_b64jose, size=TOKEN_SIZE, minimum=True)) # XXX: rename to ~token_good_for_url @property def good_token(self) -> bool: # XXX: @token.decoder """Is `token` good? .. todo:: acme-spec wants "It MUST NOT contain any non-ASCII characters", but it should also warrant that it doesn't contain ".." or "/"... """ # TODO: check that path combined with uri does not go above # URI_ROOT_PATH! # pylint: disable=unsupported-membership-test return b'..' not in self.token and b'/' not in self.token
class Resource(jose.JSONObjectWithFields): """ACME Resource. :ivar acme.messages.ResourceBody body: Resource body. """ body: "ResourceBody" = jose.field('body')
class Header(jose.Header): """ACME-specific JOSE Header. Implements nonce, kid, and url. """ nonce: Optional[bytes] = jose.field('nonce', omitempty=True, encoder=jose.encode_b64jose) kid: Optional[str] = jose.field('kid', omitempty=True) url: Optional[str] = jose.field('url', omitempty=True) # Mypy does not understand the josepy magic happening here, and falsely claims # that nonce is redefined. Let's ignore the type check here. @nonce.decoder # type: ignore[no-redef,union-attr] def nonce(value: str) -> bytes: # type: ignore[misc] # pylint: disable=no-self-argument,missing-function-docstring try: return jose.decode_b64jose(value) except jose.DeserializationError as error: # TODO: custom error raise jose.DeserializationError("Invalid nonce: {0}".format(error))
class RegistrationResourceWithNewAuthzrURI(messages.RegistrationResource): """A backwards-compatible RegistrationResource with a new-authz URI. Hack: Certbot versions pre-0.11.1 expect to load new_authzr_uri as part of the account. Because people sometimes switch between old and new versions, we will continue to write out this field for some time so older clients don't crash in that scenario. """ new_authzr_uri: str = jose.field('new_authzr_uri')
class CertificateRequest(ResourceMixin, jose.JSONObjectWithFields): """ACME new-cert request. :ivar jose.ComparableX509 csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509` """ resource_type = 'new-cert' resource: str = fields.resource(resource_type) csr: jose.ComparableX509 = jose.field('csr', decoder=jose.decode_csr, encoder=jose.encode_csr)
class Signature(jose.Signature): """ACME-specific Signature. Uses ACME-specific Header for customer fields.""" __slots__ = jose.Signature._orig_slots # type: ignore[attr-defined] # pylint: disable=protected-access,no-member # TODO: decoder/encoder should accept cls? Otherwise, subclassing # JSONObjectWithFields is tricky... header_cls = Header header: Header = jose.field('header', omitempty=True, default=header_cls(), decoder=header_cls.from_json)
class OrderResource(ResourceWithURI): """Order Resource. :ivar acme.messages.Order body: :ivar bytes csr_pem: The CSR this Order will be finalized with. :ivar authorizations: Fully-fetched AuthorizationResource objects. :vartype authorizations: `list` of `acme.messages.AuthorizationResource` :ivar str fullchain_pem: The fetched contents of the certificate URL produced once the order was finalized, if it's present. :ivar alternative_fullchains_pem: The fetched contents of alternative certificate chain URLs produced once the order was finalized, if present and requested during finalization. :vartype alternative_fullchains_pem: `list` of `str` """ body: Order = jose.field('body', decoder=Order.from_json) csr_pem: bytes = jose.field('csr_pem', omitempty=True) authorizations: List[AuthorizationResource] = jose.field('authorizations') fullchain_pem: str = jose.field('fullchain_pem', omitempty=True) alternative_fullchains_pem: List[str] = jose.field( 'alternative_fullchains_pem', omitempty=True)
class Order(ResourceBody): """Order Resource Body. :ivar identifiers: List of identifiers for the certificate. :vartype identifiers: `list` of `.Identifier` :ivar acme.messages.Status status: :ivar authorizations: URLs of authorizations. :vartype authorizations: `list` of `str` :ivar str certificate: URL to download certificate as a fullchain PEM. :ivar str finalize: URL to POST to to request issuance once all authorizations have "valid" status. :ivar datetime.datetime expires: When the order expires. :ivar ~.Error error: Any error that occurred during finalization, if applicable. """ identifiers: List[Identifier] = jose.field('identifiers', omitempty=True) status: Status = jose.field('status', decoder=Status.from_json, omitempty=True) authorizations: List[str] = jose.field('authorizations', omitempty=True) certificate: str = jose.field('certificate', omitempty=True) finalize: str = jose.field('finalize', omitempty=True) expires: datetime.datetime = fields.rfc3339('expires', omitempty=True) error: Error = jose.field('error', omitempty=True, decoder=Error.from_json) # Mypy does not understand the josepy magic happening here, and falsely claims # that identifiers is redefined. Let's ignore the type check here. @identifiers.decoder # type: ignore def identifiers(value: List[Dict[str, Any]]) -> Tuple[Identifier, ...]: # type: ignore[misc] # pylint: disable=no-self-argument,missing-function-docstring return tuple(Identifier.from_json(identifier) for identifier in value)
class KeyAuthorizationChallengeResponse(ChallengeResponse): """Response to Challenges based on Key Authorization. :param str key_authorization: """ key_authorization: str = jose.field("keyAuthorization") thumbprint_hash_function = hashes.SHA256 def verify(self, chall: 'KeyAuthorizationChallenge', account_public_key: jose.JWK) -> bool: """Verify the key authorization. :param KeyAuthorization chall: Challenge that corresponds to this response. :param JWK account_public_key: :return: ``True`` iff verification of the key authorization was successful. :rtype: bool """ parts = self.key_authorization.split('.') # pylint: disable=no-member if len(parts) != 2: logger.debug("Key authorization (%r) is not well formed", self.key_authorization) return False if parts[0] != chall.encode("token"): logger.debug( "Mismatching token in key authorization: " "%r instead of %r", parts[0], chall.encode("token")) return False thumbprint = jose.b64encode( account_public_key.thumbprint( hash_function=self.thumbprint_hash_function)).decode() if parts[1] != thumbprint: logger.debug( "Mismatching thumbprint in key authorization: " "%r instead of %r", parts[0], thumbprint) return False return True def to_partial_json(self) -> Dict[str, Any]: jobj = super().to_partial_json() jobj.pop('keyAuthorization', None) return jobj
class DNSResponse(ChallengeResponse): """ACME "dns" challenge response. :param JWS validation: """ typ = "dns" validation: jose.JWS = jose.field("validation", decoder=jose.JWS.from_json) def check_validation(self, chall: 'DNS', account_public_key: jose.JWK) -> bool: """Check validation. :param challenges.DNS chall: :param JWK account_public_key: :rtype: bool """ return chall.check_validation(self.validation, account_public_key)
class Error(jose.JSONObjectWithFields, errors.Error): """ACME error. https://datatracker.ietf.org/doc/html/rfc7807 :ivar str typ: :ivar str title: :ivar str detail: :ivar Identifier identifier: :ivar tuple subproblems: An array of ACME Errors which may be present when the CA returns multiple errors related to the same request, `tuple` of `Error`. """ typ: str = jose.field('type', omitempty=True, default='about:blank') title: str = jose.field('title', omitempty=True) detail: str = jose.field('detail', omitempty=True) identifier: Optional['Identifier'] = jose.field( 'identifier', decoder=Identifier.from_json, omitempty=True) subproblems: Optional[Tuple['Error', ...]] = jose.field('subproblems', omitempty=True) # Mypy does not understand the josepy magic happening here, and falsely claims # that subproblems is redefined. Let's ignore the type check here. @subproblems.decoder # type: ignore def subproblems(value: List[Dict[str, Any]]) -> Tuple['Error', ...]: # type: ignore[misc] # pylint: disable=no-self-argument,missing-function-docstring return tuple(Error.from_json(subproblem) for subproblem in value) @classmethod def with_code(cls, code: str, **kwargs: Any) -> 'Error': """Create an Error instance with an ACME Error code. :str code: An ACME error code, like 'dnssec'. :kwargs: kwargs to pass to Error. """ if code not in ERROR_CODES: raise ValueError("The supplied code: %s is not a known ACME error" " code" % code) typ = ERROR_PREFIX + code # Mypy will not understand that the Error constructor accepts a named argument # "typ" because of josepy magic. Let's ignore the type check here. return cls(typ=typ, **kwargs) @property def description(self) -> Optional[str]: """Hardcoded error description based on its type. :returns: Description if standard ACME error or ``None``. :rtype: str """ return ERROR_TYPE_DESCRIPTIONS.get(self.typ) @property def code(self) -> Optional[str]: """ACME error code. Basically self.typ without the ERROR_PREFIX. :returns: error code if standard ACME code or ``None``. :rtype: str """ code = str(self.typ).rsplit(':', maxsplit=1)[-1] if code in ERROR_CODES: return code return None def __str__(self) -> str: result = b' :: '.join( part.encode('ascii', 'backslashreplace') for part in (self.typ, self.description, self.detail, self.title) if part is not None).decode() if self.identifier: result = f'Problem for {self.identifier.value}: ' + result # pylint: disable=no-member if self.subproblems and len(self.subproblems) > 0: for subproblem in self.subproblems: result += f'\n{subproblem}' return result
class Registration(ResourceBody): """Registration Resource Body. :ivar jose.JWK key: Public key. :ivar tuple contact: Contact information following ACME spec, `tuple` of `str`. :ivar str agreement: """ # on new-reg key server ignores 'key' and populates it based on # JWS.signature.combined.jwk key: jose.JWK = jose.field('key', omitempty=True, decoder=jose.JWK.from_json) # Contact field implements special behavior to allow messages that clear existing # contacts while not expecting the `contact` field when loading from json. # This is implemented in the constructor and *_json methods. contact: Tuple[str, ...] = jose.field('contact', omitempty=True, default=()) agreement: str = jose.field('agreement', omitempty=True) status: Status = jose.field('status', omitempty=True) terms_of_service_agreed: bool = jose.field('termsOfServiceAgreed', omitempty=True) only_return_existing: bool = jose.field('onlyReturnExisting', omitempty=True) external_account_binding: Dict[str, Any] = jose.field('externalAccountBinding', omitempty=True) phone_prefix = 'tel:' email_prefix = 'mailto:' @classmethod def from_data(cls: Type[GenericRegistration], phone: Optional[str] = None, email: Optional[str] = None, external_account_binding: Optional[Dict[str, Any]] = None, **kwargs: Any) -> GenericRegistration: """ Create registration resource from contact details. The `contact` keyword being passed to a Registration object is meaningful, so this function represents empty iterables in its kwargs by passing on an empty `tuple`. """ # Note if `contact` was in kwargs. contact_provided = 'contact' in kwargs # Pop `contact` from kwargs and add formatted email or phone numbers details = list(kwargs.pop('contact', ())) if phone is not None: details.append(cls.phone_prefix + phone) if email is not None: details.extend( [cls.email_prefix + mail for mail in email.split(',')]) # Insert formatted contact information back into kwargs # or insert an empty tuple if `contact` provided. if details or contact_provided: kwargs['contact'] = tuple(details) if external_account_binding: kwargs['external_account_binding'] = external_account_binding return cls(**kwargs) def __init__(self, **kwargs: Any) -> None: """Note if the user provides a value for the `contact` member.""" if 'contact' in kwargs and kwargs['contact'] is not None: # Avoid the __setattr__ used by jose.TypedJSONObjectWithFields object.__setattr__(self, '_add_contact', True) super().__init__(**kwargs) def _filter_contact(self, prefix: str) -> Tuple[str, ...]: return tuple(detail[len(prefix):] for detail in self.contact # pylint: disable=not-an-iterable if detail.startswith(prefix)) def _add_contact_if_appropriate(self, jobj: Dict[str, Any]) -> Dict[str, Any]: """ The `contact` member of Registration objects should not be required when de-serializing (as it would be if the Fields' `omitempty` flag were `False`), but it should be included in serializations if it was provided. :param jobj: Dictionary containing this Registrations' data :type jobj: dict :returns: Dictionary containing Registrations data to transmit to the server :rtype: dict """ if getattr(self, '_add_contact', False): jobj['contact'] = self.encode('contact') return jobj def to_partial_json(self) -> Dict[str, Any]: """Modify josepy.JSONDeserializable.to_partial_json()""" jobj = super().to_partial_json() return self._add_contact_if_appropriate(jobj) def fields_to_partial_json(self) -> Dict[str, Any]: """Modify josepy.JSONObjectWithFields.fields_to_partial_json()""" jobj = super().fields_to_partial_json() return self._add_contact_if_appropriate(jobj) @property def phones(self) -> Tuple[str, ...]: """All phones found in the ``contact`` field.""" return self._filter_contact(self.phone_prefix) @property def emails(self) -> Tuple[str, ...]: """All emails found in the ``contact`` field.""" return self._filter_contact(self.email_prefix)
class ChallengeBody(ResourceBody): """Challenge Resource Body. .. todo:: Confusingly, this has a similar name to `.challenges.Challenge`, as well as `.achallenges.AnnotatedChallenge`. Please use names such as ``challb`` to distinguish instances of this class from ``achall``. :ivar acme.challenges.Challenge: Wrapped challenge. Conveniently, all challenge fields are proxied, i.e. you can call ``challb.x`` to get ``challb.chall.x`` contents. :ivar acme.messages.Status status: :ivar datetime.datetime validated: :ivar messages.Error error: """ __slots__ = ('chall', ) # ACMEv1 has a "uri" field in challenges. ACMEv2 has a "url" field. This # challenge object supports either one, but should be accessed through the # name "uri". In Client.answer_challenge, whichever one is set will be # used. _uri: str = jose.field('uri', omitempty=True, default=None) _url: str = jose.field('url', omitempty=True, default=None) status: Status = jose.field('status', decoder=Status.from_json, omitempty=True, default=STATUS_PENDING) validated: datetime.datetime = fields.rfc3339('validated', omitempty=True) error: Error = jose.field('error', decoder=Error.from_json, omitempty=True, default=None) def __init__(self, **kwargs: Any) -> None: kwargs = {self._internal_name(k): v for k, v in kwargs.items()} super().__init__(**kwargs) def encode(self, name: str) -> Any: return super().encode(self._internal_name(name)) def to_partial_json(self) -> Dict[str, Any]: jobj = super().to_partial_json() jobj.update(self.chall.to_partial_json()) return jobj @classmethod def fields_from_json(cls, jobj: Mapping[str, Any]) -> Dict[str, Any]: jobj_fields = super().fields_from_json(jobj) jobj_fields['chall'] = challenges.Challenge.from_json(jobj) return jobj_fields @property def uri(self) -> str: """The URL of this challenge.""" return self._url or self._uri def __getattr__(self, name: str) -> Any: return getattr(self.chall, name) def __iter__(self) -> Iterator[str]: # When iterating over fields, use the external name 'uri' instead of # the internal '_uri'. for name in super().__iter__(): yield name[1:] if name == '_uri' else name def _internal_name(self, name: str) -> str: return '_' + name if name == 'uri' else name