# Post-quantum hybrid TLS image -- Chapter 10, Labs (e) and 5.
#
# Builds liboqs 0.15.0 + oqs-provider 0.11.0 against the OpenSSL 3
# that ships with ubuntu:24.04, then generates a self-signed cert and
# starts an s_server that offers the hybrid group X25519MLKEM768 (0x11EC).
#
# Pinned releases (access date 11 May 2026 -- both are public, stable tags):
#   liboqs   0.15.0  https://github.com/open-quantum-safe/liboqs/releases/tag/0.15.0
#   oqs-provider 0.11.0  https://github.com/open-quantum-safe/oqs-provider/releases/tag/0.11.0

FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive
ENV LIBOQS_VERSION=0.15.0
ENV OQSPROV_VERSION=0.11.0

# Build dependencies
RUN apt-get update -qq && apt-get install -y -qq \
    build-essential \
    cmake \
    ninja-build \
    git \
    libssl-dev \
    openssl \
    python3 \
    pkg-config \
    curl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build

# --- Build liboqs ---
RUN git clone --branch ${LIBOQS_VERSION} --depth 1 \
    https://github.com/open-quantum-safe/liboqs.git && \
    cmake -S liboqs -B liboqs/build \
        -G Ninja \
        -DBUILD_SHARED_LIBS=ON \
        -DOQS_BUILD_ONLY_LIB=ON \
        -DOQS_USE_OPENSSL=ON \
        -DCMAKE_INSTALL_PREFIX=/usr/local && \
    cmake --build liboqs/build -j"$(nproc)" && \
    cmake --install liboqs/build

# --- Build oqs-provider ---
RUN git clone --branch ${OQSPROV_VERSION} --depth 1 \
    https://github.com/open-quantum-safe/oqs-provider.git && \
    cmake -S oqs-provider -B oqs-provider/build \
        -G Ninja \
        -Dliboqs_DIR=/usr/local/lib/cmake/liboqs \
        -DCMAKE_INSTALL_PREFIX=/usr/local && \
    cmake --build oqs-provider/build -j"$(nproc)" && \
    cmake --install oqs-provider/build

# Update shared library cache
RUN ldconfig

# Configure OpenSSL to load oqs-provider
RUN mkdir -p /usr/local/oqs && \
    OPENSSL_CNF=$(openssl version -d | awk '{print $2}' | tr -d '"')/openssl.cnf && \
    cp "$OPENSSL_CNF" /usr/local/oqs/openssl.cnf && \
    sed -i 's/\[openssl_init\]/[openssl_init]\nproviders = provider_sect\n\n[provider_sect]\ndefault = default_sect\noqsprovider = oqsprovider_sect\n\n[default_sect]\nactivate = 1\n\n[oqsprovider_sect]\nmodule = \/usr\/local\/lib\/ossl-modules\/oqsprovider.so\nactivate = 1\n/' \
    /usr/local/oqs/openssl.cnf || true

ENV OPENSSL_CONF=/usr/local/oqs/openssl.cnf

# Generate a self-signed certificate for the s_server
RUN openssl req -x509 -newkey rsa:2048 -keyout /usr/local/oqs/server.key \
    -out /usr/local/oqs/server.crt -days 3650 -nodes \
    -subj "/CN=pq-lab-server"

WORKDIR /usr/local/oqs

# Default: start an s_server offering X25519MLKEM768 on port 4433
# Override CMD to run s_client or other commands
EXPOSE 4433
CMD ["openssl", "s_server", \
     "-groups", "X25519MLKEM768", \
     "-cert", "/usr/local/oqs/server.crt", \
     "-key", "/usr/local/oqs/server.key", \
     "-www", \
     "-accept", "4433"]
