-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtls.rs
More file actions
648 lines (595 loc) · 24.6 KB
/
Copy pathtls.rs
File metadata and controls
648 lines (595 loc) · 24.6 KB
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! TLS support, built on the sans-I/O [`purecrypto::tls`] engine.
//!
//! A [`TlsAcceptor`] holds a server [`Config`] (certificate chain + private
//! key). For each accepted socket it mints a [`TlsStream`], itself sans-I/O:
//! feed it ciphertext from the socket, pull decrypted application bytes,
//! push application bytes to encrypt, and drain ciphertext to write back.
//! [`crate::session::Session`] drives this together with the HTTP engine.
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use purecrypto::ec::ed25519::Ed25519PrivateKey;
use purecrypto::ec::{BoxedEcdsaPrivateKey, CurveId};
use purecrypto::rng::OsRng;
use purecrypto::rsa::BoxedRsaPrivateKey;
use purecrypto::tls::{Config, Connection, SigningKey};
use purecrypto::x509::{AnyPrivateKey, Certificate, DistinguishedName, Time, Validity};
#[cfg(feature = "acme")]
use purecrypto::x509::{CertSigner, Extension, GeneralName, extension::subject_alt_name};
use crate::error::{Error, Result};
fn tls_err<E: std::fmt::Debug>(e: E) -> Error {
Error::Tls(format!("{e:?}"))
}
/// A reusable TLS server configuration. Cheap to clone (shares the underlying
/// config via `Arc`).
#[derive(Clone)]
pub struct TlsAcceptor {
config: Arc<Config>,
/// The certificate chain (DER, leaf first) and the key as PEM, retained so
/// the same identity can also mint per-connection QUIC configs for HTTP/3
/// (`QuicConfig`/`SigningKey` are neither `Clone` nor reusable across
/// connections, so the key PEM is re-parsed on demand).
#[cfg(feature = "h3")]
chain: Vec<Vec<u8>>,
#[cfg(feature = "h3")]
key_pem: Arc<String>,
}
impl TlsAcceptor {
/// Build an acceptor from a PEM certificate chain and a PEM private key.
///
/// The certificate PEM may contain the leaf followed by intermediates. The
/// key may be PKCS#8 (`PRIVATE KEY`), PKCS#1 RSA (`RSA PRIVATE KEY`), or
/// SEC1 EC (`EC PRIVATE KEY`).
pub fn from_pem(cert_pem: &str, key_pem: &str) -> Result<TlsAcceptor> {
let chain = cert_chain_der(cert_pem)?;
if chain.is_empty() {
return Err(Error::Tls("no certificates found in PEM".into()));
}
TlsAcceptor::build(chain, key_pem.to_owned())
}
/// Build an acceptor by reading a certificate file and a key file.
pub fn from_pem_files(
cert_path: impl AsRef<std::path::Path>,
key_path: impl AsRef<std::path::Path>,
) -> Result<TlsAcceptor> {
let cert = std::fs::read_to_string(cert_path)?;
warn_if_key_world_readable(key_path.as_ref());
let key = std::fs::read_to_string(key_path)?;
TlsAcceptor::from_pem(&cert, &key)
}
/// Generate an ephemeral self-signed certificate covering the given host
/// names. Uses an ECDSA P-256 key, which generates near-instantly (unlike
/// RSA). Handy for local development; clients must opt out of verification
/// or trust the generated certificate.
pub fn self_signed(hostnames: &[&str]) -> Result<TlsAcceptor> {
let primary = hostnames.first().copied().unwrap_or("localhost");
let mut rng = OsRng;
let key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
let name = DistinguishedName::common_name(primary);
let validity = Validity::new(
Time::utc(2020, 1, 1, 0, 0, 0),
Time::utc(2040, 1, 1, 0, 0, 0),
);
// Keep the SEC1 PEM so `build`/`quic_config` can re-parse the identity.
let key_pem = key.to_sec1_pem();
let any = AnyPrivateKey::Ecdsa(key);
let cert = Certificate::self_signed_with_sans(&any, &name, &validity, 1, false, hostnames)
.map_err(tls_err)?;
let chain = vec![cert.to_der().to_vec()];
TlsAcceptor::build(chain, key_pem)
}
fn build(chain: Vec<Vec<u8>>, key_pem: String) -> Result<TlsAcceptor> {
// Offer HTTP/2 ahead of HTTP/1.1 when compiled in; the client picks.
let alpn = if cfg!(feature = "h2") {
vec![b"h2".to_vec(), b"http/1.1".to_vec()]
} else {
vec![b"http/1.1".to_vec()]
};
TlsAcceptor::build_with_alpn(chain, key_pem, alpn)
}
fn build_with_alpn(
chain: Vec<Vec<u8>>,
key_pem: String,
alpn: Vec<Vec<u8>>,
) -> Result<TlsAcceptor> {
let key = load_signing_key(&key_pem)?;
let config = Config::builder()
.rng(Arc::new(OsRng))
.tls_only()
.identity(chain.clone(), key)
.alpn(alpn)
.build();
Ok(TlsAcceptor {
config: Arc::new(config),
#[cfg(feature = "h3")]
chain,
#[cfg(feature = "h3")]
key_pem: Arc::new(key_pem),
})
}
/// Build the special acceptor for an ACME **TLS-ALPN-01** challenge
/// (RFC 8737): a self-signed cert for `host` carrying the critical
/// `id-pe-acmeIdentifier` extension with `key_auth_digest`
/// (`SHA-256(key authorization)`), and an ALPN of exactly `acme-tls/1`.
/// The CA opens an `acme-tls/1` connection and validates this cert; no
/// application data flows.
#[cfg(feature = "acme")]
pub fn acme_challenge(host: &str, key_auth_digest: &[u8; 32]) -> Result<TlsAcceptor> {
let mut rng = OsRng;
let key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
let name = DistinguishedName::common_name(host);
let validity = Validity::new(
Time::utc(2020, 1, 1, 0, 0, 0),
Time::utc(2040, 1, 1, 0, 0, 0),
);
let san = subject_alt_name(&[GeneralName::Dns(host.to_owned())]);
// extnValue is OCTET STRING; its content is itself an OCTET STRING of
// the 32-byte digest. `Extension.value` is wrapped in the outer OCTET
// STRING at serialization, so it must hold the inner DER `04 20 <32>`.
let mut acme_value = vec![0x04, 0x20];
acme_value.extend_from_slice(key_auth_digest);
let acme_ext = Extension {
oid: vec![1, 3, 6, 1, 5, 5, 7, 1, 31], // id-pe-acmeIdentifier
critical: true,
value: acme_value,
};
let cert = Certificate::self_signed_with_extensions(
&CertSigner::Ecdsa(&key),
&name,
&validity,
1,
&[san, acme_ext],
)
.map_err(tls_err)?;
let chain = vec![cert.to_der().to_vec()];
TlsAcceptor::build_with_alpn(chain, key.to_sec1_pem(), vec![b"acme-tls/1".to_vec()])
}
/// Begin a new server-side TLS connection. The handshake is driven by
/// feeding the returned stream the bytes that arrive on the socket.
pub fn accept(&self) -> Result<TlsStream> {
let conn = Connection::server(&self.config).map_err(tls_err)?;
Ok(TlsStream { conn })
}
/// Build a fresh server [`QuicConfig`](purecrypto::quic::QuicConfig) for one
/// HTTP/3 connection, advertising the `h3` ALPN. A new config (and freshly
/// parsed signing key) is needed per connection because neither type is
/// reusable.
// `QuicConfig` is `#[non_exhaustive]`, so it can only be built by mutating
// a `default()` — hence the field reassignment.
#[cfg(feature = "h3")]
#[allow(clippy::field_reassign_with_default)]
pub fn quic_config(&self) -> Result<purecrypto::quic::QuicConfig> {
use purecrypto::quic::{QuicConfig, TransportParameters};
let key = load_signing_key(&self.key_pem)?;
let tls = Config::builder()
.rng(Arc::new(OsRng))
.tls_only()
.identity(self.chain.clone(), key)
.alpn(vec![b"h3".to_vec()])
.build();
let transport_params = TransportParameters {
max_idle_timeout_ms: Some(30_000),
max_udp_payload_size: Some(1500),
initial_max_data: Some(8 << 20),
initial_max_stream_data_bidi_local: Some(1 << 20),
initial_max_stream_data_bidi_remote: Some(1 << 20),
initial_max_stream_data_uni: Some(1 << 20),
initial_max_streams_bidi: Some(128),
initial_max_streams_uni: Some(8),
active_connection_id_limit: Some(2),
..TransportParameters::default()
};
let mut cfg = QuicConfig::default();
cfg.tls = tls;
cfg.transport_params = transport_params;
Ok(cfg)
}
}
impl std::fmt::Debug for TlsAcceptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TlsAcceptor").finish_non_exhaustive()
}
}
/// A [`TlsAcceptor`] that can be atomically swapped at runtime — e.g. on SIGHUP
/// when its certificate files change on disk — without dropping connections.
/// Cheap to clone (all clones share one cell). Every accepted connection reads
/// the acceptor currently in effect via [`current`](Self::current).
#[derive(Clone)]
pub struct ReloadableAcceptor {
current: Arc<RwLock<Arc<TlsAcceptor>>>,
/// (cert, key) paths to re-read on reload; `None` for sources with no file
/// backing (e.g. self-signed), whose `reload` is a no-op.
source: Option<Arc<(PathBuf, PathBuf)>>,
}
impl ReloadableAcceptor {
/// Build a reloadable acceptor from a PEM certificate file and key file,
/// remembering the paths so [`reload`](Self::reload) can re-read them.
pub fn from_pem_files(
cert: impl AsRef<Path>,
key: impl AsRef<Path>,
) -> Result<ReloadableAcceptor> {
let cert = cert.as_ref().to_path_buf();
let key = key.as_ref().to_path_buf();
let acceptor = TlsAcceptor::from_pem_files(&cert, &key)?;
Ok(ReloadableAcceptor {
current: Arc::new(RwLock::new(Arc::new(acceptor))),
source: Some(Arc::new((cert, key))),
})
}
/// Wrap a fixed acceptor with no file backing; its [`reload`](Self::reload)
/// is a no-op. Preserves existing callers that pass a bare [`TlsAcceptor`].
pub fn fixed(acceptor: TlsAcceptor) -> ReloadableAcceptor {
ReloadableAcceptor {
current: Arc::new(RwLock::new(Arc::new(acceptor))),
source: None,
}
}
/// A cheap `Arc` clone of the acceptor currently in effect. Poison-safe: a
/// panic elsewhere while holding the lock does not wedge this read.
pub fn current(&self) -> Arc<TlsAcceptor> {
Arc::clone(&self.current.read().unwrap_or_else(|e| e.into_inner()))
}
/// Re-read the certificate files and swap in a fresh acceptor. Fail-safe: on
/// a read/parse error the old acceptor is kept and the error returned (the
/// cell is neither poisoned nor cleared). A no-op `Ok(())` when there is no
/// file backing (a [`fixed`](Self::fixed) acceptor).
pub fn reload(&self) -> Result<()> {
let Some(source) = &self.source else {
return Ok(());
};
// Build the new acceptor before taking the write lock, so a failure
// leaves the old one untouched and readers are never blocked on I/O.
let fresh = TlsAcceptor::from_pem_files(&source.0, &source.1)?;
*self.current.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(fresh);
Ok(())
}
}
impl std::fmt::Debug for ReloadableAcceptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReloadableAcceptor")
.field("reloadable", &self.source.is_some())
.finish_non_exhaustive()
}
}
/// One server-side TLS connection: a sans-I/O wrapper over
/// [`purecrypto::tls::Connection`].
pub struct TlsStream {
conn: Connection,
}
impl TlsStream {
/// Feed ciphertext received from the socket into the TLS engine.
pub fn feed(&mut self, wire: &[u8]) -> Result<()> {
let mut off = 0;
while off < wire.len() {
let n = self.conn.feed(&wire[off..]).map_err(tls_err)?;
if n == 0 {
break; // engine buffered the rest internally
}
off += n;
}
Ok(())
}
/// Drain all currently available decrypted application bytes.
pub fn recv_all(&mut self) -> Result<Vec<u8>> {
let mut out = Vec::new();
loop {
let chunk = self.conn.recv().map_err(tls_err)?;
if chunk.is_empty() {
break;
}
out.extend_from_slice(&chunk);
}
Ok(out)
}
/// Queue application bytes to be encrypted and sent.
pub fn send(&mut self, app: &[u8]) -> Result<()> {
if !app.is_empty() {
self.conn.send(app).map_err(tls_err)?;
}
Ok(())
}
/// Drain all ciphertext that must be written to the socket (handshake
/// records and/or encrypted application data).
pub fn pop_all(&mut self) -> Result<Vec<u8>> {
let mut out = Vec::new();
loop {
let chunk = self.conn.pop().map_err(tls_err)?;
if chunk.is_empty() {
break;
}
out.extend_from_slice(&chunk);
}
Ok(out)
}
/// Whether the TLS handshake has completed.
pub fn is_handshake_complete(&self) -> bool {
self.conn.is_handshake_complete()
}
/// The ALPN protocol negotiated during the handshake (e.g. `b"h2"` or
/// `b"http/1.1"`), once available.
pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
self.conn.alpn_selected().map(|p| p.to_vec())
}
/// Begin a clean shutdown (queues a `close_notify`).
pub fn close(&mut self) -> Result<()> {
self.conn.close().map_err(tls_err)
}
}
// ---- PEM parsing ----
struct PemBlock {
label: String,
text: String,
der: Vec<u8>,
}
/// Split a PEM document into its constituent blocks.
fn pem_blocks(pem: &str) -> Vec<PemBlock> {
const BEGIN: &str = "-----BEGIN ";
let mut out = Vec::new();
let mut rest = pem;
while let Some(bpos) = rest.find(BEGIN) {
let after = &rest[bpos + BEGIN.len()..];
let Some(label_end) = after.find("-----") else {
break;
};
let label = after[..label_end].to_owned();
let end_marker = format!("-----END {label}-----");
let body_start = bpos + BEGIN.len() + label_end + "-----".len();
let Some(epos) = rest[body_start..].find(&end_marker) else {
break;
};
let block_end = body_start + epos + end_marker.len();
let text = rest[bpos..block_end].to_owned();
if let Some(der) = base64_decode(&rest[body_start..body_start + epos]) {
out.push(PemBlock { label, text, der });
}
rest = &rest[block_end..];
}
out
}
/// Decode standard-alphabet base64. Whitespace (including newlines) is ignored
/// so wrapped PEM bodies decode, and standard trailing `=` padding is accepted.
/// Stricter than a permissive decoder: interior `=` (padding followed by more
/// data), a lone trailing symbol, or non-zero dangling bits are all rejected so
/// corrupted or truncated PEM fails loudly rather than loading silently.
/// Returns `None` on invalid input.
fn base64_decode(s: &str) -> Option<Vec<u8>> {
fn val(c: u8) -> Option<u8> {
match c {
b'A'..=b'Z' => Some(c - b'A'),
b'a'..=b'z' => Some(c - b'a' + 26),
b'0'..=b'9' => Some(c - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
let mut out = Vec::new();
let mut acc: u32 = 0;
let mut bits = 0u32;
let mut padding_seen = false;
for &c in s.as_bytes() {
if c.is_ascii_whitespace() {
continue;
}
if c == b'=' {
// Only trailing padding is valid; remember we've seen it.
padding_seen = true;
continue;
}
// A data symbol after padding means an interior `=` — reject.
if padding_seen {
return None;
}
let v = val(c)? as u32;
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
}
}
// A leftover of 6 bits means a lone trailing symbol (invalid length); 2 or 4
// leftover bits are normal for padded input but must be zero (no dangling
// data bits beyond the last whole byte).
if bits == 6 {
return None;
}
if bits != 0 && acc & ((1 << bits) - 1) != 0 {
return None;
}
Some(out)
}
/// Warn loudly if the private-key file is group- or world-readable. A leaked
/// key is far more damaging than a leaked certificate, so over-permissive key
/// files deserve a visible operator warning. Non-fatal so existing deployments
/// keep working. No-op on non-Unix platforms (permission bits differ).
#[cfg(unix)]
fn warn_if_key_world_readable(path: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
if let Ok(meta) = std::fs::metadata(path) {
let mode = meta.permissions().mode();
// 0o077 = any group/other permission bit.
if mode & 0o077 != 0 {
eprintln!(
"httpsd: WARNING: private key file {} is group/other-accessible \
(mode {:#o}); restrict it to owner-only (chmod 600)",
path.display(),
mode & 0o777,
);
}
}
}
#[cfg(not(unix))]
fn warn_if_key_world_readable(_path: &std::path::Path) {}
/// Collect every `CERTIFICATE` block's DER, in order.
fn cert_chain_der(pem: &str) -> Result<Vec<Vec<u8>>> {
let chain: Vec<Vec<u8>> = pem_blocks(pem)
.into_iter()
.filter(|b| b.label == "CERTIFICATE")
.map(|b| b.der)
.collect();
Ok(chain)
}
/// Load the first private-key block as a TLS [`SigningKey`].
fn load_signing_key(pem: &str) -> Result<SigningKey> {
for block in pem_blocks(pem) {
match block.label.as_str() {
"RSA PRIVATE KEY" => {
// Map parse failures to a fixed, material-free message: the
// inner error's Debug output may echo (partial) key bytes,
// which must never reach logs.
let k = BoxedRsaPrivateKey::from_pkcs1_pem(&block.text)
.map_err(|_| Error::Tls("invalid RSA private key".into()))?;
return Ok(SigningKey::Rsa(k));
}
"EC PRIVATE KEY" => {
// Likewise, do not Debug-format the parse error for EC keys.
let k = BoxedEcdsaPrivateKey::from_sec1_pem(&block.text)
.map_err(|_| Error::Tls("invalid EC private key".into()))?;
return Ok(SigningKey::Ecdsa(k));
}
"PRIVATE KEY" => return signing_key_from_pkcs8(&block.text),
_ => continue,
}
}
Err(Error::Tls("no private key found in PEM".into()))
}
/// A PKCS#8 key may hold RSA, EC, or Ed25519 material; try each.
fn signing_key_from_pkcs8(text: &str) -> Result<SigningKey> {
if let Ok(k) = BoxedRsaPrivateKey::from_pkcs8_pem(text) {
return Ok(SigningKey::Rsa(k));
}
if let Ok(k) = BoxedEcdsaPrivateKey::from_pkcs8_pem(text) {
return Ok(SigningKey::Ecdsa(k));
}
if let Ok(k) = Ed25519PrivateKey::from_pkcs8_pem(text) {
return Ok(SigningKey::Ed25519(k));
}
Err(Error::Tls("PKCS#8 key is not RSA, EC, or Ed25519".into()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn self_signed_round_trips() {
let acceptor = TlsAcceptor::self_signed(&["localhost"]).expect("self-signed");
let _stream = acceptor.accept().expect("accept");
}
#[test]
fn reloadable_fixed_is_usable_and_reload_is_noop() {
let acc = ReloadableAcceptor::fixed(
TlsAcceptor::self_signed(&["localhost"]).expect("self-signed"),
);
// `current()` yields a usable acceptor.
let _stream = acc.current().accept().expect("accept");
// A fixed acceptor has no file backing: reload is a no-op success.
acc.reload().expect("no-op reload");
let _again = acc.current().accept().expect("accept after reload");
}
/// Generate a self-signed cert + key and return them as PEM strings, so a
/// file-based reload test has real material to write. `TlsAcceptor::self_signed`
/// does not expose PEM, so build the pieces directly: the SEC1 key PEM comes
/// from the key, and the leaf DER is wrapped into a `CERTIFICATE` PEM block.
#[cfg(test)]
fn self_signed_pem(host: &str) -> (String, String) {
let mut rng = OsRng;
let key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
let key_pem = key.to_sec1_pem();
let name = DistinguishedName::common_name(host);
let validity = Validity::new(
Time::utc(2020, 1, 1, 0, 0, 0),
Time::utc(2040, 1, 1, 0, 0, 0),
);
let any = AnyPrivateKey::Ecdsa(key);
let cert = Certificate::self_signed_with_sans(&any, &name, &validity, 1, false, &[host])
.expect("self-sign");
let cert_pem = der_to_pem("CERTIFICATE", cert.to_der());
(cert_pem, key_pem)
}
/// Wrap DER bytes in a PEM block with the given label (standard 64-col base64).
#[cfg(test)]
fn der_to_pem(label: &str, der: &[u8]) -> String {
const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut b64 = String::new();
for chunk in der.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
b64.push(ALPHA[(n >> 18 & 63) as usize] as char);
b64.push(ALPHA[(n >> 12 & 63) as usize] as char);
b64.push(if chunk.len() > 1 {
ALPHA[(n >> 6 & 63) as usize] as char
} else {
'='
});
b64.push(if chunk.len() > 2 {
ALPHA[(n & 63) as usize] as char
} else {
'='
});
}
let mut out = format!("-----BEGIN {label}-----\n");
for line in b64.as_bytes().chunks(64) {
out.push_str(std::str::from_utf8(line).unwrap());
out.push('\n');
}
out.push_str(&format!("-----END {label}-----\n"));
out
}
#[test]
fn reloadable_from_files_reloads_and_keeps_old_on_missing() {
let dir = std::env::temp_dir().join(format!("httpsd-reload-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("mkdir");
let cert_path = dir.join("cert.pem");
let key_path = dir.join("key.pem");
let (cert_pem, key_pem) = self_signed_pem("localhost");
std::fs::write(&cert_path, &cert_pem).expect("write cert");
std::fs::write(&key_path, &key_pem).expect("write key");
let acc = ReloadableAcceptor::from_pem_files(&cert_path, &key_path).expect("build");
acc.current().accept().expect("accept before reload");
// Rewrite the files with a fresh identity and reload: it succeeds.
let (cert2, key2) = self_signed_pem("localhost");
std::fs::write(&cert_path, &cert2).expect("rewrite cert");
std::fs::write(&key_path, &key2).expect("rewrite key");
acc.reload().expect("reload after rewrite");
acc.current().accept().expect("accept after reload");
// Now delete a file: reload fails, but the old acceptor is kept usable.
std::fs::remove_file(&cert_path).expect("rm cert");
assert!(acc.reload().is_err(), "reload with missing cert must Err");
acc.current()
.accept()
.expect("old acceptor still usable after failed reload");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn base64_accepts_valid_padding_and_whitespace() {
// "Man" -> "TWFu" (no padding)
assert_eq!(base64_decode("TWFu"), Some(b"Man".to_vec()));
// "Ma" -> "TWE=" (one pad), "M" -> "TQ==" (two pads)
assert_eq!(base64_decode("TWE="), Some(b"Ma".to_vec()));
assert_eq!(base64_decode("TQ=="), Some(b"M".to_vec()));
// Wrapped with newlines/whitespace still decodes.
assert_eq!(base64_decode("TW\n Fu\r\n"), Some(b"Man".to_vec()));
}
#[test]
fn base64_rejects_malformed() {
// Interior padding.
assert_eq!(base64_decode("TW=Fu"), None);
// Lone trailing symbol (invalid length).
assert_eq!(base64_decode("TWFuQ"), None);
// Non-zero dangling bits: "TX==" has a set low bit beyond the byte.
assert_eq!(base64_decode("TX=="), None);
// Out-of-alphabet character.
assert_eq!(base64_decode("TW*u"), None);
}
#[test]
fn pem_block_splitting() {
let pem = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
let blocks = pem_blocks(pem);
assert_eq!(blocks.len(), 1);
assert_eq!(blocks[0].label, "CERTIFICATE");
assert_eq!(blocks[0].der, vec![0, 0, 0]);
}
}