import dataclasses from datetime import UTC, datetime, timedelta from os import path from pathlib import Path from secrets import token_urlsafe from typing import cast from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric.types import ( CertificateIssuerPrivateKeyTypes, ) from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel from app.types import CSR, CertificateChainResponse CONFIG_DIR = Path("config") if not path.exists(CONFIG_DIR): raise RuntimeError( f"Configuration directory '{CONFIG_DIR}' does not exist. Please create it and add the necessary files." ) CA_PRIVATE_KEY = cast( CertificateIssuerPrivateKeyTypes, serialization.load_pem_private_key( (CONFIG_DIR / "ca.key").read_bytes(), password=None ), ) CA_CERTIFICATE_CHAIN = x509.load_pem_x509_certificates( (CONFIG_DIR / "ca.crt").read_bytes() ) CA_CERTIFICATE = CA_CERTIFICATE_CHAIN[0] app = FastAPI() class OrderRequest(BaseModel): domain: str port: int = 80 class OrderResponse(BaseModel): order_id: str token: str class FinalizeRequest(BaseModel): csr: CSR @dataclasses.dataclass class Order: domain: str port: int authorization: str orders = dict[str, Order]() @app.post("/acme/new-order", status_code=status.HTTP_201_CREATED) async def new_order(req: OrderRequest) -> OrderResponse: order_id = token_urlsafe(8) token = token_urlsafe(32) order = Order(domain=req.domain, port=req.port, authorization=token) orders[order_id] = order return OrderResponse(order_id=order_id, token=token) @app.post("/acme/orders/{order_id}/finalize", response_class=CertificateChainResponse) async def finalize_order(order_id: str, req: FinalizeRequest): if order_id not in orders: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Order not found" ) order = orders[order_id] # try: # well_known_url = f"http://{order.domain}:{order.port}/.well-known/acme-challenge/{order.authorization}" # async with httpx.AsyncClient() as client: # resp = await client.get(well_known_url, timeout=5) # if resp.status_code != 200 or resp.text.strip() != order.authorization: # raise HTTPException( # status_code=status.HTTP_400_BAD_REQUEST, # detail="Invalid challenge", # ) # except httpx.RequestError: # raise HTTPException( # status_code=status.HTTP_400_BAD_REQUEST, # detail="Challenge request failed", # ) cert_builder = ( x509.CertificateBuilder() .subject_name(req.csr.subject) .issuer_name(CA_CERTIFICATE.subject) .public_key(req.csr.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.now(UTC)) .not_valid_after(datetime.now(UTC) + timedelta(days=30)) .add_extension( x509.SubjectAlternativeName([x509.DNSName(order.domain)]), critical=False ) ) signed_cert = cert_builder.sign( private_key=CA_PRIVATE_KEY, algorithm=hashes.SHA256() ) return CertificateChainResponse( [signed_cert] + CA_CERTIFICATE_CHAIN, filename=f"{order.domain}.crt" )