瀏覽代碼

feat: terminate TLS in-process, one certificate per hostname via SNI SV-132

Stage 2 of #132. `tls.cert_dir` in the boot config makes this process serve
HTTPS and choose a certificate per connection from the SNI hostname. Off by
default, so every deployment today - behind nginx, the devstack, the test
fixture - is byte-for-byte unaffected.

VERIFIED IN THE PINNED LIBRARY BEFORE DESIGNING ANYTHING: `SSLServer(const
tls::ContextSetupCallback&)` exists at httplib.h:3350, and `ctx_t` really is an
`SSL_CTX*` - but only under the OpenSSL backend. The header also ships an Mbed
TLS backend where it is a different type entirely, so the cast would compile
and corrupt memory. An `#error` guard on CPPHTTPLIB_OPENSSL_SUPPORT turns a
backend switch into a BUILD failure.

Certificate LOADING goes through httplib's own `tls::` abstraction; only the
SNI hook is raw OpenSSL, because selection has no API. One SSL_CTX per
certificate, because OpenSSL cannot hold two certificates for different NAMES
in one context - its multi-certificate support is for different key types on
the same name - so the callback swaps the whole context.

NO DEFAULT CERTIFICATE, and no fallback anywhere. A hostname with no
certificate is a refused handshake naming the host in our log; so is a client
sending no SNI, which is what addressing the service by IP does. Serving an
arbitrary certificate instead would turn a missing-certificate mistake into a
name-mismatch error on an UNRELATED tenant's hostname, which is strictly harder
to diagnose. main() refuses to start if TLS was configured and could not be set
up, rather than serving plain HTTP on a port callers reach over https.

TWO BLIND SPOTS IN MY OWN TESTS, BOTH FOUND BY FALSIFICATION AND BOTH FIXED.
This is the part worth keeping:

- Removing the exact-beats-wildcard pass left all 16 unit tests GREEN. The
  arithmetic says why: a wildcard covering host H is `*.<suffix>` where
  H = `<label>.<suffix>`, so it is SHORTER than H whenever the label exceeds
  one character - and `nt.kb.example.com` made a plain longest-name-wins rule
  pick the exact match by accident. Only a ONE-character label ties the
  lengths, which is the single case that discriminates. A new test uses
  `a.kb.example.com` with the wildcard listed first, and asserts the tie.
- Adding a default-certificate fallback to the SNI hook left all 6 handshake
  tests GREEN. They pin a CA and expect failure, and a wrong certificate fails
  the pin just as a refusal does - safe either way, operationally opposite. The
  discriminator is a handshake with verification OFF, where only a genuine
  refusal fails. Paired, so it cannot pass by everything failing.

Four more falsifications each turn exactly one test red: a wildcard spanning
several labels, a no-match fallback in selectCert, the hook ignoring SNI
entirely, and tolerating a missing SNI.

The handshake tests are real TLS on a loopback socket with openssl-minted
certificates (skipped cleanly without the openssl CLI, like the integration
tests without a database). They confirm what no unit test can: that the hook is
reached, that SSL_set_SSL_CTX actually changes the certificate sent, and that
the one-label wildcard rule is the rule in force on the wire rather than only
in our arithmetic.

The filename is the source of truth rather than the certificate's SANs - a
stated trade: auditable with `ls`, no X509 parsing in our process, matches what
ACME clients write, and a mis-named file fails LOUDLY at the client as a name
mismatch. SAN verification at load time would catch it earlier and is deferred,
not overlooked.

A reload swaps a shared_ptr snapshot and the handshake holds the one it was
handed, so renewal cannot free a context mid-handshake. A certificate that
fails to load is skipped and NAMED: one unreadable file, a renewal caught
mid-write, must not take every other hostname offline.

17 pure + 8 handshake tests; 1485/1485 serial, zero pending build steps.
fszontagh 6 天之前
父節點
當前提交
ff3a129c52
共有 14 個文件被更改,包括 1018 次插入 和 18 次删除
  1. 27 0
      api/llms.txt
  2. 2 0
      src/CMakeLists.txt
  3. 133 0
      src/cert_store.cpp
  4. 81 0
      src/cert_store.hpp
  5. 5 0
      src/config.cpp
  6. 14 0
      src/config.hpp
  7. 15 1
      src/main.cpp
  8. 125 14
      src/server.cpp
  9. 18 3
      src/server.hpp
  10. 120 0
      src/tls_certs.cpp
  11. 84 0
      src/tls_certs.hpp
  12. 12 0
      tests/CMakeLists.txt
  13. 179 0
      tests/test_tls_certs.cpp
  14. 203 0
      tests/test_tls_sni.cpp

+ 27 - 0
api/llms.txt

@@ -8,6 +8,33 @@
 > Machine-readable spec: `/openapi.json` (OpenAPI 3.1).
 
 
+## TLS: vectorapi can terminate it, with a certificate per hostname
+
+Off by default. `tls.cert_dir` (or `tls_cert_dir`) in the boot config makes this
+process serve HTTPS and select a certificate per connection from the SNI
+hostname. A BOOT setting, not hot-reloading: it decides which server class is
+constructed. The certificates inside the directory ARE reloadable.
+
+We do NOT speak ACME. An external client (lego, certbot, acme.sh) obtains and
+renews with DNS-01 and writes into that directory. File naming is the mapping:
+
+    nt.kb.example.com.crt  +  nt.kb.example.com.key
+    _.kb.example.com.crt   +  _.kb.example.com.key     (a wildcard)
+
+An exact certificate beats a wildcard; among wildcards the longest wins. A
+wildcard covers exactly ONE label, so `*.kb.example.com` serves
+`nt.kb.example.com` and neither `a.b.kb.example.com` nor `kb.example.com`.
+
+**A hostname with no certificate gets a REFUSED HANDSHAKE, never a different
+hostname's certificate**, and so does a client that sends no SNI at all (which
+is what addressing the service by IP does). The refusal is logged with the
+hostname; the client sees only a TLS alert. There is no default certificate, on
+purpose: serving one would turn a missing-certificate mistake into a
+name-mismatch error on an unrelated tenant's hostname.
+
+If TLS is configured and cannot be set up, the server REFUSES TO START rather
+than serving plain HTTP on a port callers reach over https.
+
 ## Hostnames: the short path form
 
 Every project-scoped route accepts TWO shapes:

+ 2 - 0
src/CMakeLists.txt

@@ -8,6 +8,8 @@ add_library(vectorapi_core STATIC
     filters.cpp
     client_ip.cpp
     hostnames.cpp
+    cert_store.cpp
+    tls_certs.cpp
     access_log.cpp
     request_trace.cpp
     vector_search.cpp

+ 133 - 0
src/cert_store.cpp

@@ -0,0 +1,133 @@
+#include "cert_store.hpp"
+
+#include <httplib.h>
+#include <spdlog/spdlog.h>
+
+#include <algorithm>
+#include <filesystem>
+
+// The SSL_CTX cast below is valid ONLY under the OpenSSL backend: cpp-httplib
+// also ships an Mbed TLS backend where `tls::ctx_t` is a pointer to its own
+// context struct, and casting that to SSL_CTX* would compile and then corrupt
+// memory. Our build forces OpenSSL (HTTPLIB_REQUIRE_OPENSSL ON in
+// cmake/Dependencies.cmake, CPPHTTPLIB_OPENSSL_SUPPORT in src/CMakeLists.txt),
+// so this guard turns a backend switch into a BUILD failure instead of a
+// runtime one.
+#ifndef CPPHTTPLIB_OPENSSL_SUPPORT
+#error "cert_store.cpp casts tls::ctx_t to SSL_CTX*, which is only true under the OpenSSL backend"
+#endif
+
+namespace svapi {
+
+CertSnapshot::~CertSnapshot() {
+    for (void* c : contexts)
+        if (c) httplib::tls::free_context(static_cast<httplib::tls::ctx_t>(c));
+}
+
+CertStore& certStore() {
+    static CertStore s;
+    return s;
+}
+
+std::shared_ptr<const CertSnapshot> CertStore::snapshot() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return snap_;
+}
+
+std::string CertStore::dir() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return dir_;
+}
+
+std::size_t CertStore::reload(const std::string& dir) {
+    auto next = std::make_shared<CertSnapshot>();
+    std::error_code ec;
+    std::vector<std::string> skipped;
+
+    std::filesystem::directory_iterator it(dir, ec), end;
+    if (ec) {
+        spdlog::error("TLS certificate directory '{}' cannot be read: {} - keeping the "
+                      "{} certificate(s) already loaded",
+                      dir, ec.message(), snapshot()->files.size());
+        return snapshot()->files.size();
+    }
+
+    for (; it != end; it.increment(ec)) {
+        if (ec) break;
+        const std::string path = it->path().string();
+        const auto name = certNameFromFilename(it->path().filename().string());
+        if (!name) continue;   // a key, or not a certificate; silent by design
+
+        // The key sits beside the certificate under the same stem. Both
+        // spellings are accepted because lego writes `.key` and some setups
+        // keep a combined `.pem`: a certificate file that already contains the
+        // key is handed to OpenSSL as both halves.
+        std::filesystem::path keyPath = it->path();
+        keyPath.replace_extension(".key");
+        std::string key = std::filesystem::exists(keyPath) ? keyPath.string() : path;
+
+        httplib::tls::ctx_t ctx = httplib::tls::create_server_context();
+        if (!ctx) { skipped.push_back(*name + " (no TLS context)"); continue; }
+        if (!httplib::tls::set_server_cert_file(ctx, path.c_str(), key.c_str(), nullptr)) {
+            // SKIPPED AND NAMED, never fatal: one unreadable file - a renewal
+            // caught mid-write, a wrong mode - must not take every other
+            // hostname offline with it.
+            httplib::tls::free_context(ctx);
+            skipped.push_back(*name + " (" + path + ")");
+            continue;
+        }
+        if (!installSniHook(ctx)) {
+            // Each per-certificate context needs the hook too: after
+            // SSL_set_SSL_CTX a renegotiation would re-enter the callback on
+            // the NEW context, and a context without the hook would then serve
+            // whatever it holds for any name.
+            httplib::tls::free_context(ctx);
+            skipped.push_back(*name + " (SNI hook)");
+            continue;
+        }
+        next->files.push_back(CertFile{*name, path, std::move(key)});
+        next->contexts.push_back(static_cast<void*>(ctx));
+    }
+
+    // A STABLE ORDER, so two deployments with the same files make the same
+    // choices. Selection does not depend on order - the exact-first pass and
+    // the longest-wildcard rule settle it - but a log an operator compares
+    // between hosts should not shuffle.
+    std::vector<std::size_t> idx(next->files.size());
+    for (std::size_t i = 0; i < idx.size(); ++i) idx[i] = i;
+    std::sort(idx.begin(), idx.end(),
+              [&](std::size_t a, std::size_t b) { return next->files[a].name < next->files[b].name; });
+    {
+        std::vector<CertFile> f;
+        std::vector<void*> c;
+        f.reserve(idx.size());
+        c.reserve(idx.size());
+        for (const std::size_t i : idx) { f.push_back(next->files[i]); c.push_back(next->contexts[i]); }
+        next->files = std::move(f);
+        next->contexts = std::move(c);
+    }
+
+    for (const std::string& s : skipped)
+        spdlog::error("TLS certificate for '{}' could NOT be loaded and that hostname will "
+                      "refuse every handshake until it is fixed", s);
+
+    std::vector<std::string> names;
+    names.reserve(next->files.size());
+    for (const CertFile& f : next->files) names.push_back(f.name);
+    spdlog::info("TLS: {} certificate(s) loaded from {}{}", names.size(), dir,
+                 names.empty() ? "" : " for " + [&] {
+                     std::string j;
+                     for (const std::string& n : names) j += (j.empty() ? "" : ", ") + n;
+                     return j;
+                 }());
+
+    const std::size_t count = next->files.size();
+    {
+        std::lock_guard<std::mutex> lk(m_);
+        dir_ = dir;
+        snap_ = std::move(next);
+    }
+    return count;
+}
+
+} // namespace svapi

+ 81 - 0
src/cert_store.hpp

@@ -0,0 +1,81 @@
+#pragma once
+
+#include "tls_certs.hpp"
+
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+/// Certificates loaded from a directory, one TLS context per certificate, and
+/// the SNI hook that picks between them.
+///
+/// ONE `SSL_CTX` PER CERTIFICATE, because OpenSSL cannot hold two certificates
+/// for different NAMES in one context - the multiple-certificate support it has
+/// is for different key TYPES (RSA beside ECDSA) on the same name. So the SNI
+/// callback swaps the whole context for the connection, which is the standard
+/// shape for this and the reason a context per certificate is not wasteful
+/// bookkeeping but the actual mechanism.
+///
+/// THE SNAPSHOT IS SWAPPED, NEVER MUTATED, exactly as SettingsStore and
+/// KeyStore do it. Renewal every ~60 days across several hostnames makes reload
+/// routine rather than exceptional, so it has to be boring: a handshake in
+/// flight keeps the snapshot it was handed, and the old contexts stay alive
+/// until the last connection referencing them has gone.
+namespace svapi {
+
+/// Everything a handshake needs, immutable once built.
+struct CertSnapshot {
+    /// Parallel to `contexts`: entry i is served by context i.
+    std::vector<CertFile> files;
+    /// `tls::ctx_t` values, owned here and freed when this snapshot dies.
+    /// `void*` rather than the httplib type so this header pulls in neither
+    /// httplib nor OpenSSL - the server is the only place that needs them.
+    std::vector<void*> contexts;
+
+    CertSnapshot() = default;
+    CertSnapshot(const CertSnapshot&) = delete;
+    CertSnapshot& operator=(const CertSnapshot&) = delete;
+    ~CertSnapshot();
+};
+
+class CertStore {
+public:
+    /// Scan `dir` and replace the snapshot. Returns how many certificates are
+    /// now loaded.
+    ///
+    /// A certificate that fails to load is SKIPPED AND NAMED, never fatal: one
+    /// unreadable file - a renewal caught mid-write, a wrong mode - must not
+    /// take every other hostname offline with it. The cost is that a deployment
+    /// can come up serving fewer names than the operator intended, which is why
+    /// the count and every skip are logged rather than counted silently.
+    std::size_t reload(const std::string& dir);
+
+    std::shared_ptr<const CertSnapshot> snapshot() const;
+
+    /// The directory last scanned, for the reload timer and for diagnostics.
+    std::string dir() const;
+
+private:
+    mutable std::mutex m_;
+    std::shared_ptr<const CertSnapshot> snap_ = std::make_shared<const CertSnapshot>();
+    std::string dir_;
+};
+
+/// The process-wide store. A singleton for the same reason the embedding cache
+/// is one: the SNI callback is a C function pointer reached from inside OpenSSL
+/// with no path for passing a `this`, and threading one through would mean
+/// handing OpenSSL a raw pointer whose lifetime nothing guarantees.
+CertStore& certStore();
+
+/// Install the SNI hook on a server context. Declared here and defined in the
+/// server translation unit, which is the only one that may include OpenSSL.
+///
+/// Returns false if the hook could not be installed, which must FAIL THE
+/// SERVER rather than be tolerated: without it every connection is served
+/// whatever certificate the base context holds, so a deployment would come up
+/// looking healthy and answer every tenant's hostname with the wrong
+/// certificate.
+bool installSniHook(void* ctx);
+
+} // namespace svapi

+ 5 - 0
src/config.cpp

@@ -11,6 +11,11 @@ Config Config::fromJson(const nlohmann::json& j) {
         const auto& h = j["http"];
         c.httpBind = h.value("bind_address", c.httpBind);
         c.httpPort = h.value("port", c.httpPort);
+
+        if (j.contains("tls") && j["tls"].is_object())
+            c.tlsCertDir = j["tls"].value("cert_dir", c.tlsCertDir);
+        // Also accepted at the top level, so a minimal config needs no nesting.
+        c.tlsCertDir = j.value("tls_cert_dir", c.tlsCertDir);
         c.httpThreadPoolSize = h.value("thread_pool_size", c.httpThreadPoolSize);
     }
     if (j.contains("access_log") && j["access_log"].is_object())

+ 14 - 0
src/config.hpp

@@ -10,6 +10,20 @@ struct Config {
     std::string logLevel  = "info";
     std::string httpBind  = "0.0.0.0";
     uint16_t    httpPort  = 8080;
+
+    /// Directory holding TLS certificates, one pair per hostname. EMPTY MEANS
+    /// PLAIN HTTP, which is the default and every deployment behind a proxy.
+    ///
+    /// A BOOT setting rather than a hot-reloading one, unlike almost everything
+    /// else here: whether this process terminates TLS decides which concrete
+    /// server class is constructed, so changing it live would mean dropping
+    /// every connection and rebuilding the listener. The certificates INSIDE
+    /// the directory are reloadable; the decision to serve TLS at all is not.
+    ///
+    /// Files are named for the host they serve - `nt.kb.example.com.crt` with
+    /// `nt.kb.example.com.key` beside it, or `_.kb.example.com.crt` for a
+    /// wildcard. We do not speak ACME: an external client writes here.
+    std::string tlsCertDir;
     /// Request threads. 0 means "cpp-httplib's own default", which is
     /// `max(8, hardware_concurrency - 1)`.
     ///

+ 15 - 1
src/main.cpp

@@ -166,7 +166,21 @@ int main(int argc, char** argv) {
     svapi::ServerDeps deps{db,        settings,     keys,          registry,
                            sessions,  functions,    functionRuns,  runners.get(),
                            cfg.webuiDir, shareDir, &jobQueue};
-    svapi::ApiServer server(std::move(deps));
+    svapi::ApiServer server(std::move(deps), cfg.tlsCertDir);
+    // REFUSE TO START if TLS was asked for and could not be set up. A server
+    // that quietly fell back to plain HTTP on the port a customer reaches over
+    // https would come up looking healthy, answer every request, and be
+    // reported by nothing - the silent-wrong-answer shape this codebase keeps
+    // paying for. The same spirit as the runner refusing to start with no token
+    // on a non-loopback bind.
+    if (!cfg.tlsCertDir.empty() && !server.valid()) {
+        spdlog::critical("TLS was configured (cert_dir={}) but the TLS server could not be "
+                         "created - refusing to start rather than serving plain HTTP on a port "
+                         "callers will reach over https", cfg.tlsCertDir);
+        return 1;
+    }
+    if (!cfg.tlsCertDir.empty())
+        spdlog::info("serving HTTPS with per-hostname certificates from {}", cfg.tlsCertDir);
     if (runners && cfg.schedulerEnabled) {
         svapi::FunctionSchedulerOptions so;
         so.tickIntervalSec   = cfg.schedulerTickSec;

+ 125 - 14
src/server.cpp

@@ -1,5 +1,8 @@
 #include "scope_refusal.hpp"
 #include "server.hpp"
+#include <openssl/tls1.h>
+#include <openssl/ssl.h>
+#include "cert_store.hpp"
 #include "captcha.hpp"
 #include "db_errors.hpp"
 #include "errors.hpp"
@@ -15,6 +18,86 @@
 
 namespace svapi {
 
+// --- SNI: choosing the certificate for the name the client asked for --------
+//
+// THE ONLY RAW OPENSSL IN THIS SERVICE. Certificate LOADING goes through
+// cpp-httplib's own tls:: abstraction (cert_store.cpp), because that part has
+// an API; selection does not, so the hook is ours.
+namespace {
+
+/// Called by OpenSSL during the handshake, before any certificate is sent.
+int sniCallback(SSL* ssl, int* al, void*) {
+    if (!ssl) return SSL_TLSEXT_ERR_ALERT_FATAL;
+    const char* requested = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
+
+    // NO SNI AT ALL is refused rather than served a default. A client that
+    // sends no name is either very old or addressing us by IP, and in both
+    // cases there is no right certificate to pick - serving an arbitrary one
+    // produces a name-mismatch error against a RANDOM tenant's hostname, which
+    // is strictly harder to diagnose than a refused handshake. The direct-
+    // address recovery path is for HTTP-level access, not a reason to hand out
+    // somebody's certificate.
+    if (!requested || !*requested) {
+        spdlog::warn("TLS handshake refused: the client sent no SNI hostname, so there is no "
+                     "certificate to choose - address this service by name");
+        if (al) *al = SSL_AD_UNRECOGNIZED_NAME;
+        return SSL_TLSEXT_ERR_ALERT_FATAL;
+    }
+
+    // The snapshot is taken ONCE and held for the rest of this handshake, so a
+    // reload landing mid-handshake cannot free the context under us: the
+    // shared_ptr keeps the old snapshot, and with it every SSL_CTX in it, alive
+    // until this function returns.
+    const auto snap = certStore().snapshot();
+    const CertFile* chosen = selectCert(snap->files, requested);
+    if (!chosen) {
+        // Named in the log, because this is the one failure an operator has to
+        // act on and the client sees only a handshake alert.
+        spdlog::warn("TLS handshake refused for '{}': no certificate covers that hostname "
+                     "({} loaded). Put <host>.crt and <host>.key in the certificate directory, "
+                     "or a wildcard as _.<parent>.crt",
+                     requested, snap->files.size());
+        if (al) *al = SSL_AD_UNRECOGNIZED_NAME;
+        return SSL_TLSEXT_ERR_ALERT_FATAL;
+    }
+
+    // Find the context beside the chosen file. `files` and `contexts` are
+    // parallel and built together, so this cannot miss - but it is written as a
+    // search rather than pointer arithmetic so that a later change to either
+    // vector fails safe instead of indexing past the end.
+    for (std::size_t i = 0; i < snap->files.size(); ++i) {
+        if (&snap->files[i] != chosen) continue;
+        if (SSL_set_SSL_CTX(ssl, static_cast<SSL_CTX*>(snap->contexts[i])) == nullptr) {
+            spdlog::error("TLS: could not install the certificate for '{}'", requested);
+            if (al) *al = SSL_AD_INTERNAL_ERROR;
+            return SSL_TLSEXT_ERR_ALERT_FATAL;
+        }
+        // SSL_set_SSL_CTX REPLACES THE CERTIFICATE AND KEY AND NOTHING ELSE -
+        // the options, the minimum protocol version and the verify mode stay
+        // those of the context the connection was accepted on. That is the
+        // documented OpenSSL behaviour and the usual trap here: a per-
+        // certificate context configured more strictly than the base one would
+        // have its strictness silently ignored. We therefore set the same
+        // options on every context (create_server_context does it) rather than
+        // relying on the swap to carry them.
+        return SSL_TLSEXT_ERR_OK;
+    }
+    if (al) *al = SSL_AD_INTERNAL_ERROR;
+    return SSL_TLSEXT_ERR_ALERT_FATAL;
+}
+
+} // namespace
+
+bool installSniHook(void* ctx) {
+    if (!ctx) return false;
+    auto* c = static_cast<SSL_CTX*>(ctx);
+    // Returns 1 on success. Checked, because without the hook every connection
+    // gets whatever certificate the base context holds and the deployment comes
+    // up looking healthy while answering every hostname wrongly.
+    if (SSL_CTX_set_tlsext_servername_callback(c, sniCallback) != 1) return false;
+    return true;
+}
+
 std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group) {
     const auto reg = d.settings.hostRegistry();
     const bool gatingOn = reg && reg->gating();
@@ -34,7 +117,35 @@ std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group)
     return r.project;
 }
 
-ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
+ApiServer::ApiServer(ServerDeps deps, std::string tlsCertDir) : d_(std::move(deps)) {
+    if (tlsCertDir.empty()) {
+        svr_ = std::make_unique<httplib::Server>();
+        return;
+    }
+
+    // Load BEFORE the server exists, so a deployment with an unreadable
+    // directory or no usable certificate fails at startup rather than on the
+    // first customer connection. The count is logged either way.
+    const std::size_t loaded = certStore().reload(tlsCertDir);
+    if (loaded == 0)
+        spdlog::error("TLS was requested but NO usable certificate was found in '{}' - every "
+                      "handshake will be refused", tlsCertDir);
+
+    // The base context carries the SNI hook; the callback swaps in a
+    // per-certificate context for the name the client asked for. The base
+    // context deliberately holds NO certificate of its own, which is what makes
+    // "no certificate for this name" a refused handshake rather than a wrong
+    // certificate served confidently.
+    svr_ = std::make_unique<httplib::SSLServer>(
+        [](httplib::tls::ctx_t ctx) { return installSniHook(static_cast<void*>(ctx)); });
+    tls_ = true;
+}
+
+bool ApiServer::valid() const {
+    // `SSLServer::is_valid()` is false when the context could not be built, so
+    // this covers both "the hook would not install" and "OpenSSL refused".
+    return svr_ && svr_->is_valid();
+}
 
 static bool keyExpired(const ApiKey& k) {
     if (!k.scope) return false;
@@ -136,7 +247,7 @@ void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& r
 }
 
 void ApiServer::registerRoutes() {
-    svr_.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
+    svr_->set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
         // RECORD THE SLUG. We build a structured reason for every refusal and
         // used to keep NONE of it for a 4xx, so a refused request left only its
         // status code behind - and a status code is shared by a dozen causes.
@@ -209,7 +320,7 @@ void ApiServer::registerRoutes() {
     // route (e.g. /login, /settings) reaches the server as a 404 (no such static file).
     // Serve index.html so React Router can handle it. Excludes API/meta routes and asset
     // requests (paths with a file extension), which should keep their real 404.
-    svr_.set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
+    svr_->set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
         if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
             && req.path.rfind("/api/", 0) != 0
             && req.path.rfind("/ui/", 0) != 0
@@ -232,7 +343,7 @@ void ApiServer::registerRoutes() {
     });
 
     // Authenticate /api/* (authorization is per-handler).
-    svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
+    svr_->set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
         // START of the request: zero the clock and forget the previous
         // request's slug. See access_log.hpp on why that ordering matters.
         beginRequestTrace();
@@ -288,7 +399,7 @@ void ApiServer::registerRoutes() {
     // `code=unauthorized` rather than on every 401 the service emits, and the
     // address it acts on is one we resolved under the trusted-proxy rule rather
     // than whatever a header claimed.
-    svr_.set_logger([this](const httplib::Request& req, const httplib::Response& res) {
+    svr_->set_logger([this](const httplib::Request& req, const httplib::Response& res) {
         if (!accessLog().enabled()) return;
         auto snap = d_.settings.snapshot();
         AccessLogEntry e;
@@ -305,7 +416,7 @@ void ApiServer::registerRoutes() {
         accessLog().write(e);
     });
 
-    svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
+    svr_->set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
         auto snap = d_.settings.snapshot();
         std::string responseOrigin;
         if (!snap->corsOrigins.empty() && snap->corsOrigins[0] == "*") {
@@ -320,7 +431,7 @@ void ApiServer::registerRoutes() {
         res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Captcha-Token, Cache-Control");
         res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
     });
-    svr_.Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
+    svr_->Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
 
     registerMetaRoutes(*this);
     registerWebuiAuthRoutes(*this);
@@ -344,18 +455,18 @@ void ApiServer::registerRoutes() {
     // if cpp-httplib's matching order ever changes.
     registerFunctionDispatchRoutes(*this);
 
-    if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
-    if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
+    if (!d_.shareDir.empty()) svr_->set_mount_point("/docs", d_.shareDir + "/docs");
+    if (!d_.webuiDir.empty()) svr_->set_mount_point("/", d_.webuiDir);
 }
 
 void ApiServer::setThreadPoolSize(uint32_t n) {
     if (n == 0) return;  // leave cpp-httplib's own default alone
-    svr_.new_task_queue = [n] { return new httplib::ThreadPool(n); };
+    svr_->new_task_queue = [n] { return new httplib::ThreadPool(n); };
 }
 
-int  ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
-void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
-bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }
-void ApiServer::stop() { svr_.stop(); }
+int  ApiServer::bindToAnyPort(const std::string& host) { return svr_->bind_to_any_port(host); }
+void ApiServer::listenAfterBind() { svr_->listen_after_bind(); }
+bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_->listen(host, port); }
+void ApiServer::stop() { svr_->stop(); }
 
 } // namespace svapi

+ 18 - 3
src/server.hpp

@@ -10,6 +10,7 @@
 #include "runner_client.hpp"
 #include "key_store.hpp"
 #include "settings_store.hpp"
+#include <memory>
 #include <httplib.h>
 #include <optional>
 #include <string>
@@ -75,7 +76,11 @@ std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group)
 
 class ApiServer {
 public:
-    explicit ApiServer(ServerDeps deps);
+    /// `tlsCertDir` empty means PLAIN HTTP, which is the default and every
+    /// deployment today: behind nginx, in the devstack, and in the test
+    /// fixture. Non-empty constructs an `SSLServer` instead and installs the
+    /// SNI hook, so TLS is opt-in by configuration rather than by build.
+    explicit ApiServer(ServerDeps deps, std::string tlsCertDir = {});
     void registerRoutes();
     /// Size the request thread pool. 0 leaves cpp-httplib's own default
     /// (`max(8, hardware_concurrency - 1)`) in place.
@@ -90,11 +95,21 @@ public:
     void listenAfterBind();
     bool listen(const std::string& host, uint16_t port);
     void stop();
-    httplib::Server& raw() { return svr_; }
+    httplib::Server& raw() { return *svr_; }
+    /// False when TLS was asked for and could not be set up. main() must REFUSE
+    /// TO START on that: a server that silently fell back to plain HTTP on the
+    /// port a customer reaches over https is worse than one that does not come
+    /// up, because nothing downstream would report it.
+    bool valid() const;
     ServerDeps& deps() { return d_; }
 private:
     ServerDeps d_;
-    httplib::Server svr_;
+    /// A pointer because the concrete type is decided at construction:
+    /// `SSLServer` when a certificate directory is configured, `Server`
+    /// otherwise. `raw()` keeps its signature, so no route registration
+    /// changes.
+    std::unique_ptr<httplib::Server> svr_;
+    bool tls_ = false;
 };
 
 // Auth helpers (defined in server.cpp).

+ 120 - 0
src/tls_certs.cpp

@@ -0,0 +1,120 @@
+#include "tls_certs.hpp"
+
+#include "hostnames.hpp"
+
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+bool endsWith(std::string_view s, std::string_view suf) {
+    return s.size() >= suf.size() && s.compare(s.size() - suf.size(), suf.size(), suf) == 0;
+}
+
+/// How many labels a name has, and whether any is empty. An empty label is what
+/// makes `a..b` and a leading dot unmatched rather than mishandled.
+bool labelsOk(std::string_view h) {
+    if (h.empty()) return false;
+    std::size_t start = 0;
+    while (true) {
+        const std::size_t dot = h.find('.', start);
+        const std::string_view label =
+            h.substr(start, dot == std::string_view::npos ? std::string_view::npos : dot - start);
+        if (label.empty()) return false;
+        if (dot == std::string_view::npos) return true;
+        start = dot + 1;
+    }
+}
+
+} // namespace
+
+std::optional<std::string> certNameFromFilename(std::string_view filename) {
+    // Strip a directory, if a caller passed a path.
+    const std::size_t slash = filename.find_last_of('/');
+    if (slash != std::string_view::npos) filename = filename.substr(slash + 1);
+
+    // The private half names no host. Checked FIRST, because `host.key` would
+    // otherwise be read as a certificate for `host` and the pair would race to
+    // define the same name.
+    if (endsWith(filename, ".key")) return std::nullopt;
+
+    std::string_view stem = filename;
+    if (endsWith(stem, ".crt")) stem.remove_suffix(4);
+    else if (endsWith(stem, ".pem")) stem.remove_suffix(4);
+    else if (endsWith(stem, ".cert")) stem.remove_suffix(5);
+    else return std::nullopt;   // not a certificate we recognise
+    if (stem.empty()) return std::nullopt;
+
+    // lego writes a wildcard as `_.kb.example.com`; `wildcard.` is the other
+    // spelling operators use. Both become the same pattern, so the rest of this
+    // file only ever sees one form.
+    std::string name;
+    if (stem.size() > 2 && stem.substr(0, 2) == "_.") {
+        name = "*" + std::string(stem.substr(1));
+    } else if (stem.size() > 9 && stem.substr(0, 9) == "wildcard.") {
+        name = "*" + std::string(stem.substr(8));
+    } else {
+        name = std::string(stem);
+    }
+
+    // Normalise exactly as the Host header is normalised, so the comparison at
+    // request time cannot fail on case or a trailing dot. A certificate file
+    // named in capitals must serve the same name a lowercase request asks for.
+    const bool wild = !name.empty() && name.front() == '*';
+    const std::string bare = wild ? name.substr(1) : name;   // keeps the leading '.'
+    std::string normalised = normaliseHost(bare);
+    if (normalised.empty()) return std::nullopt;
+    // normaliseHost strips nothing from a leading dot, so re-attach the star.
+    return wild ? "*" + normalised : normalised;
+}
+
+bool certCovers(std::string_view pattern, std::string_view host) {
+    if (pattern.empty() || host.empty()) return false;
+    if (!labelsOk(host)) return false;
+
+    if (pattern.front() != '*') return pattern == host;   // exact
+
+    // A bare `*` matches nothing: a certificate claiming every name is not a
+    // configuration anyone means, and treating it as a catch-all would be the
+    // default certificate this design refuses to have.
+    if (pattern.size() < 3 || pattern[1] != '.') return false;
+    const std::string_view suffix = pattern.substr(1);    // ".kb.example.com"
+
+    // Only ONE wildcard, and only leftmost - `a.*.example.com` and
+    // `*.*.example.com` match nothing.
+    if (suffix.find('*') != std::string_view::npos) return false;
+    if (!labelsOk(suffix.substr(1))) return false;
+
+    if (!endsWith(host, suffix)) return false;
+    const std::string_view head = host.substr(0, host.size() - suffix.size());
+    // EXACTLY ONE label: non-empty and containing no dot. This is the rule that
+    // stops `*.example.com` covering `a.b.example.com`, which is how one
+    // tenant's certificate silently begins covering another's subdomain.
+    return !head.empty() && head.find('.') == std::string_view::npos;
+}
+
+const CertFile* selectCert(const std::vector<CertFile>& available, std::string_view host) {
+    const std::string h = normaliseHost(host);
+    if (h.empty()) return nullptr;
+
+    // EXACT FIRST, in a separate pass rather than by scoring in one. Two passes
+    // make the precedence a property of the code's structure instead of a
+    // comparison somebody can get backwards, and this precedence has to hold:
+    // without it, renewing a wildcard could silently change which certificate a
+    // tenant with its own certificate is served.
+    for (const CertFile& c : available)
+        if (c.name == h) return &c;
+
+    // Then wildcards. Among several, the LONGEST pattern wins, so
+    // `*.kb.example.com` beats `*.example.com` for `nt.kb.example.com` - the
+    // more specific statement of intent.
+    const CertFile* best = nullptr;
+    for (const CertFile& c : available) {
+        if (c.name.empty() || c.name.front() != '*') continue;
+        if (!certCovers(c.name, h)) continue;
+        if (!best || c.name.size() > best->name.size()) best = &c;
+    }
+    return best;
+}
+
+} // namespace svapi

+ 84 - 0
src/tls_certs.hpp

@@ -0,0 +1,84 @@
+#pragma once
+
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+/// Choosing a TLS certificate for the hostname a client asked for.
+///
+/// WE DO NOT SPEAK ACME, deliberately and permanently. An external client
+/// (lego, certbot, acme.sh) obtains and renews certificates with DNS-01 and
+/// writes them into a directory; this reads what is there. The reasons are
+/// worth keeping because the temptation recurs: an ACME bug in our process is a
+/// live outage on every hostname at once, renewal scheduling is somebody else's
+/// tested code, and an account key is a credential we would rather not hold.
+/// The cost is one more moving part in the deployment, which is the better
+/// trade.
+///
+/// THE SELECTION RULES ARE PURE AND LIVE HERE because they are where the
+/// mistakes are, and none of them needs a socket to test. Serving the WRONG
+/// certificate is the failure to avoid: it is not a security hole - a client
+/// refuses a certificate that does not match the name it asked for - but it is
+/// an outage that reads as a certificate problem rather than a configuration
+/// one, which is the expensive kind to diagnose.
+namespace svapi {
+
+/// A certificate on disk and the name it serves.
+struct CertFile {
+    /// The name read off the FILENAME, which may be a wildcard pattern.
+    std::string name;
+    std::string certPath;
+    std::string keyPath;
+};
+
+/// The hostname a certificate file serves, from its filename.
+///
+/// THE FILENAME IS THE SOURCE OF TRUTH, not the certificate's SANs, and that is
+/// a deliberate trade with a stated cost. For it: the mapping is auditable with
+/// `ls`, it needs no X509 parsing in our process, and it matches what ACME
+/// clients already write. Against it: a file NAMED for one host but CONTAINING
+/// a certificate for another will be served for the name on the tin, and the
+/// client will reject it.
+///
+/// That failure is loud - a browser shows a name-mismatch error and refuses -
+/// so it cannot pass silently, which is why the simpler scheme is acceptable.
+/// Reading the SANs would catch it at load time instead and is a real
+/// improvement; it is deferred rather than overlooked.
+///
+/// Accepted spellings, matching what lego and certbot write:
+///   `nt.kb.example.com.crt`   -> nt.kb.example.com
+///   `nt.kb.example.com.pem`   -> nt.kb.example.com
+///   `_.kb.example.com.crt`    -> *.kb.example.com   (lego's wildcard spelling)
+///   `wildcard.kb.example.com.crt` -> *.kb.example.com
+/// A `.key` file is the private half and names no host.
+std::optional<std::string> certNameFromFilename(std::string_view filename);
+
+/// Does `pattern` (possibly a wildcard) cover `host`?
+///
+/// RFC 6125 wildcard rules, and each restriction below exists because the loose
+/// version is a real misconfiguration rather than a theoretical one:
+///   - the wildcard must be the LEFTMOST label and the only one, so
+///     `a.*.example.com` matches nothing
+///   - it matches EXACTLY ONE label, so `*.example.com` covers
+///     `foo.example.com` and NOT `a.b.example.com` - the loose reading is how
+///     one tenant's certificate silently starts covering another's subdomain
+///   - it does NOT match the bare domain, so `*.example.com` does not cover
+///     `example.com`, which needs its own certificate
+///   - a bare `*` matches nothing at all
+bool certCovers(std::string_view pattern, std::string_view host);
+
+/// The best certificate for `host`, or nullopt to REFUSE THE HANDSHAKE.
+///
+/// AN EXACT MATCH BEATS A WILDCARD, always. Without that rule a deployment
+/// holding both `*.kb.example.com` and a specific `nt.kb.example.com` would
+/// serve whichever happened to be enumerated first, so renewing one could
+/// silently change which certificate a tenant is served.
+///
+/// NO MATCH MEANS REFUSE, never "serve the first one" and never "serve a
+/// default". A default certificate here would turn a missing-certificate
+/// mistake into a name-mismatch error on a RANDOM tenant's hostname, which is
+/// strictly harder to diagnose than a refused handshake naming the host.
+const CertFile* selectCert(const std::vector<CertFile>& available, std::string_view host);
+
+} // namespace svapi

+ 12 - 0
tests/CMakeLists.txt

@@ -43,6 +43,18 @@ add_executable(test_hostnames test_hostnames.cpp)
 target_link_libraries(test_hostnames PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_hostnames)
 
+# Certificate selection is pure too: the wildcard rules and the exact-beats-
+# wildcard precedence need no socket and no OpenSSL to test.
+add_executable(test_tls_certs test_tls_certs.cpp)
+target_link_libraries(test_tls_certs PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_tls_certs)
+
+# A REAL handshake. Needs the openssl CLI to mint test certificates and skips
+# cleanly without it, the same way the integration tests skip with no database.
+add_executable(test_tls_sni test_tls_sni.cpp)
+target_link_libraries(test_tls_sni PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_tls_sni)
+
 add_executable(test_filters test_filters.cpp)
 target_link_libraries(test_filters PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_filters)

+ 179 - 0
tests/test_tls_certs.cpp

@@ -0,0 +1,179 @@
+// Certificate selection for a hostname. Pure: no socket, no OpenSSL, no disk.
+//
+// The failure to avoid is serving the WRONG certificate. It is not a security
+// hole - a client refuses a certificate that does not match the name it asked
+// for - but it is an outage that reads as a certificate problem rather than a
+// configuration one, and those are the expensive ones to diagnose.
+#include <gtest/gtest.h>
+
+#include "tls_certs.hpp"
+
+using svapi::CertFile;
+using svapi::certCovers;
+using svapi::certNameFromFilename;
+using svapi::selectCert;
+
+// --- what a filename says it serves -----------------------------------------
+
+TEST(CertNameFromFilename, ReadsAPlainHostname) {
+    EXPECT_EQ(certNameFromFilename("nt.kb.example.com.crt").value_or("-"), "nt.kb.example.com");
+    EXPECT_EQ(certNameFromFilename("nt.kb.example.com.pem").value_or("-"), "nt.kb.example.com");
+    EXPECT_EQ(certNameFromFilename("nt.kb.example.com.cert").value_or("-"), "nt.kb.example.com");
+    EXPECT_EQ(certNameFromFilename("/etc/tls/nt.kb.example.com.crt").value_or("-"),
+              "nt.kb.example.com");
+}
+
+TEST(CertNameFromFilename, ReadsBothWildcardSpellings) {
+    // lego writes `_.`; operators also write `wildcard.`. Both normalise to one
+    // form so the rest of the code only ever sees `*.`.
+    EXPECT_EQ(certNameFromFilename("_.kb.example.com.crt").value_or("-"), "*.kb.example.com");
+    EXPECT_EQ(certNameFromFilename("wildcard.kb.example.com.crt").value_or("-"),
+              "*.kb.example.com");
+}
+
+TEST(CertNameFromFilename, APrivateKeyNamesNoHost) {
+    // Checked BEFORE the certificate suffixes: otherwise `host.key` reads as a
+    // certificate for `host` and the pair races to define the same name.
+    EXPECT_FALSE(certNameFromFilename("nt.kb.example.com.key").has_value());
+}
+
+TEST(CertNameFromFilename, IgnoresAnythingThatIsNotACertificate) {
+    for (const char* f : {"README", "notes.txt", "nt.kb.example.com", ".crt", "", "archive.tar.gz"})
+        EXPECT_FALSE(certNameFromFilename(f).has_value()) << f;
+}
+
+TEST(CertNameFromFilename, NormalisesExactlyAsTheHostHeaderIs) {
+    // A certificate file named in capitals must serve the name a lowercase
+    // request asks for, or selection fails on spelling at request time.
+    EXPECT_EQ(certNameFromFilename("NT.KB.Example.COM.crt").value_or("-"), "nt.kb.example.com");
+    EXPECT_EQ(certNameFromFilename("_.KB.Example.com.crt").value_or("-"), "*.kb.example.com");
+}
+
+// --- wildcard rules: every restriction is a real misconfiguration -----------
+
+TEST(CertCovers, AnExactNameMatchesOnlyItself) {
+    EXPECT_TRUE(certCovers("nt.kb.example.com", "nt.kb.example.com"));
+    EXPECT_FALSE(certCovers("nt.kb.example.com", "other.kb.example.com"));
+    EXPECT_FALSE(certCovers("nt.kb.example.com", "kb.example.com"));
+}
+
+TEST(CertCovers, AWildcardMatchesEXACTLYOneLabel) {
+    EXPECT_TRUE(certCovers("*.kb.example.com", "nt.kb.example.com"));
+    // THE one that matters. The loose reading is how one tenant's certificate
+    // silently begins covering another tenant's deeper subdomain.
+    EXPECT_FALSE(certCovers("*.kb.example.com", "a.b.kb.example.com"))
+        << "a wildcard matched more than one label";
+    // And it does NOT cover the bare domain, which needs its own certificate.
+    EXPECT_FALSE(certCovers("*.kb.example.com", "kb.example.com"));
+    EXPECT_FALSE(certCovers("*.kb.example.com", "example.com"));
+}
+
+TEST(CertCovers, AWildcardMustBeLEFTMOSTAndTheOnlyOne) {
+    EXPECT_FALSE(certCovers("a.*.example.com", "a.b.example.com"));
+    EXPECT_FALSE(certCovers("*.*.example.com", "a.b.example.com"));
+    EXPECT_FALSE(certCovers("kb.*.com", "kb.example.com"));
+}
+
+TEST(CertCovers, ABareStarMatchesNOTHING) {
+    // A certificate claiming every name is not a configuration anyone means,
+    // and treating it as a catch-all would reintroduce the default certificate
+    // this design refuses to have.
+    for (const char* h : {"anything.example.com", "example.com", "a.b.c.d"}) {
+        EXPECT_FALSE(certCovers("*", h)) << h;
+        EXPECT_FALSE(certCovers("*.", h)) << h;
+    }
+}
+
+TEST(CertCovers, MalformedInputMatchesNothingRatherThanThrowing) {
+    for (const char* h : {"", ".example.com", "a..b.example.com"})
+        EXPECT_FALSE(certCovers("*.example.com", h)) << h;
+    EXPECT_FALSE(certCovers("", "example.com"));
+}
+
+// --- selection: precedence, and the refusal ---------------------------------
+
+namespace {
+std::vector<CertFile> twoCerts() {
+    return {{"*.kb.example.com", "/w.crt", "/w.key"},
+            {"nt.kb.example.com", "/nt.crt", "/nt.key"}};
+}
+} // namespace
+
+TEST(SelectCert, AnEXACTMatchBeatsAWildcard) {
+    // Without this, a deployment holding both would serve whichever was
+    // enumerated first - so renewing one could silently change which
+    // certificate a tenant is served.
+    const auto certs = twoCerts();
+    const CertFile* c = selectCert(certs, "nt.kb.example.com");
+    ASSERT_NE(c, nullptr);
+    EXPECT_EQ(c->certPath, "/nt.crt") << "the wildcard won over an exact match";
+}
+
+TEST(SelectCert, AnExactMatchBeatsAWildcardOfTHESAMELENGTH) {
+    // THIS TEST EXISTS BECAUSE THE OBVIOUS ONE ABOVE CANNOT FAIL, which a
+    // deliberate falsification exposed: removing the exact-first pass entirely
+    // left all 16 tests green.
+    //
+    // The arithmetic. A wildcard covering host H is `*.<suffix>` where
+    // H = `<label>.<suffix>`, so |wildcard| = 2 + |suffix| and
+    // |H| = |label| + 1 + |suffix|. The wildcard is therefore SHORTER whenever
+    // the label is longer than one character - so with `nt.kb.example.com` a
+    // plain longest-name-wins rule picks the exact match by accident, and the
+    // test passes without the precedence it claims to check existing at all.
+    //
+    // A ONE-CHARACTER label makes the two lengths EQUAL, which is the only
+    // case that discriminates: a length comparison then ties and iteration
+    // order decides, which is exactly the nondeterminism the exact-first pass
+    // exists to remove. The wildcard is listed FIRST so a tie resolves the
+    // wrong way if the pass is missing.
+    const std::vector<CertFile> certs = {{"*.kb.example.com", "/w.crt", "/w.key"},
+                                         {"a.kb.example.com", "/exact.crt", "/exact.key"}};
+    ASSERT_EQ(certs[0].name.size(), certs[1].name.size()) << "the lengths must tie, or this "
+                                                             "test stops discriminating";
+    const CertFile* c = selectCert(certs, "a.kb.example.com");
+    ASSERT_NE(c, nullptr);
+    EXPECT_EQ(c->certPath, "/exact.crt")
+        << "a wildcard of equal length won over an exact match - the exact-first pass is gone, "
+           "so which certificate a tenant is served depends on enumeration order";
+}
+
+TEST(SelectCert, AWildcardCoversASiblingWithNoCertificateOfItsOwn) {
+    const auto certs = twoCerts();
+    const CertFile* c = selectCert(certs, "other.kb.example.com");
+    ASSERT_NE(c, nullptr);
+    EXPECT_EQ(c->certPath, "/w.crt");
+}
+
+TEST(SelectCert, TheLONGESTWildcardWinsAsTheMoreSpecificIntent) {
+    const std::vector<CertFile> certs = {{"*.example.com", "/broad.crt", "/broad.key"},
+                                         {"*.kb.example.com", "/narrow.crt", "/narrow.key"}};
+    const CertFile* c = selectCert(certs, "nt.kb.example.com");
+    ASSERT_NE(c, nullptr);
+    EXPECT_EQ(c->certPath, "/narrow.crt");
+}
+
+TEST(SelectCert, NoMatchIsNULLPTRSoTheHandshakeIsREFUSED) {
+    // Never "serve the first one" and never a default: that would turn a
+    // missing-certificate mistake into a name-mismatch error on a RANDOM
+    // tenant's hostname, which is strictly harder to diagnose than a refused
+    // handshake naming the host.
+    const auto certs = twoCerts();
+    for (const char* h : {"nobody.example.com", "kb.example.com", "example.com",
+                          "a.b.kb.example.com", ""}) {
+        EXPECT_EQ(selectCert(certs, h), nullptr) << h << " was served a certificate";
+    }
+}
+
+TEST(SelectCert, AnEmptyStoreServesNothingRatherThanCrashing) {
+    EXPECT_EQ(selectCert({}, "nt.kb.example.com"), nullptr);
+}
+
+TEST(SelectCert, SelectionIsCaseAndPortInsensitiveLikeTheHostHeader) {
+    const auto certs = twoCerts();
+    const CertFile* a = selectCert(certs, "NT.KB.Example.com");
+    ASSERT_NE(a, nullptr);
+    EXPECT_EQ(a->certPath, "/nt.crt");
+    const CertFile* b = selectCert(certs, "nt.kb.example.com:8443");
+    ASSERT_NE(b, nullptr);
+    EXPECT_EQ(b->certPath, "/nt.crt");
+}

+ 203 - 0
tests/test_tls_sni.cpp

@@ -0,0 +1,203 @@
+// A REAL TLS HANDSHAKE, selecting between certificates by SNI.
+//
+// WHY THIS TEST IS NOT A UNIT TEST: the selection rules are pure and tested in
+// test_tls_certs.cpp. What cannot be unit-tested is whether the hook is reached
+// at all, whether SSL_set_SSL_CTX actually changes the certificate sent, and
+// whether a name with no certificate refuses rather than serving the wrong one.
+// Those are facts about OpenSSL and cpp-httplib, not about our arithmetic, so
+// they need a socket.
+//
+// HOW IT KNOWS WHICH CERTIFICATE WAS SERVED, without parsing one: the client
+// pins its CA to exactly ONE self-signed certificate and turns verification
+// ON. Verification then succeeds only if the server sent that very certificate.
+// Pinning the OTHER certificate for the same hostname must FAIL - which is the
+// pairing, and the reason this cannot pass against a server that sends the same
+// certificate to everyone.
+#include <gtest/gtest.h>
+
+#include "cert_store.hpp"
+#include "server.hpp"
+
+#include <httplib.h>
+
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <thread>
+
+namespace {
+
+struct TlsFixture : public ::testing::Test {
+    std::filesystem::path dir;
+    std::unique_ptr<httplib::SSLServer> srv;
+    std::thread th;
+    int port = 0;
+
+    static bool makeCert(const std::filesystem::path& dir, const std::string& fileStem,
+                         const std::string& cn) {
+        const std::string crt = (dir / (fileStem + ".crt")).string();
+        const std::string key = (dir / (fileStem + ".key")).string();
+        const std::string cmd =
+            "openssl req -x509 -newkey rsa:2048 -keyout '" + key + "' -out '" + crt +
+            "' -days 2 -nodes -subj '/CN=" + cn + "' -addext 'subjectAltName=DNS:" + cn +
+            "' >/dev/null 2>&1";
+        return std::system(cmd.c_str()) == 0;
+    }
+
+    void SetUp() override {
+        dir = std::filesystem::temp_directory_path() /
+              ("svapi_tls_" + std::to_string(::getpid()));
+        std::filesystem::create_directories(dir);
+        // Two exact names and one wildcard, in lego's `_.` spelling.
+        if (!makeCert(dir, "nt.kb.example.test", "nt.kb.example.test") ||
+            !makeCert(dir, "other.kb.example.test", "other.kb.example.test") ||
+            !makeCert(dir, "_.wild.example.test", "*.wild.example.test"))
+            GTEST_SKIP() << "openssl is not available to generate test certificates";
+
+        ASSERT_EQ(svapi::certStore().reload(dir.string()), 3u)
+            << "the store did not load all three certificates from " << dir.string();
+
+        srv = std::make_unique<httplib::SSLServer>(
+            [](httplib::tls::ctx_t c) { return svapi::installSniHook((void*)c); });
+        ASSERT_TRUE(srv->is_valid()) << "the SNI hook would not install on the base context";
+        srv->Get("/probe", [](const httplib::Request& rq, httplib::Response& rs) {
+            // Request::sni() is httplib's own view of the negotiated name - a
+            // second, independent source from the certificate the client
+            // verified, so the two can corroborate each other.
+            rs.set_content("sni=" + rq.sni(), "text/plain");
+        });
+        port = srv->bind_to_any_port("127.0.0.1");
+        ASSERT_GT(port, 0);
+        th = std::thread([this] { srv->listen_after_bind(); });
+        for (int i = 0; i < 200 && !srv->is_running(); ++i)
+            std::this_thread::sleep_for(std::chrono::milliseconds(5));
+    }
+
+    void TearDown() override {
+        if (srv) srv->stop();
+        if (th.joinable()) th.join();
+        std::error_code ec;
+        std::filesystem::remove_all(dir, ec);
+    }
+
+    /// Connect as `host` with verification OFF.
+    ///
+    /// THIS IS THE ONLY CHECK THAT CAN TELL A REFUSED HANDSHAKE FROM A WRONG
+    /// CERTIFICATE, and it exists because a deliberate falsification showed the
+    /// pinned-CA tests below cannot. Adding a default-certificate fallback to
+    /// the hook left all six of them green: the client still failed, but
+    /// because the served certificate did not match its PIN rather than because
+    /// the server refused. Both outcomes are safe - the client rejects either
+    /// way - and they are operationally opposite: a refusal names the host in
+    /// our log and says what to add, while a wrong certificate produces a
+    /// name-mismatch error whose cause is not stated anywhere, and silently
+    /// undoes the decision to have no default certificate at all.
+    ///
+    /// With verification off, only a GENUINE refusal fails.
+    httplib::Result getUnverified(const std::string& host) {
+        httplib::SSLClient c(host, port);
+        c.set_hostname_addr_map({{host, "127.0.0.1"}});
+        c.enable_server_certificate_verification(false);
+        c.set_connection_timeout(5, 0);
+        c.set_read_timeout(5, 0);
+        return c.Get("/probe");
+    }
+
+    /// Connect as `host`, pinning `caStem`'s certificate as the only trusted CA.
+    httplib::Result get(const std::string& host, const std::string& caStem) {
+        httplib::SSLClient c(host, port);
+        // SNI carries `host` while the connection goes to loopback - the same
+        // hostname/address split ctx.fetch uses for its pinning.
+        c.set_hostname_addr_map({{host, "127.0.0.1"}});
+        c.set_ca_cert_path((dir / (caStem + ".crt")).string());
+        c.enable_server_certificate_verification(true);
+        c.set_connection_timeout(5, 0);
+        c.set_read_timeout(5, 0);
+        return c.Get("/probe");
+    }
+};
+
+} // namespace
+
+TEST_F(TlsFixture, EachHostnameIsServedITSOWNCertificate) {
+    auto a = get("nt.kb.example.test", "nt.kb.example.test");
+    ASSERT_TRUE(a) << "handshake failed for nt: " << httplib::to_string(a.error());
+    EXPECT_EQ(a->status, 200);
+    EXPECT_EQ(a->body, "sni=nt.kb.example.test") << "httplib saw a different negotiated name";
+
+    auto b = get("other.kb.example.test", "other.kb.example.test");
+    ASSERT_TRUE(b) << "handshake failed for other: " << httplib::to_string(b.error());
+    EXPECT_EQ(b->body, "sni=other.kb.example.test");
+}
+
+TEST_F(TlsFixture, PinningTheWRONGCertificateFAILS_whichIsWhatMakesTheTestAbove_MEAN_something) {
+    // THE PAIRING. Without it, the test above would pass just as well against a
+    // server that sent one certificate to every client - because the client
+    // would be pinning that same certificate.
+    auto wrong = get("nt.kb.example.test", "other.kb.example.test");
+    EXPECT_FALSE(wrong) << "the server sent other's certificate for nt's hostname, or sent nt's "
+                           "certificate to a client that trusts only other's - either way the "
+                           "per-hostname selection is not happening";
+}
+
+TEST_F(TlsFixture, AWildcardCertificateServesASubdomain) {
+    auto r = get("anything.wild.example.test", "_.wild.example.test");
+    ASSERT_TRUE(r) << "handshake failed for a wildcard subdomain: "
+                   << httplib::to_string(r.error());
+    EXPECT_EQ(r->body, "sni=anything.wild.example.test");
+}
+
+TEST_F(TlsFixture, AWildcardDoesNOTCoverADeeperSubdomainOverTheWire) {
+    // The pure rule is tested in test_tls_certs.cpp; this confirms it is the
+    // rule actually in force during a handshake, which is a different claim.
+    auto r = get("a.b.wild.example.test", "_.wild.example.test");
+    EXPECT_FALSE(r) << "a wildcard covered two labels in a real handshake";
+}
+
+TEST_F(TlsFixture, AHostnameWithNOCertificateIsREFUSEDRatherThanServedTheWrongOne) {
+    // The whole point of having no default certificate. Every pinning choice
+    // must fail, because the server should send nothing at all.
+    for (const char* ca : {"nt.kb.example.test", "other.kb.example.test", "_.wild.example.test"}) {
+        auto r = get("nobody.example.test", ca);
+        EXPECT_FALSE(r) << "a hostname with no certificate was served the one pinned as " << ca;
+    }
+}
+
+TEST_F(TlsFixture, ThereIsNODefaultCertificate_measuredWithVerificationOFF) {
+    // The discriminating test. See getUnverified() for why the pinned-CA tests
+    // cannot answer this: they pass whether the handshake was refused or a
+    // wrong certificate was served and rejected.
+    //
+    // PAIRED, so it cannot pass by everything failing: a KNOWN hostname must
+    // still complete a handshake with verification off.
+    auto known = getUnverified("nt.kb.example.test");
+    ASSERT_TRUE(known) << "verification off should make a known hostname trivially succeed: "
+                       << httplib::to_string(known.error());
+    EXPECT_EQ(known->status, 200);
+
+    for (const char* h : {"nobody.example.test", "wild.example.test", "a.b.wild.example.test"}) {
+        auto r = getUnverified(h);
+        EXPECT_FALSE(r) << "'" << h << "' completed a handshake with NO certificate of its own, "
+                           "so something is serving a default certificate - which turns a "
+                           "missing-certificate mistake into a name-mismatch error on a random "
+                           "tenant's hostname";
+    }
+}
+
+TEST_F(TlsFixture, ACLIENTSENDINGNOSNIAtAllIsRefused) {
+    // Addressing the service by IP sends no SNI (RFC 6066 forbids it for IP
+    // literals, and httplib honours that), so there is no name to choose a
+    // certificate for. Refused rather than served an arbitrary one.
+    httplib::SSLClient c("127.0.0.1", port);
+    c.enable_server_certificate_verification(false);
+    c.set_connection_timeout(5, 0);
+    auto r = c.Get("/probe");
+    EXPECT_FALSE(r) << "a client that sent no SNI was served somebody's certificate";
+}
+
+TEST_F(TlsFixture, TheBareParentOfAWildcardIsRefusedToo) {
+    // `*.wild.example.test` does not cover `wild.example.test`, which needs its
+    // own certificate - a rule people get wrong in both directions.
+    auto r = get("wild.example.test", "_.wild.example.test");
+    EXPECT_FALSE(r);
+}