Skip to main content

feldera_mtls/
lib.rs

1//! Client certificate identities of Feldera components, and the server side of checking
2//! them: the compiler, runner, pipeline and coordinator servers with
3//! `--require-client-certificates`.
4//!
5//! The control plane presents a certificate with the URI SAN [`CONTROL_PLANE_CERTIFICATE_URI`],
6//! a pipeline one with [`pipeline_certificate_uri`]. The private CA signs both. Pipelines may
7//! also admit external clients, such as sidecars, by a URI SAN outside `urn:feldera:`.
8
9use actix_tls::accept::rustls_0_23::TlsStream;
10use actix_web::body::{BoxBody, MessageBody};
11use actix_web::dev::{Extensions, ServiceRequest, ServiceResponse};
12use actix_web::http::{Method, StatusCode};
13use actix_web::middleware::Next;
14use actix_web::rt::net::TcpStream;
15use actix_web::{HttpResponse, ResponseError};
16use feldera_types::error::{DetailedError, ErrorResponse};
17use rustls::RootCertStore;
18use rustls::crypto::CryptoProvider;
19use rustls::pki_types::CertificateDer;
20use rustls::server::WebPkiClientVerifier;
21use rustls::server::danger::ClientCertVerifier;
22use serde::Serialize;
23use std::any::Any;
24use std::borrow::Cow;
25use std::fmt;
26use std::sync::Arc;
27use tracing::warn;
28use uuid::Uuid;
29
30/// Environment variable that makes the compiler, runner, pipeline and coordinator servers
31/// require client certificates.
32pub const REQUIRE_CLIENT_CERTIFICATES_ENV: &str = "FELDERA_REQUIRE_CLIENT_CERTIFICATES";
33
34/// Environment variable with the URI SANs of the extra clients that pipelines admit.
35pub const EXTRA_CLIENT_CERTIFICATE_URIS_ENV: &str = "FELDERA_EXTRA_CLIENT_CERTIFICATE_URIS";
36
37/// URI SAN of the control-plane client certificate (API server, runner, compiler replicas).
38pub const CONTROL_PLANE_CERTIFICATE_URI: &str = "urn:feldera:control-plane";
39
40/// Prefix of the URI SAN of a pipeline certificate. The pipeline id follows it.
41const PIPELINE_CERTIFICATE_URI_PREFIX: &str = "urn:feldera:pipeline:";
42
43/// Namespace of the URI SANs of Feldera components. URN namespaces are case-insensitive.
44const FELDERA_URI_PREFIX: &str = "urn:feldera:";
45
46fn is_feldera_uri(uri: &str) -> bool {
47    uri.get(..FELDERA_URI_PREFIX.len())
48        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(FELDERA_URI_PREFIX))
49}
50
51/// URI SAN of the certificate of pipeline `pipeline_id`.
52pub fn pipeline_certificate_uri(pipeline_id: Uuid) -> String {
53    format!("{PIPELINE_CERTIFICATE_URI_PREFIX}{pipeline_id}")
54}
55
56/// Who called a server, according to the client certificate of the connection.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Caller {
59    /// No client certificate, or a certificate without exactly one identity.
60    Anonymous,
61    ControlPlane,
62    Pipeline(Uuid),
63    /// A client outside Feldera, by its URI SAN.
64    External(String),
65}
66
67impl Caller {
68    /// Maps a certificate to its caller. Only a certificate that the TLS handshake verified
69    /// proves the identity.
70    pub fn from_certificate(cert: &CertificateDer<'_>) -> Self {
71        let Ok(cert) = webpki::EndEntityCert::try_from(cert) else {
72            return Self::Anonymous;
73        };
74        let mut callers = cert.valid_uri_names().filter_map(|uri| {
75            if uri == CONTROL_PLANE_CERTIFICATE_URI {
76                Some(Self::ControlPlane)
77            } else if let Some(id) = uri.strip_prefix(PIPELINE_CERTIFICATE_URI_PREFIX) {
78                Uuid::parse_str(id).ok().map(Self::Pipeline)
79            } else if is_feldera_uri(uri) {
80                // Not an identity that Feldera issues, in any spelling.
81                None
82            } else {
83                Some(Self::External(uri.to_string()))
84            }
85        });
86        match (callers.next(), callers.next()) {
87            (Some(caller), None) => caller,
88            // A certificate with two identities is ambiguous, so it grants neither.
89            _ => Self::Anonymous,
90        }
91    }
92
93    /// Stores the caller of a new connection, for [`Caller::of`]. Pass it to
94    /// `HttpServer::on_connect`.
95    pub fn record(connection: &dyn Any, extensions: &mut Extensions) {
96        let caller = connection
97            .downcast_ref::<TlsStream<TcpStream>>()
98            .and_then(|stream| stream.get_ref().1.peer_certificates())
99            .and_then(|certs| certs.first())
100            .map_or(Self::Anonymous, Self::from_certificate);
101        extensions.insert(caller);
102    }
103
104    /// The caller of the connection that carried `req`.
105    pub fn of(req: &ServiceRequest) -> Self {
106        req.conn_data::<Self>().cloned().unwrap_or(Self::Anonymous)
107    }
108}
109
110/// Runs `next` if `is_allowed` admits the request for the caller of its connection, and
111/// refuses it with 401 (no identity) or 403 (another identity) otherwise.
112pub async fn authorize<B: MessageBody>(
113    server: &'static str,
114    is_allowed: impl FnOnce(&Caller, &Method, &str) -> bool,
115    req: ServiceRequest,
116    next: Next<B>,
117) -> Result<ServiceResponse<B>, actix_web::Error> {
118    let caller = Caller::of(&req);
119    if is_allowed(&caller, req.method(), req.path()) {
120        return next.call(req).await;
121    }
122    let method = req.method().to_string();
123    let path = req.path().to_string();
124    warn!("The {server} server refused {method} {path} from {caller:?}");
125    Err(match caller {
126        Caller::Anonymous => ClientAuthError::ClientCertificateRequired {
127            server,
128            method,
129            path,
130        },
131        _ => ClientAuthError::CallerNotAllowed {
132            server,
133            caller: format!("{caller:?}"),
134            method,
135            path,
136        },
137    }
138    .into())
139}
140
141/// A request that a server refused because of the client certificate of its connection.
142#[derive(Debug, Serialize)]
143#[serde(untagged)]
144pub enum ClientAuthError {
145    ClientCertificateRequired {
146        server: &'static str,
147        method: String,
148        path: String,
149    },
150    CallerNotAllowed {
151        server: &'static str,
152        caller: String,
153        method: String,
154        path: String,
155    },
156}
157
158impl DetailedError for ClientAuthError {
159    fn error_code(&self) -> Cow<'static, str> {
160        match self {
161            Self::ClientCertificateRequired { .. } => Cow::from("ClientCertificateRequired"),
162            Self::CallerNotAllowed { .. } => Cow::from("CallerNotAllowed"),
163        }
164    }
165}
166
167impl fmt::Display for ClientAuthError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            Self::ClientCertificateRequired {
171                server,
172                method,
173                path,
174            } => write!(
175                f,
176                "The {server} server requires a client certificate for {method} {path}: present a certificate that the private CA signed (control plane: --https-client-cert-path)"
177            ),
178            Self::CallerNotAllowed {
179                server,
180                caller,
181                method,
182                path,
183            } => write!(
184                f,
185                "{caller} may not send {method} {path} to the {server} server"
186            ),
187        }
188    }
189}
190
191impl std::error::Error for ClientAuthError {}
192
193impl ResponseError for ClientAuthError {
194    fn status_code(&self) -> StatusCode {
195        match self {
196            Self::ClientCertificateRequired { .. } => StatusCode::UNAUTHORIZED,
197            Self::CallerNotAllowed { .. } => StatusCode::FORBIDDEN,
198        }
199    }
200
201    fn error_response(&self) -> HttpResponse<BoxBody> {
202        HttpResponse::build(self.status_code()).json(ErrorResponse::from_error_nolog(self))
203    }
204}
205
206/// The rustls provider that the process installed, or the aws-lc-rs one that Feldera binaries
207/// install. With several rustls crypto features compiled in, rustls has no default unless the
208/// process installed one.
209pub fn crypto_provider() -> Arc<CryptoProvider> {
210    CryptoProvider::get_default()
211        .cloned()
212        .unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
213}
214
215/// Builds a client certificate verifier that trusts only the first certificate of `ca_chain`,
216/// the private CA that issues client certificates, so a client may send its leaf certificate
217/// without the chain. The rest of the chain is not trusted, because other CAs under the same
218/// root could issue Feldera identities. Clients without a certificate may connect, so that
219/// they get an actionable 401 or reach routes open to everyone.
220pub fn client_certificate_verifier(
221    ca_chain: &[CertificateDer<'static>],
222) -> Result<Arc<dyn ClientCertVerifier>, String> {
223    let issuing_ca = ca_chain
224        .first()
225        .ok_or("the CA chain holds no certificate")?;
226    let mut roots = RootCertStore::empty();
227    roots
228        .add(issuing_ca.clone())
229        .map_err(|e| format!("invalid CA certificate: {e}"))?;
230    WebPkiClientVerifier::builder_with_provider(Arc::new(roots), crypto_provider())
231        .allow_unauthenticated()
232        .build()
233        .map_err(|e| format!("client certificate verifier: {e}"))
234}
235
236/// The client verifier and admitted callers of a pipeline or coordinator server. Its
237/// certificate chain names the pipeline in the leaf and ends with the private CA chain, which
238/// the runner appends, so the server needs no separate CA file.
239pub struct PipelineClientAuth {
240    pub own: Caller,
241    /// URI SANs of the external clients that the server admits like the control plane.
242    pub extra_client_uris: Vec<String>,
243    pub verifier: Arc<dyn ClientCertVerifier>,
244}
245
246impl PipelineClientAuth {
247    pub fn from_chain(
248        chain: &[CertificateDer<'static>],
249        extra_client_uris: &[String],
250    ) -> Result<Self, String> {
251        // Feldera mints `urn:feldera:` URIs for its own components, so admitting one here
252        // could admit another pipeline.
253        if let Some(uri) = extra_client_uris
254            .iter()
255            .find(|uri| uri.is_empty() || uri.contains(char::is_whitespace) || is_feldera_uri(uri))
256        {
257            return Err(format!(
258                "extra client URI '{uri}' must be non-empty, have no whitespace, and lie outside {FELDERA_URI_PREFIX}, which Feldera components use"
259            ));
260        }
261        let (leaf, ca_chain) = chain
262            .split_first()
263            .ok_or("the certificate file holds no certificate")?;
264        let own @ Caller::Pipeline(_) = Caller::from_certificate(leaf) else {
265            return Err(format!(
266                "the certificate names no pipeline: client certificates need the URI SAN {PIPELINE_CERTIFICATE_URI_PREFIX}<id>, which the runner adds"
267            ));
268        };
269        if ca_chain.is_empty() {
270            return Err(
271                "the certificate file holds no CA chain after the leaf to verify clients with"
272                    .to_string(),
273            );
274        }
275        Ok(Self {
276            own,
277            extra_client_uris: extra_client_uris.to_vec(),
278            verifier: client_certificate_verifier(ca_chain)?,
279        })
280    }
281
282    /// Whether a pipeline or coordinator server admits `caller`: the control plane, the
283    /// pipeline itself (the coordinator calls the hosts of its pipeline), or a listed external
284    /// client.
285    pub fn is_allowed(&self, caller: &Caller) -> bool {
286        match caller {
287            Caller::ControlPlane => true,
288            Caller::Pipeline(_) => *caller == self.own,
289            Caller::External(uri) => self.extra_client_uris.contains(uri),
290            Caller::Anonymous => false,
291        }
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::{
298        CONTROL_PLANE_CERTIFICATE_URI, Caller, PipelineClientAuth, client_certificate_verifier,
299        pipeline_certificate_uri,
300    };
301    use rcgen::{
302        BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer,
303        KeyPair, SanType,
304    };
305    use rustls::pki_types::{CertificateDer, UnixTime};
306    use uuid::Uuid;
307
308    const PIPELINE_A: Uuid = Uuid::from_u128(0xa);
309    const PIPELINE_B: Uuid = Uuid::from_u128(0xb);
310
311    fn ca() -> (Issuer<'static, KeyPair>, CertificateDer<'static>) {
312        named_ca("ca", None)
313    }
314
315    /// A CA certificate signed by `parent`, or self-signed without one.
316    fn named_ca(
317        name: &str,
318        parent: Option<&Issuer<'static, KeyPair>>,
319    ) -> (Issuer<'static, KeyPair>, CertificateDer<'static>) {
320        let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
321        params.distinguished_name.push(DnType::CommonName, name);
322        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
323        let key = KeyPair::generate().unwrap();
324        let cert = match parent {
325            Some(parent) => params.signed_by(&key, parent),
326            None => params.self_signed(&key),
327        }
328        .unwrap();
329        (Issuer::new(params, key), cert.der().clone())
330    }
331
332    fn leaf(issuer: &Issuer<'static, KeyPair>, uris: &[String]) -> CertificateDer<'static> {
333        let mut params = CertificateParams::default();
334        params.subject_alt_names = uris
335            .iter()
336            .map(|uri| SanType::URI(uri.as_str().try_into().unwrap()))
337            .collect();
338        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
339        let key = KeyPair::generate().unwrap();
340        params.signed_by(&key, issuer).unwrap().der().clone()
341    }
342
343    fn caller_of(uris: &[String]) -> Caller {
344        Caller::from_certificate(&leaf(&ca().0, uris))
345    }
346
347    const SIDECAR: &str = "urn:example:sidecar";
348
349    /// Certificate URIs map to callers, and a certificate with two identities grants neither.
350    #[test]
351    fn caller_from_certificate() {
352        let control_plane = CONTROL_PLANE_CERTIFICATE_URI.to_string();
353        let a = pipeline_certificate_uri(PIPELINE_A);
354        let b = pipeline_certificate_uri(PIPELINE_B);
355        let sidecar = SIDECAR.to_string();
356        assert_eq!(
357            caller_of(std::slice::from_ref(&control_plane)),
358            Caller::ControlPlane
359        );
360        assert_eq!(
361            caller_of(std::slice::from_ref(&a)),
362            Caller::Pipeline(PIPELINE_A)
363        );
364        assert_eq!(caller_of(&[]), Caller::Anonymous);
365        assert_eq!(
366            caller_of(&["urn:feldera:pipeline:not-a-uuid".to_string()]),
367            Caller::Anonymous
368        );
369        assert_eq!(
370            caller_of(std::slice::from_ref(&sidecar)),
371            Caller::External(SIDECAR.to_string())
372        );
373        assert_eq!(
374            caller_of(&[format!("URN:Feldera:pipeline:{PIPELINE_A}")]),
375            Caller::Anonymous
376        );
377        assert_eq!(
378            caller_of(&["urn:feldera:sidecar".to_string()]),
379            Caller::Anonymous
380        );
381        assert_eq!(
382            caller_of(&[control_plane.clone(), a.clone()]),
383            Caller::Anonymous
384        );
385        assert_eq!(caller_of(&[control_plane, sidecar]), Caller::Anonymous);
386        assert_eq!(caller_of(&[a, b]), Caller::Anonymous);
387    }
388
389    /// A pipeline server admits the control plane, its own pipeline and the listed external
390    /// clients, and needs a CA chain and a pipeline identity in its own certificate file.
391    #[test]
392    fn pipeline_client_auth() {
393        let (issuer, ca_cert) = ca();
394        let own_leaf = leaf(&issuer, &[pipeline_certificate_uri(PIPELINE_A)]);
395        let chain = [own_leaf.clone(), ca_cert.clone()];
396        let auth = PipelineClientAuth::from_chain(&chain, &[SIDECAR.to_string()]).unwrap();
397        assert!(auth.is_allowed(&Caller::ControlPlane));
398        assert!(auth.is_allowed(&Caller::Pipeline(PIPELINE_A)));
399        assert!(auth.is_allowed(&Caller::External(SIDECAR.to_string())));
400        assert!(!auth.is_allowed(&Caller::External("urn:example:other".to_string())));
401        assert!(!auth.is_allowed(&Caller::Pipeline(PIPELINE_B)));
402        assert!(!auth.is_allowed(&Caller::Anonymous));
403
404        let no_external = PipelineClientAuth::from_chain(&chain, &[]).unwrap();
405        assert!(!no_external.is_allowed(&Caller::External(SIDECAR.to_string())));
406
407        for invalid in [
408            pipeline_certificate_uri(PIPELINE_B),
409            format!("URN:FELDERA:pipeline:{PIPELINE_B}"),
410            String::new(),
411            "urn:example:a urn:example:b".to_string(),
412        ] {
413            assert!(
414                PipelineClientAuth::from_chain(&chain, std::slice::from_ref(&invalid)).is_err(),
415                "{invalid}"
416            );
417        }
418
419        assert!(PipelineClientAuth::from_chain(&[own_leaf], &[]).is_err());
420        let server_leaf = leaf(&issuer, &[]);
421        assert!(PipelineClientAuth::from_chain(&[server_leaf, ca_cert], &[]).is_err());
422    }
423
424    /// Servers trust client certificates from the private CA, the first certificate of the CA
425    /// chain, and refuse ones from its root or from another CA under that root.
426    #[test]
427    fn verifier_trusts_only_private_ca() {
428        let (root, root_cert) = named_ca("root", None);
429        let (private_ca, private_ca_cert) = named_ca("private", Some(&root));
430        let (other_ca, other_ca_cert) = named_ca("other", Some(&root));
431        let own_leaf = leaf(&private_ca, &[pipeline_certificate_uri(PIPELINE_A)]);
432        let pipeline_chain = [own_leaf, private_ca_cert.clone(), root_cert.clone()];
433        let ca_chain = [private_ca_cert, root_cert];
434        let control_plane = [CONTROL_PLANE_CERTIFICATE_URI.to_string()];
435        let now = UnixTime::now();
436        for verifier in [
437            client_certificate_verifier(&ca_chain).unwrap(),
438            PipelineClientAuth::from_chain(&pipeline_chain, &[])
439                .unwrap()
440                .verifier,
441        ] {
442            let from_private_ca = leaf(&private_ca, &control_plane);
443            assert!(
444                verifier
445                    .verify_client_cert(&from_private_ca, &[], now)
446                    .is_ok()
447            );
448            let from_root = leaf(&root, &control_plane);
449            assert!(verifier.verify_client_cert(&from_root, &[], now).is_err());
450            let from_other_ca = leaf(&other_ca, &control_plane);
451            let other_chain = std::slice::from_ref(&other_ca_cert);
452            assert!(
453                verifier
454                    .verify_client_cert(&from_other_ca, other_chain, now)
455                    .is_err()
456            );
457        }
458    }
459}