Skip to content

Commit

Permalink
Allow Connection.get_certificate to return a cryptography certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Aug 9, 2024
1 parent b0cb4b4 commit 529aee4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/OpenSSL/SSL.py
Original file line number Diff line number Diff line change
Expand Up @@ -2696,7 +2696,27 @@ def sock_shutdown(self, *args: Any, **kwargs: Any) -> None:
"""
return self._socket.shutdown(*args, **kwargs) # type: ignore[return-value, union-attr]

def get_certificate(self) -> X509 | None:
@typing.overload
def get_certificate(
self, *, as_cryptography: typing.Literal[True]
) -> x509.Certificate | None:
pass

@typing.overload
def get_certificate(
self, *, as_cryptography: typing.Literal[False] = False
) -> X509 | None:
pass

@typing.overload
def get_certificate(
self, *, as_cryptography: bool = False
) -> X509 | x509.Certificate | None:
pass

def get_certificate(
self, *, as_cryptography: bool = False
) -> X509 | x509.Certificate | None:
"""
Retrieve the local certificate (if any)
Expand All @@ -2705,7 +2725,10 @@ def get_certificate(self) -> X509 | None:
cert = _lib.SSL_get_certificate(self._ssl)
if cert != _ffi.NULL:
_lib.X509_up_ref(cert)
return X509._from_raw_x509_ptr(cert)
pycert = X509._from_raw_x509_ptr(cert)
if as_cryptography:
return pycert.to_cryptography()
return pycert
return None

def get_peer_certificate(self) -> X509 | None:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2556,6 +2556,13 @@ def test_get_certificate(self):
assert cert is not None
assert "Server Certificate" == cert.get_subject().CN

cryptography_cert = client.get_certificate(as_cryptography=True)
assert cryptography_cert is not None
assert (
cryptography_cert.subject.rfc4514_string()
== "CN=Server Certificate"
)

def test_get_certificate_none(self):
"""
`Connection.get_certificate` returns the local certificate.
Expand Down

0 comments on commit 529aee4

Please sign in to comment.