Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fully remove OpenSSL #212

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ Changelog

2.0.0 (main)
-------------------
* Breaking Change: PyOpenSSL has been fully removed.
- Dropped objects:
`josepy.util.ComparableX509`
- Functions now expect `cryptography.x509` objects:
`josepy.json_util.encode_cert`
`josepy.json_util.encode_csr`
`josepy.jws.Header.x5c.encoder`
- Functions now return `cryptography.x509` objects:
`josepy.json_util.decode_cert`
`josepy.json_util.decode_csr`
`josepy.jws.Header.x5c.decoder`


1.15.0 (2025-01-22)
-------------------
Expand Down
54 changes: 3 additions & 51 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 1 addition & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "josepy"
version = "1.16.0.dev0"
version = "2.0.0.dev0"
description = "JOSE protocol implementation in Python"
license = "Apache License 2.0"
classifiers = [
Expand Down Expand Up @@ -43,8 +43,6 @@ python = "^3.8"
# rsa_recover_prime_factors (>=0.8)
# add sign() and verify() to asymetric keys (RSA >=1.4, ECDSA >=1.5)
cryptography = ">=1.5"
# Connection.set_tlsext_host_name (>=0.13)
pyopenssl = ">=0.13"
# >=4.3.0 is needed for Python 3.10 support
sphinx = {version = ">=4.3.0", optional = true}
sphinx-rtd-theme = {version = ">=1.0", optional = true}
Expand All @@ -57,7 +55,6 @@ coverage = {version = ">=4.0", extras = ["toml"]}
# https://github.com/python/importlib_resources/tree/7f4fbb5ee026d7610636d5ece18b09c64aa0c893#compatibility.
importlib_resources = {version = ">=1.3", python = "<3.9"}
mypy = "*"
types-pyOpenSSL = "*"
types-pyRFC3339 = "*"
types-requests = "*"
types-setuptools = "*"
Expand Down Expand Up @@ -97,11 +94,8 @@ disallow_untyped_defs = true
[tool.pytest.ini_options]
filterwarnings = [
"error",
"ignore:CSR support in pyOpenSSL is deprecated:DeprecationWarning",
# We ignore our own warning about dropping Python 3.8 support.
"ignore:Python 3.8 support will be dropped:DeprecationWarning",
# We ignore our own warning about ComparableX509
"ignore:.*josepy will remove josepy.util.ComparableX509",
]
norecursedirs = "*.egg .eggs dist build docs .tox"

Expand Down
1 change: 0 additions & 1 deletion src/josepy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@
ComparableECKey,
ComparableKey,
ComparableRSAKey,
ComparableX509,
ImmutableMap,
)

Expand Down
55 changes: 34 additions & 21 deletions src/josepy/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
TypeVar,
)

from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding

from josepy import b64, errors, interfaces, util

Expand Down Expand Up @@ -426,59 +427,71 @@ def decode_hex16(value: str, size: Optional[int] = None, minimum: bool = False)
raise errors.DeserializationError(error)


def encode_cert(cert: util.ComparableX509) -> str:
def encode_cert(cert: x509.Certificate) -> str:
"""Encode certificate as JOSE Base-64 DER.

:type cert: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
:type cert: `cryptography.x509.Certificate`
:rtype: unicode

.. versionchanged:: 2.0.0
The `cert` parameter is now `cryptography.x509.Certificate`.
Previously this was an `josepy.util.ComparableX509` object, which wrapped
an `OpenSSL.crypto.X509` object.
"""
if isinstance(cert.wrapped, crypto.X509Req):
if isinstance(cert, x509.CertificateSigningRequest):
raise ValueError("Error input is actually a certificate request.")

return encode_b64jose(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert.wrapped))
return encode_b64jose(cert.public_bytes(Encoding.DER))


def decode_cert(b64der: str) -> util.ComparableX509:
def decode_cert(b64der: str) -> x509.Certificate:
"""Decode JOSE Base-64 DER-encoded certificate.

:param unicode b64der:
:rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
:rtype: `cryptography.x509.Certificate`

.. versionchanged:: 2.0.0
The returned object is now a `cryptography.x509.Certificate`.
Previously this was an `josepy.util.ComparableX509` object, which wrapped
an `OpenSSL.crypto.X509` object.
"""
try:
return util.ComparableX509(
crypto.load_certificate(crypto.FILETYPE_ASN1, decode_b64jose(b64der))
)
except crypto.Error as error:
return x509.load_der_x509_certificate(decode_b64jose(b64der))
except Exception as error:
raise errors.DeserializationError(error)


def encode_csr(csr: util.ComparableX509) -> str:
def encode_csr(csr: x509.CertificateSigningRequest) -> str:
"""Encode CSR as JOSE Base-64 DER.

:type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
:type csr: `cryptography.x509.CertificateSigningRequest`
:rtype: unicode

.. versionchanged:: 2.0.0
The `cert` parameter is now `cryptography.x509.CertificateSigningRequest`.
Previously this was an `josepy.util.ComparableX509` object, which wrapped
an `OpenSSL.crypto.X509Req` object.
"""
if isinstance(csr.wrapped, crypto.X509):
if isinstance(csr, x509.Certificate):
raise ValueError("Error input is actually a certificate.")

return encode_b64jose(crypto.dump_certificate_request(crypto.FILETYPE_ASN1, csr.wrapped))
return encode_b64jose(csr.public_bytes(Encoding.DER))


def decode_csr(b64der: str) -> util.ComparableX509:
def decode_csr(b64der: str) -> x509.CertificateSigningRequest:
"""Decode JOSE Base-64 DER-encoded CSR.

:param unicode b64der:
:rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
:rtype: `cryptography.x509.CertificateSigningRequest`

.. versionchanged:: 2.0.0
The returned object is now a `cryptography.x509.CertificateSigningRequest`.
Previously this was an `josepy.util.ComparableX509` object, which wrapped
an `OpenSSL.crypto.X509Req` object.
"""
try:
return util.ComparableX509(
crypto.load_certificate_request(crypto.FILETYPE_ASN1, decode_b64jose(b64der))
)
except crypto.Error as error:
return x509.load_der_x509_csr(decode_b64jose(b64der))
except Exception as error:
raise errors.DeserializationError(error)


Expand Down
32 changes: 18 additions & 14 deletions src/josepy/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
cast,
)

from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding

import josepy
from josepy import b64, errors, json_util, jwa
from josepy import jwk as jwk_mod
from josepy import util


class MediaType:
Expand Down Expand Up @@ -80,7 +80,7 @@ class Header(json_util.JSONObjectWithFields):
)
kid: Optional[str] = json_util.field("kid", omitempty=True)
x5u: Optional[bytes] = json_util.field("x5u", omitempty=True)
x5c: Tuple[util.ComparableX509, ...] = json_util.field("x5c", omitempty=True, default=())
x5c: Tuple[x509.Certificate, ...] = json_util.field("x5c", omitempty=True, default=())
x5t: Optional[bytes] = json_util.field("x5t", decoder=json_util.decode_b64jose, omitempty=True)
x5tS256: Optional[bytes] = json_util.field(
"x5t#S256", decoder=json_util.decode_b64jose, omitempty=True
Expand Down Expand Up @@ -138,21 +138,25 @@ def crit(unused_value: Any) -> Any:

@x5c.encoder # type: ignore
def x5c(value):
return [
base64.b64encode(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert.wrapped))
for cert in value
]
"""
.. versionchanged:: 2.0.0
The values are now `cryptography.x509.Certificate` objects.
Previously these were `josepy.util.ComparableX509` objects, which wrapped
`OpenSSL.crypto.X509` objects.
"""
return [base64.b64encode(cert.public_bytes(Encoding.DER)) for cert in value]

@x5c.decoder # type: ignore
def x5c(value):
"""
.. versionchanged:: 2.0.0
The values are now `cryptography.x509.Certificate` objects.
Previously these were `josepy.util.ComparableX509` objects, which wrapped
`OpenSSL.crypto.X509` objects.
"""
try:
return tuple(
util.ComparableX509(
crypto.load_certificate(crypto.FILETYPE_ASN1, base64.b64decode(cert))
)
for cert in value
)
except crypto.Error as error:
return tuple(x509.load_der_x509_certificate(base64.b64decode(cert)) for cert in value)
except Exception as error:
raise errors.DeserializationError(error)


Expand Down
56 changes: 0 additions & 56 deletions src/josepy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,69 +8,13 @@
from typing import Any, Callable, Iterator, List, Tuple, TypeVar, Union, cast

from cryptography.hazmat.primitives.asymmetric import ec, rsa
from OpenSSL import crypto


# Deprecated. Please use built-in decorators @classmethod and abc.abstractmethod together instead.
def abstractclassmethod(func: Callable) -> classmethod:
return classmethod(abc.abstractmethod(func))


class ComparableX509:
"""Wrapper for OpenSSL.crypto.X509** objects that supports __eq__.

:ivar wrapped: Wrapped certificate or certificate request.
:type wrapped: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.

.. deprecated:: 1.15.0
"""

def __init__(self, wrapped: Union[crypto.X509, crypto.X509Req]) -> None:
warnings.warn(
"The next major version of josepy will remove josepy.util.ComparableX509 and all "
"uses of it as part of removing our dependency on PyOpenSSL. This includes "
"modifying any functions with ComparableX509 parameters or return values. This "
"will be a breaking change. To avoid breakage, we recommend pinning josepy < 2.0.0 "
"until josepy 2.0.0 is out and you've had time to update your code.",
DeprecationWarning,
stacklevel=2,
)
assert isinstance(wrapped, crypto.X509) or isinstance(wrapped, crypto.X509Req)
self.wrapped = wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.wrapped, name)

def _dump(self, filetype: int = crypto.FILETYPE_ASN1) -> bytes:
"""Dumps the object into a buffer with the specified encoding.

:param int filetype: The desired encoding. Should be one of
`OpenSSL.crypto.FILETYPE_ASN1`,
`OpenSSL.crypto.FILETYPE_PEM`, or
`OpenSSL.crypto.FILETYPE_TEXT`.

:returns: Encoded X509 object.
:rtype: bytes

"""
if isinstance(self.wrapped, crypto.X509):
return crypto.dump_certificate(filetype, self.wrapped)

# assert in __init__ makes sure this is X509Req
return crypto.dump_certificate_request(filetype, self.wrapped)

def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self._dump() == other._dump()

def __hash__(self) -> int:
return hash((self.__class__, self._dump()))

def __repr__(self) -> str:
return "<{0}({1!r})>".format(self.__class__.__name__, self.wrapped)


class ComparableKey:
"""Comparable wrapper for ``cryptography`` keys.

Expand Down
Loading
Loading