40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
from typing import Annotated
|
|
|
|
from cryptography import x509
|
|
from cryptography.hazmat.primitives import serialization
|
|
from fastapi.responses import Response
|
|
from pydantic import PlainValidator
|
|
|
|
|
|
def parse_csr(csr: str) -> x509.CertificateSigningRequest:
|
|
try:
|
|
return x509.load_pem_x509_csr(csr.encode("utf-8"))
|
|
except (UnicodeEncodeError, ValueError) as e:
|
|
raise ValueError(f"Invalid CSR: {e}")
|
|
|
|
|
|
CSR = Annotated[x509.CertificateSigningRequest, PlainValidator(parse_csr)]
|
|
|
|
|
|
class CertificateChainResponse(Response):
|
|
media_type = "application/pem-certificate-chain"
|
|
|
|
def __init__(
|
|
self,
|
|
content: list[x509.Certificate],
|
|
status_code: int = 200,
|
|
filename: str = "cert.pem",
|
|
):
|
|
cert_pem = "".join(
|
|
[
|
|
cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
|
|
for cert in content
|
|
]
|
|
)
|
|
super().__init__(
|
|
content=cert_pem,
|
|
status_code=status_code,
|
|
headers={"Content-Disposition": f'inline; filename="{filename}"'},
|
|
media_type=self.media_type,
|
|
)
|