httpsd 0.1.1

A pure-Rust HTTP/HTTPS server — usable as a sans-I/O library with pluggable runtimes (thread pool, tokio, mio) or as a CLI that serves a directory or a TOML config.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! [`AcmeManager`] ties the store, the protocol client, and the challenge
//! solvers together: it answers "what certificate do I serve for this SNI?",
//! issuing (and renewing) on demand with per-host single-flight, and exposes
//! the challenge state the TLS router and HTTP listener read.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use purecrypto::ec::BoxedEcdsaPrivateKey;
use purecrypto::hash::sha256;
use purecrypto::x509::Certificate;

use super::client::{AcmeClient, ChallengeSolver, LETSENCRYPT_PRODUCTION};
use super::jose::AccountKey;
use super::store::Store;
use crate::error::{Error, Result};
use crate::tls::TlsAcceptor;

/// Re-issue a certificate once it is within this window of expiry.
const RENEW_BEFORE_SECS: u64 = 30 * 86_400;

/// Maximum number of successfully-issued certs kept in memory. The on-disk store
/// is the source of truth; evicted entries are reloaded cheaply on next use.
/// Bounding this stops the success cache growing without limit under many
/// distinct SNIs.
const CACHE_MAX: usize = 1024;

/// After an issuance failure for a host, refuse to re-attempt for this long.
/// This negative cache stops a non-issuable SNI from re-running the full
/// blocking order/poll flow (which can sleep tens of seconds) on every
/// connection.
const NEG_CACHE_COOLDOWN_SECS: u64 = 300;

/// Maximum number of remembered issuance failures. Bounds the negative cache so
/// an attacker hitting unbounded distinct SNIs cannot grow memory without limit.
const NEG_CACHE_MAX: usize = 4096;

/// Maximum number of certificate issuances allowed to run concurrently. Each
/// issuance can block for tens of seconds; this caps the worst-case number of
/// threads parked in the ACME flow regardless of how many distinct SNIs arrive.
const MAX_INFLIGHT: usize = 16;

/// Configuration for automatic certificate management.
#[derive(Debug, Clone)]
pub struct AcmeConfig {
    /// ACME directory URL (defaults to Let's Encrypt production).
    pub directory_url: String,
    /// Whether the operator has accepted the CA's terms of service. Issuance is
    /// refused unless this is `true`.
    pub accept_tos: bool,
    /// Optional account contact email.
    pub email: Option<String>,
    /// If set, only these host names may be issued for; others are rejected.
    pub host_whitelist: Option<HashSet<String>>,
    /// Override the on-disk storage directory.
    pub cert_dir: Option<PathBuf>,
}

impl Default for AcmeConfig {
    fn default() -> AcmeConfig {
        AcmeConfig {
            directory_url: LETSENCRYPT_PRODUCTION.to_owned(),
            accept_tos: false,
            email: None,
            host_whitelist: None,
            cert_dir: None,
        }
    }
}

/// What the TLS router should do for a connection.
pub enum CertChoice {
    /// Complete the handshake with this acceptor.
    Serve(TlsAcceptor),
    /// Refuse the connection (e.g. host not in the whitelist).
    Reject,
}

struct Cached {
    acceptor: TlsAcceptor,
    not_after: Option<u64>,
}

/// A size-bounded, approximately-LRU cache of issued acceptors. Reads bump a
/// monotonic tick; when full, the least-recently-used entry is evicted.
struct CertCache {
    map: HashMap<String, (Arc<Cached>, u64)>,
    tick: u64,
}

impl CertCache {
    fn new() -> CertCache {
        CertCache {
            map: HashMap::new(),
            tick: 0,
        }
    }

    fn get(&mut self, host: &str) -> Option<Arc<Cached>> {
        self.tick += 1;
        let tick = self.tick;
        let entry = self.map.get_mut(host)?;
        entry.1 = tick;
        Some(Arc::clone(&entry.0))
    }

    fn put(&mut self, host: &str, value: Arc<Cached>) {
        self.tick += 1;
        let tick = self.tick;
        if !self.map.contains_key(host)
            && self.map.len() >= CACHE_MAX
            && let Some(lru) = self
                .map
                .iter()
                .min_by_key(|(_, (_, t))| *t)
                .map(|(k, _)| k.clone())
        {
            self.map.remove(&lru);
        }
        self.map.insert(host.to_owned(), (value, tick));
    }
}

/// Shared automatic-certificate manager. Cheap to clone (`Arc` inside).
#[derive(Clone)]
pub struct AcmeManager {
    inner: Arc<Inner>,
}

struct Inner {
    cfg: AcmeConfig,
    store: Store,
    self_signed: TlsAcceptor,
    cache: Mutex<CertCache>,
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
    /// host → earliest Unix time we may retry issuance after a recent failure.
    failures: Mutex<HashMap<String, u64>>,
    /// Number of issuances currently talking to the CA (bounded by `MAX_INFLIGHT`).
    in_flight: AtomicUsize,
    /// host → TLS-ALPN-01 challenge acceptor (present during validation).
    alpn_challenges: Arc<Mutex<HashMap<String, TlsAcceptor>>>,
    /// HTTP-01 token → key authorization (served by the HTTP listener).
    http_challenges: Arc<Mutex<HashMap<String, String>>>,
}

impl AcmeManager {
    /// Create a manager, opening the on-disk store and a fallback self-signed
    /// identity (used for loopback and host-less connections).
    pub fn new(cfg: AcmeConfig) -> Result<AcmeManager> {
        let store = Store::open(cfg.cert_dir.clone())?;
        let self_signed = TlsAcceptor::self_signed(&["localhost"])?;
        Ok(AcmeManager {
            inner: Arc::new(Inner {
                cfg,
                store,
                self_signed,
                cache: Mutex::new(CertCache::new()),
                locks: Mutex::new(HashMap::new()),
                failures: Mutex::new(HashMap::new()),
                in_flight: AtomicUsize::new(0),
                alpn_challenges: Arc::new(Mutex::new(HashMap::new())),
                http_challenges: Arc::new(Mutex::new(HashMap::new())),
            }),
        })
    }

    /// The fallback self-signed acceptor (loopback / no-SNI connections).
    pub fn self_signed(&self) -> TlsAcceptor {
        self.inner.self_signed.clone()
    }

    /// The TLS-ALPN-01 challenge acceptor for `host`, if a validation is in
    /// progress. The TLS router uses this when the ClientHello offers
    /// `acme-tls/1`.
    pub fn challenge_acceptor(&self, host: &str) -> Option<TlsAcceptor> {
        self.inner
            .alpn_challenges
            .lock()
            .unwrap()
            .get(&normalize(host))
            .cloned()
    }

    /// The HTTP-01 key authorization for `token`, if any (served by the HTTP
    /// listener at `/.well-known/acme-challenge/<token>`).
    pub fn http_challenge(&self, token: &str) -> Option<String> {
        self.inner
            .http_challenges
            .lock()
            .unwrap()
            .get(token)
            .cloned()
    }

    /// Decide which certificate to present for a connection.
    pub fn choose(&self, sni: Option<&str>, peer_is_loopback: bool) -> CertChoice {
        // Loopback never gets a public cert — there's nothing a CA could verify.
        if peer_is_loopback {
            return CertChoice::Serve(self.self_signed());
        }
        let Some(host) = sni.map(normalize).filter(|h| !h.is_empty()) else {
            // No SNI (bare IP over TLS): present the self-signed default.
            return CertChoice::Serve(self.self_signed());
        };
        if let Some(wl) = &self.inner.cfg.host_whitelist
            && !wl.contains(&host)
        {
            return CertChoice::Reject;
        }
        match self.get_or_issue(&host) {
            Ok(acceptor) => CertChoice::Serve(acceptor),
            Err(e) => {
                if cfg!(debug_assertions) {
                    eprintln!("httpsd: acme: no certificate for {host}: {e}");
                }
                CertChoice::Reject
            }
        }
    }

    /// Like [`choose`](Self::choose) but **never blocks on ACME issuance** —
    /// it serves only a cert already cached or on disk. Used by the QUIC/HTTP-3
    /// runtime, whose single event loop must not stall on a multi-second
    /// issuance; the TCP path issues, and HTTP/3 picks the cert up once it
    /// exists (browsers reach TCP first and upgrade via `Alt-Svc`).
    pub fn choose_cached(&self, sni: Option<&str>, peer_is_loopback: bool) -> CertChoice {
        if peer_is_loopback {
            return CertChoice::Serve(self.self_signed());
        }
        let Some(host) = sni.map(normalize).filter(|h| !h.is_empty()) else {
            return CertChoice::Serve(self.self_signed());
        };
        if let Some(wl) = &self.inner.cfg.host_whitelist
            && !wl.contains(&host)
        {
            return CertChoice::Reject;
        }
        if let Some(c) = self.inner.cache.lock().unwrap().get(&host) {
            return CertChoice::Serve(c.acceptor.clone());
        }
        match self.inner.store.load_cert(&host) {
            Ok(Some(stored)) => match TlsAcceptor::from_pem(&stored.chain_pem, &stored.key_pem) {
                Ok(acceptor) => {
                    let not_after = cert_not_after(&stored.chain_pem);
                    self.cache_put(&host, acceptor.clone(), not_after);
                    CertChoice::Serve(acceptor)
                }
                Err(_) => CertChoice::Reject,
            },
            // Not issued yet: don't block the QUIC loop — let the TCP path issue.
            _ => CertChoice::Reject,
        }
    }

    /// Return a ready acceptor for `host`, issuing or renewing as needed.
    fn get_or_issue(&self, host: &str) -> Result<TlsAcceptor> {
        let now = now_secs();

        // Fast path: a fresh cached cert.
        if let Some(c) = self.inner.cache.lock().unwrap().get(host)
            && !near_expiry(c.not_after, now)
        {
            return Ok(c.acceptor.clone());
        }

        // Negative cache: a recent failure short-circuits to an error (→ Reject)
        // without re-running the blocking issuance flow, until the cooldown ends.
        if self.in_backoff(host, now) {
            return Err(Error::Acme(format!(
                "{host}: skipping issuance, backing off after a recent failure"
            )));
        }

        // Serialize issuance per host.
        let lock = self.host_lock(host);
        let result = {
            let _guard = lock.lock().unwrap();

            // Re-check the cache and backoff now that we hold the lock (another
            // waiter may have just succeeded or failed).
            if let Some(c) = self.inner.cache.lock().unwrap().get(host)
                && !near_expiry(c.not_after, now)
            {
                Ok(c.acceptor.clone())
            } else if self.in_backoff(host, now) {
                Err(Error::Acme(format!(
                    "{host}: skipping issuance, backing off after a recent failure"
                )))
            } else {
                self.try_issue(host, now)
            }
        };
        // Drop the per-host lock entry if no other waiter still references it,
        // so the lock map cannot grow without bound across distinct SNIs.
        self.release_host_lock(host, lock);
        result
    }

    /// Disk-then-CA issuance, recording negative-cache state on the outcome.
    /// Assumes the per-host lock is held.
    fn try_issue(&self, host: &str, now: u64) -> Result<TlsAcceptor> {
        // Try disk before talking to the CA.
        let stored = self.inner.store.load_cert(host)?;
        if let Some(stored) = &stored {
            let not_after = cert_not_after(&stored.chain_pem);
            if !near_expiry(not_after, now) {
                let acceptor = TlsAcceptor::from_pem(&stored.chain_pem, &stored.key_pem)?;
                self.cache_put(host, acceptor.clone(), not_after);
                self.clear_failure(host);
                return Ok(acceptor);
            }
        }

        // We are about to talk to the CA: take a global in-flight permit so the
        // number of concurrent blocking issuances stays bounded.
        let Some(_permit) = self.acquire_permit() else {
            // Transient capacity limit: shed load without backing the host off.
            return Err(Error::Acme(format!(
                "{host}: too many certificate issuances in flight, retry shortly"
            )));
        };

        match self.issue(host) {
            Ok(acceptor) => {
                self.clear_failure(host);
                Ok(acceptor)
            }
            Err(e) => {
                // Renewal failed but a still-valid cert is on disk: serve it and
                // do NOT enter backoff (we have a usable cert to present).
                if let Some(stored) = &stored {
                    let not_after = cert_not_after(&stored.chain_pem);
                    if not_after.is_some_and(|t| t > now) {
                        if cfg!(debug_assertions) {
                            eprintln!(
                                "httpsd: acme: renewal for {host} failed, serving existing: {e}"
                            );
                        }
                        let acceptor = TlsAcceptor::from_pem(&stored.chain_pem, &stored.key_pem)?;
                        self.cache_put(host, acceptor.clone(), not_after);
                        return Ok(acceptor);
                    }
                }
                // Genuine failure with no servable cert: remember it briefly.
                self.record_failure(host, now);
                Err(e)
            }
        }
    }

    /// Issue a brand-new certificate for `host` via ACME and persist it.
    fn issue(&self, host: &str) -> Result<TlsAcceptor> {
        if !self.inner.cfg.accept_tos {
            return Err(Error::Acme(
                "automatic issuance disabled: the CA terms of service have not been accepted"
                    .into(),
            ));
        }
        let mut client = self.make_client()?;
        let solver = ManagerSolver {
            alpn: Arc::clone(&self.inner.alpn_challenges),
            http: Arc::clone(&self.inner.http_challenges),
        };
        let issued = client.issue(&[host], &solver)?;
        self.inner
            .store
            .save_cert(host, &issued.chain_pem, &issued.key_pem)?;
        let not_after = cert_not_after(&issued.chain_pem);
        let acceptor = TlsAcceptor::from_pem(&issued.chain_pem, &issued.key_pem)?;
        self.cache_put(host, acceptor.clone(), not_after);
        Ok(acceptor)
    }

    fn make_client(&self) -> Result<AcmeClient> {
        let account = match self.inner.store.load_account_key()? {
            Some(pem) => {
                let key = BoxedEcdsaPrivateKey::from_sec1_pem(&pem)
                    .map_err(|e| Error::Acme(format!("account key: {e:?}")))?;
                AccountKey::new(key)
            }
            None => {
                let acct = AccountKey::generate();
                self.inner
                    .store
                    .save_account_key(&acct.private_key().to_sec1_pem())?;
                acct
            }
        };
        AcmeClient::new(
            &self.inner.cfg.directory_url,
            account,
            self.inner.cfg.email.clone(),
        )
    }

    fn host_lock(&self, host: &str) -> Arc<Mutex<()>> {
        self.inner
            .locks
            .lock()
            .unwrap()
            .entry(host.to_owned())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone()
    }

    /// Drop the per-host lock entry once issuance completes if no other thread
    /// still references it. Holding the map mutex makes the strong-count check
    /// atomic against concurrent `host_lock` callers (they need the same mutex
    /// to clone the `Arc`). `2` = the map's copy plus the `lock` argument.
    fn release_host_lock(&self, host: &str, lock: Arc<Mutex<()>>) {
        let mut locks = self.inner.locks.lock().unwrap();
        if Arc::strong_count(&lock) == 2 {
            locks.remove(host);
        }
    }

    /// Whether `host` is within an issuance-failure cooldown. Expired entries are
    /// purged opportunistically.
    fn in_backoff(&self, host: &str, now: u64) -> bool {
        let mut failures = self.inner.failures.lock().unwrap();
        match failures.get(host).copied() {
            Some(retry_at) if retry_at > now => true,
            Some(_) => {
                failures.remove(host);
                false
            }
            None => false,
        }
    }

    /// Remember an issuance failure for `host`, bounding the map's size.
    fn record_failure(&self, host: &str, now: u64) {
        let retry_at = now.saturating_add(NEG_CACHE_COOLDOWN_SECS);
        let mut failures = self.inner.failures.lock().unwrap();
        if !failures.contains_key(host) && failures.len() >= NEG_CACHE_MAX {
            // Drop expired entries first; if still full, evict the soonest to
            // expire so the map can never grow past the cap.
            failures.retain(|_, &mut t| t > now);
            if failures.len() >= NEG_CACHE_MAX
                && let Some(oldest) = failures
                    .iter()
                    .min_by_key(|&(_, &t)| t)
                    .map(|(k, _)| k.clone())
            {
                failures.remove(&oldest);
            }
        }
        failures.insert(host.to_owned(), retry_at);
    }

    /// Clear any remembered failure for `host` (called on success).
    fn clear_failure(&self, host: &str) {
        self.inner.failures.lock().unwrap().remove(host);
    }

    /// Take a global in-flight issuance permit, or `None` if at capacity.
    fn acquire_permit(&self) -> Option<Permit<'_>> {
        let prev = self.inner.in_flight.fetch_add(1, Ordering::SeqCst);
        if prev >= MAX_INFLIGHT {
            self.inner.in_flight.fetch_sub(1, Ordering::SeqCst);
            None
        } else {
            Some(Permit {
                counter: &self.inner.in_flight,
            })
        }
    }

    fn cache_put(&self, host: &str, acceptor: TlsAcceptor, not_after: Option<u64>) {
        self.inner.cache.lock().unwrap().put(
            host,
            Arc::new(Cached {
                acceptor,
                not_after,
            }),
        );
    }
}

/// RAII guard for a global in-flight issuance permit.
struct Permit<'a> {
    counter: &'a AtomicUsize,
}

impl Drop for Permit<'_> {
    fn drop(&mut self) {
        self.counter.fetch_sub(1, Ordering::SeqCst);
    }
}

/// The solver the manager hands to the ACME client: it stashes challenge
/// responses in the shared maps the runtime serves from.
struct ManagerSolver {
    alpn: Arc<Mutex<HashMap<String, TlsAcceptor>>>,
    http: Arc<Mutex<HashMap<String, String>>>,
}

impl ChallengeSolver for ManagerSolver {
    fn preferred(&self) -> &[&'static str] {
        &["tls-alpn-01", "http-01"]
    }

    fn present(&self, typ: &str, host: &str, token: &str, key_auth: &str) -> Result<()> {
        match typ {
            "tls-alpn-01" => {
                let digest = sha256(key_auth.as_bytes());
                let acceptor = TlsAcceptor::acme_challenge(host, &digest)?;
                self.alpn.lock().unwrap().insert(normalize(host), acceptor);
            }
            "http-01" => {
                self.http
                    .lock()
                    .unwrap()
                    .insert(token.to_owned(), key_auth.to_owned());
            }
            other => return Err(Error::Acme(format!("unsupported challenge: {other}"))),
        }
        Ok(())
    }

    fn cleanup(&self, typ: &str, host: &str, token: &str) {
        match typ {
            "tls-alpn-01" => {
                self.alpn.lock().unwrap().remove(&normalize(host));
            }
            "http-01" => {
                self.http.lock().unwrap().remove(token);
            }
            _ => {}
        }
    }
}

fn normalize(host: &str) -> String {
    host.trim().trim_end_matches('.').to_ascii_lowercase()
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Whether a cert with this `not_after` should be renewed now.
fn near_expiry(not_after: Option<u64>, now: u64) -> bool {
    match not_after {
        Some(t) => now + RENEW_BEFORE_SECS >= t,
        // Unknown expiry: treat as needing renewal rather than never-expiring,
        // so a cert whose `notAfter` can't be parsed isn't served forever.
        None => true,
    }
}

/// Parse the leaf certificate's `notAfter` (Unix seconds) from a chain PEM.
fn cert_not_after(chain_pem: &str) -> Option<u64> {
    let cert = Certificate::from_pem(chain_pem).ok()?;
    Some(cert.validity().ok()?.not_after.to_unix())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn expiry_window() {
        let now = 1_000_000_000;
        assert!(near_expiry(Some(now + 10 * 86_400), now)); // 10 days left → renew
        assert!(!near_expiry(Some(now + 60 * 86_400), now)); // 60 days left → keep
        assert!(near_expiry(None, now)); // unknown expiry → renew, don't serve forever
    }

    #[test]
    fn normalize_host() {
        assert_eq!(normalize(" Example.COM. "), "example.com");
    }
}