polyc-crypto 2026.9.0

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
//! Shared CA-bundle PEM loading for TLS trust stores.
//!
//! Every trust-store consumer (the #1167
//! control-plane<->harness mTLS pair) needs the same fail-closed
//! "read this PEM file, add every certificate in it to a root store, error
//! loudly if the file is unreadable or carries none" shape. One shared
//! loader means that failure-loudness behavior can't drift between call
//! sites.

use std::path::Path;
use std::sync::Arc;

use rustls::RootCertStore;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};

/// A CA bundle failed to load into a [`RootCertStore`].
#[derive(Debug, thiserror::Error)]
pub enum CaLoadError {
    /// The file couldn't be opened or read.
    #[error("read CA file {path}: {source}")]
    Read {
        /// The path that failed to read.
        path: String,
        /// The underlying I/O/PEM-decode error.
        #[source]
        source: rustls::pki_types::pem::Error,
    },
    /// A certificate in the file was structurally invalid.
    #[error("parse CA certificate in {path}: {source}")]
    Parse {
        /// The file the invalid certificate came from.
        path: String,
        /// The underlying PEM-decode error.
        #[source]
        source: rustls::pki_types::pem::Error,
    },
    /// A certificate was well-formed but rustls rejected it (e.g. an
    /// unsupported signature algorithm).
    #[error("add CA certificate from {path} to root store: {source}")]
    Reject {
        /// The file the rejected certificate came from.
        path: String,
        /// The underlying rustls error.
        #[source]
        source: rustls::Error,
    },
    /// The file parsed but named zero certificates — an explicitly
    /// configured CA that's empty or malformed in a way that doesn't error.
    #[error("CA file {path} contained no certificates")]
    Empty {
        /// The empty file's path.
        path: String,
    },
}

/// Load every certificate in the PEM file `path` into `roots`.
///
/// Fail-closed: refusing to silently produce a verifier that trusts nothing
/// (which would reject every real connection with no signal *why*) is the
/// caller's job — this function only reports the file-level problem
/// (unreadable, unparseable, empty) so the caller can refuse to start rather
/// than guess.
///
/// # Errors
///
/// Returns [`CaLoadError`] if the file can't be read, contains an
/// unparseable or rustls-rejected certificate, or names no certificates at
/// all.
pub fn load_ca_into(roots: &mut RootCertStore, path: &str) -> Result<(), CaLoadError> {
    let mut added = 0usize;
    for cert in CertificateDer::pem_file_iter(path).map_err(|source| CaLoadError::Read {
        path: path.to_owned(),
        source,
    })? {
        let cert = cert.map_err(|source| CaLoadError::Parse {
            path: path.to_owned(),
            source,
        })?;
        roots.add(cert).map_err(|source| CaLoadError::Reject {
            path: path.to_owned(),
            source,
        })?;
        added += 1;
    }
    if added == 0 {
        return Err(CaLoadError::Empty {
            path: path.to_owned(),
        });
    }
    Ok(())
}

/// Load every certificate in the in-memory PEM bundle `pem` into `roots`.
///
/// Same fail-closed contract and error shape as [`load_ca_into`], for a CA
/// bundle already held in memory (e.g. read from a Kubernetes Secret) rather
/// than a file on disk. `label` identifies the source in error messages
/// (there's no path to report).
///
/// # Errors
///
/// Returns [`CaLoadError`] if `pem` contains an unparseable or
/// rustls-rejected certificate, or names no certificates at all.
pub fn load_ca_pem_into(
    roots: &mut RootCertStore,
    label: &str,
    pem: &[u8],
) -> Result<(), CaLoadError> {
    let mut added = 0usize;
    for cert in CertificateDer::pem_slice_iter(pem) {
        let cert = cert.map_err(|source| CaLoadError::Parse {
            path: label.to_owned(),
            source,
        })?;
        roots.add(cert).map_err(|source| CaLoadError::Reject {
            path: label.to_owned(),
            source,
        })?;
        added += 1;
    }
    if added == 0 {
        return Err(CaLoadError::Empty {
            path: label.to_owned(),
        });
    }
    Ok(())
}

/// Which piece of a mutual-TLS client identity one load failure names.
///
/// An enum rather than a string, so the set a reader is promised and the set
/// [`mutual_tls_client_config`] emits cannot drift apart: adding a piece here
/// is a compile error at every match over it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentityPart {
    /// The authority bundle the peer's leaf is verified against. A client
    /// verifies the listener with it; a listener verifies the caller.
    AuthorityCertificate,
    /// This side's own certificate chain, whichever side that is.
    OwnCertificate,
    /// The private key that chain is presented with.
    OwnKey,
    /// The assembled pair, which rustls refused as a unit rather than naming
    /// either half.
    CertificateAndKey,
}

impl std::fmt::Display for IdentityPart {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::AuthorityCertificate => "authority certificate",
            Self::OwnCertificate => "certificate",
            Self::OwnKey => "private key",
            Self::CertificateAndKey => "certificate and key",
        })
    }
}

/// A mutual-TLS client identity failed to load.
///
/// `subject` names whose identity it is, in the caller's own words, so one
/// shared loader can serve several callers without any of them reporting a
/// failure as someone else's, and `part` names which piece of that identity
/// went wrong. The cause is boxed to keep the error small: `rustls::Error`
/// alone is wide enough that carrying [`ClientIdentityCause`] inline trips
/// `clippy::result_large_err` on every `Result` in this module.
#[derive(Debug, thiserror::Error)]
#[error("the {part} for the {subject} at {path} did not load")]
pub struct ClientIdentityError {
    /// Whose identity was being loaded.
    subject: String,
    /// Which piece of that identity went wrong.
    part: IdentityPart,
    /// The path the piece was read from.
    path: String,
    /// What actually went wrong.
    #[source]
    source: Box<ClientIdentityCause>,
}

impl ClientIdentityError {
    /// Returns which piece of the identity failed.
    #[must_use]
    pub const fn part(&self) -> IdentityPart {
        self.part
    }

    /// Returns what went wrong with that piece.
    #[must_use]
    pub const fn cause(&self) -> &ClientIdentityCause {
        &self.source
    }
}

/// What went wrong with one piece of a mutual-TLS client identity.
#[derive(Debug, thiserror::Error)]
pub enum ClientIdentityCause {
    /// The authority bundle did not yield a usable trust store.
    #[error(transparent)]
    Authority(#[from] CaLoadError),
    /// The file could not be opened or read.
    #[error(transparent)]
    Read(#[from] std::io::Error),
    /// The PEM contents did not decode.
    #[error("{0}")]
    Parse(String),
    /// rustls refused the assembled certificate and key.
    #[error(transparent)]
    Build(#[from] rustls::Error),
}

/// Builds the mutual-TLS client configuration `subject` presents to a listener
/// that admits callers by client certificate.
///
/// One loader, because a second hand-rolled copy is how two callers of the same
/// authenticated listener come to disagree about what they present: `ca` is the
/// authority the server's leaf is verified against, and `cert`/`key` are the
/// caller's own leaf, whose digest is the workload identity the listener admits
/// it under. Hostname verification stays the ordinary one — the server's leaf
/// carries the name it is dialed by.
///
/// Fail-closed throughout: an unreadable, unparseable, or empty piece is an
/// error rather than a configuration that trusts nothing and refuses every real
/// connection with no signal why.
///
/// # Errors
///
/// Returns [`ClientIdentityError`] when the authority bundle does not load,
/// when either the certificate chain or the private key cannot be read or
/// parsed, or when rustls refuses the assembled pair.
pub fn mutual_tls_client_config(
    subject: &str,
    ca: &Path,
    cert: &Path,
    key: &Path,
) -> Result<Arc<rustls::ClientConfig>, ClientIdentityError> {
    let fail = |part: IdentityPart, path: &Path, cause: ClientIdentityCause| ClientIdentityError {
        subject: subject.to_owned(),
        part,
        path: path.display().to_string(),
        source: Box::new(cause),
    };
    let read = |path: &Path, part: IdentityPart| -> Result<Vec<u8>, ClientIdentityError> {
        std::fs::read(path).map_err(|err| fail(part, path, err.into()))
    };

    let ca_pem = read(ca, IdentityPart::AuthorityCertificate)?;
    let mut roots = RootCertStore::empty();
    load_ca_pem_into(&mut roots, subject, &ca_pem)
        .map_err(|err| fail(IdentityPart::AuthorityCertificate, ca, err.into()))?;

    let cert_pem = read(cert, IdentityPart::OwnCertificate)?;
    let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(&cert_pem)
        .collect::<Result<_, _>>()
        .map_err(|err| {
            fail(
                IdentityPart::OwnCertificate,
                cert,
                ClientIdentityCause::Parse(err.to_string()),
            )
        })?;

    let key_pem = read(key, IdentityPart::OwnKey)?;
    let private = PrivateKeyDer::from_pem_slice(&key_pem).map_err(|err| {
        fail(
            IdentityPart::OwnKey,
            key,
            ClientIdentityCause::Parse(err.to_string()),
        )
    })?;

    rustls::ClientConfig::builder()
        .with_root_certificates(roots)
        .with_client_auth_cert(chain, private)
        .map(Arc::new)
        .map_err(|err| fail(IdentityPart::CertificateAndKey, cert, err.into()))
}

/// Failure building a listener's mutual-TLS configuration.
///
/// `Display` names the part and the path. A path is deployment layout, not a
/// secret, and a startup failure that does not say which file it could not
/// read is not actionable.
#[derive(Debug, thiserror::Error)]
#[error("{subject}: cannot use the {part} at {path}")]
pub struct ServerIdentityError {
    /// Which listener this configuration belongs to.
    pub subject: String,
    /// Which part of the identity failed.
    pub part: IdentityPart,
    /// The path that failed.
    pub path: String,
}

/// Builds one listener's mutual-TLS [`rustls::ServerConfig`].
///
/// Presents `cert`/`key` as this workload's identity, and requires every
/// caller to present a certificate that chains to `ca`. Client authentication
/// is mandatory: `WebPkiClientVerifier`'s builder defaults to requiring a
/// client certificate, and the anonymous-allowed mode is a separate explicit
/// opt-in no listener built here takes.
///
/// ALPN is pinned to `h2` alone. The transport speaks whatever ALPN selects,
/// and advertising nothing else is what keeps a connection from silently
/// downgrading to HTTP/1.1 rather than failing closed.
///
/// One builder, shared by the planes that serve a mutual-TLS listener through
/// it. A second copy could differ about whether a client certificate is
/// required, and a listener that accepted an anonymous caller would look
/// identical from the outside until someone connected without one.
///
/// `polyc-harness` still builds its own; it is not migrated here.
///
/// # Errors
///
/// Returns [`ServerIdentityError`] naming the part and path that could not be
/// read, parsed, or paired.
pub fn mutual_tls_server_config(
    subject: &str,
    ca: &Path,
    cert: &Path,
    key: &Path,
) -> Result<Arc<rustls::ServerConfig>, ServerIdentityError> {
    let fail = |part: IdentityPart, path: &Path| ServerIdentityError {
        subject: subject.to_owned(),
        part,
        path: path.display().to_string(),
    };

    let mut roots = RootCertStore::empty();
    load_ca_into(&mut roots, &ca.display().to_string())
        .map_err(|_unreadable| fail(IdentityPart::AuthorityCertificate, ca))?;
    let roots = Arc::new(roots);

    let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert)
        .map_err(|_unreadable| fail(IdentityPart::OwnCertificate, cert))?
        .collect::<Result<_, _>>()
        .map_err(|_unparseable| fail(IdentityPart::OwnCertificate, cert))?;
    if chain.is_empty() {
        return Err(fail(IdentityPart::OwnCertificate, cert));
    }
    let private =
        PrivateKeyDer::from_pem_file(key).map_err(|_unreadable| fail(IdentityPart::OwnKey, key))?;

    let verifier = rustls::server::WebPkiClientVerifier::builder(roots)
        .build()
        .map_err(|_unusable| fail(IdentityPart::AuthorityCertificate, ca))?;
    let mut config = rustls::ServerConfig::builder()
        .with_client_cert_verifier(verifier)
        .with_single_cert(chain, private)
        // rustls refused the pair, not either half. Naming the key alone would
        // point an operator at the wrong file.
        .map_err(|_mismatched| fail(IdentityPart::CertificateAndKey, cert))?;
    config.alpn_protocols = vec![b"h2".to_vec()];
    Ok(Arc::new(config))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    #[test]
    fn missing_file_is_a_read_error() {
        let mut roots = RootCertStore::empty();
        let err = load_ca_into(&mut roots, "/nonexistent/ca.pem").unwrap_err();
        assert!(matches!(err, CaLoadError::Read { .. }), "got {err:?}");
        assert!(err.to_string().contains("ca.pem"), "got: {err}");
    }

    #[test]
    fn empty_file_is_an_empty_error() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("polyc-crypto-tls-test-{}.pem", std::process::id()));
        std::fs::write(&path, b"").unwrap();
        let mut roots = RootCertStore::empty();
        let err = load_ca_into(&mut roots, path.to_str().unwrap()).unwrap_err();
        std::fs::remove_file(&path).ok();
        assert!(matches!(err, CaLoadError::Empty { .. }), "got {err:?}");
    }

    #[test]
    fn empty_pem_bytes_is_an_empty_error() {
        let mut roots = RootCertStore::empty();
        let err = load_ca_pem_into(&mut roots, "test CA", b"").unwrap_err();
        assert!(matches!(err, CaLoadError::Empty { .. }), "got {err:?}");
        assert!(err.to_string().contains("test CA"), "got: {err}");
    }

    #[test]
    fn a_missing_client_identity_names_its_subject_and_the_piece_that_is_gone() {
        let missing = Path::new("/nonexistent/polychrome/ca.crt");
        let err = mutual_tls_client_config("State client", missing, missing, missing).unwrap_err();
        assert_eq!(err.part(), IdentityPart::AuthorityCertificate);
        assert!(
            matches!(err.cause(), ClientIdentityCause::Read(_)),
            "got {:?}",
            err.cause()
        );
        let rendered = err.to_string();
        assert_eq!(
            rendered,
            "the authority certificate for the State client at /nonexistent/polychrome/ca.crt \
             did not load"
        );
    }

    /// Every piece reads as a sentence beside its subject.
    ///
    /// The subject is a caller's own noun phrase and the piece is this
    /// module's, so the two meet in one line a person reads. The earlier
    /// wording put them adjacent and produced "the State client client
    /// certificate"; this pins that they no longer collide, for every piece
    /// rather than the one an easy-to-reach test happens to hit.
    #[test]
    fn every_identity_piece_reads_beside_its_subject() {
        for (part, expected) in [
            (
                IdentityPart::AuthorityCertificate,
                "the authority certificate for the State client at /x did not load",
            ),
            (
                IdentityPart::OwnCertificate,
                "the certificate for the State client at /x did not load",
            ),
            (
                IdentityPart::OwnKey,
                "the private key for the State client at /x did not load",
            ),
            (
                IdentityPart::CertificateAndKey,
                "the certificate and key for the State client at /x did not load",
            ),
        ] {
            let err = ClientIdentityError {
                subject: "State client".to_owned(),
                part,
                path: "/x".to_owned(),
                source: Box::new(ClientIdentityCause::Parse("unused".to_owned())),
            };
            assert_eq!(err.to_string(), expected);
        }
    }

    #[test]
    fn an_empty_authority_bundle_is_refused_rather_than_trusting_nothing() {
        let dir = std::env::temp_dir();
        let ca = dir.join(format!("polyc-crypto-mtls-{}.pem", std::process::id()));
        std::fs::write(&ca, b"").unwrap();
        let err = mutual_tls_client_config("State client", &ca, &ca, &ca).unwrap_err();
        std::fs::remove_file(&ca).ok();
        assert_eq!(err.part(), IdentityPart::AuthorityCertificate);
        assert!(
            matches!(
                err.cause(),
                ClientIdentityCause::Authority(CaLoadError::Empty { .. })
            ),
            "got {:?}",
            err.cause()
        );
    }
}