Skip to content
Merged
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
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ dev = [
"opentelemetry-instrumentation-grpc~=0.61b0",
"opentelemetry-exporter-zipkin~=1.11.1",
"httpx~=0.28.1",
"pyOpenSSL~=26.0.0",
"cryptography>=42.0.0",
"cryptography>=49.0.0",
"redis>=7.4.0",
"Flask~=3.1.3",
"pytest~=9.0.2",
Expand Down
56 changes: 37 additions & 19 deletions tests/clients/certs.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,56 @@
import os
import ssl
from datetime import datetime, timedelta, timezone

import grpc
from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID


class Certs:
server_type = 'grpc'

@classmethod
def create_certificates(cls):
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)

# create a self-signed cert
cert = crypto.X509()
cert.get_subject().organizationName = 'Dapr'
cert.get_subject().commonName = 'localhost'
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
key = rsa.generate_private_key(public_exponent=65537, key_size=4096)

subject = x509.Name(
[
x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Dapr'),
x509.NameAttribute(NameOID.COMMON_NAME, 'localhost'),
]
)
now = datetime.now(timezone.utc)
cert_builder = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now + timedelta(days=1))
)

if cls.server_type == 'http':
cert.add_extensions([crypto.X509Extension(b'subjectAltName', False, b'DNS:localhost')])
localhost_san = x509.SubjectAlternativeName([x509.DNSName('localhost')])
cert_builder = cert_builder.add_extension(localhost_san, critical=False)

cert.sign(k, 'sha512')
cert = cert_builder.sign(key, hashes.SHA512())

with open(cls.get_cert_path(), 'wt') as f_cert:
f_cert.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
key_pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)

with open(cls.get_pk_path(), 'wt') as f_key:
f_key.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode('utf-8'))
with open(cls.get_cert_path(), 'wb') as f_cert:
f_cert.write(cert_pem)

with open(cls.get_pk_path(), 'wb') as f_key:
f_key.write(key_pem)

@classmethod
def get_pk_path(cls):
Expand Down
Loading
Loading