Skip to main content

kaniop_operator/kanidm/controller/
context.rs

1use crate::controller::context::BackoffContext;
2use crate::kanidm::reconcile::secret::REPLICA_SECRET_KEY;
3use crate::metrics::ControllerMetrics;
4use crate::{controller::context::Context as KaniopContext, kanidm::crd::Kanidm};
5use kaniop_k8s_util::error::{Error, Result};
6
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::time::Duration;
10
11use base64::{
12    Engine as _,
13    engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
14};
15use gateway_api::apis::standard::httproutes::HTTPRoute;
16use k8s_openapi::api::apps::v1::{Deployment, StatefulSet};
17use k8s_openapi::api::core::v1::{ConfigMap, Secret, Service};
18use k8s_openapi::api::networking::v1::Ingress;
19use kube::runtime::reflector::{ObjectRef, Store};
20use openssl::asn1::Asn1Time;
21use openssl::x509::X509;
22use tokio::sync::RwLock;
23use tracing::trace;
24
25#[derive(Clone)]
26pub struct Context {
27    pub kaniop_ctx: KaniopContext<Kanidm>,
28    /// Shared store
29    pub stores: Arc<Stores>,
30    repl_cert_exp_cache: Arc<RwLock<ReplicaCertExpiration>>,
31    repl_cert_host_cache: Arc<RwLock<ReplicaCertHost>>,
32}
33
34impl Context {
35    pub fn new(kaniop_ctx: KaniopContext<Kanidm>, stores: Stores) -> Self {
36        Context {
37            kaniop_ctx,
38            stores: Arc::new(stores),
39            repl_cert_exp_cache: Arc::default(),
40            repl_cert_host_cache: Arc::default(),
41        }
42    }
43
44    pub async fn get_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) -> Option<i64> {
45        trace!(msg = format!("getting replica certificate expiration for {secret_ref}"));
46        self.repl_cert_exp_cache
47            .read()
48            .await
49            .0
50            .get(secret_ref)
51            .cloned()
52    }
53
54    pub async fn insert_repl_cert_exp(&self, secret: &Secret) -> Result<()> {
55        trace!(
56            msg = format!(
57                "inserting replica certificate expiration for {:?}",
58                &ObjectRef::from(secret)
59            )
60        );
61        match &secret.data {
62            None => Err(Error::MissingData("secret data empty".to_string())),
63            Some(data) => match data.get(REPLICA_SECRET_KEY) {
64                None => Err(Error::MissingData(format!(
65                    "secret data missing key {REPLICA_SECRET_KEY}"
66                ))),
67                Some(cert_b64url) => {
68                    let (expiration, host) = parse_cert_expiration_and_host(
69                        String::from_utf8_lossy(&cert_b64url.0).as_ref(),
70                    )?;
71                    let obj_ref = ObjectRef::from(secret);
72                    self.repl_cert_exp_cache
73                        .write()
74                        .await
75                        .0
76                        .insert(obj_ref.clone(), expiration);
77                    self.repl_cert_host_cache
78                        .write()
79                        .await
80                        .0
81                        .insert(obj_ref, host);
82                    Ok(())
83                }
84            },
85        }
86    }
87
88    #[inline]
89    pub async fn remove_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) {
90        trace!(msg = format!("removing replica certificate expiration for {secret_ref}",));
91        self.repl_cert_exp_cache.write().await.0.remove(secret_ref);
92    }
93
94    pub async fn get_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) -> Option<String> {
95        trace!(msg = format!("getting replica certificate host for {secret_ref}"));
96        self.repl_cert_host_cache
97            .read()
98            .await
99            .0
100            .get(secret_ref)
101            .cloned()
102    }
103
104    #[inline]
105    pub async fn remove_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) {
106        trace!(msg = format!("removing replica certificate host for {secret_ref}",));
107        self.repl_cert_host_cache.write().await.0.remove(secret_ref);
108    }
109}
110
111impl BackoffContext<Kanidm> for Context {
112    fn metrics(&self) -> &Arc<ControllerMetrics> {
113        self.kaniop_ctx.metrics()
114    }
115    async fn get_backoff(&self, obj_ref: ObjectRef<Kanidm>) -> Duration {
116        self.kaniop_ctx.get_backoff(obj_ref).await
117    }
118
119    async fn reset_backoff(&self, obj_ref: ObjectRef<Kanidm>) {
120        self.kaniop_ctx.reset_backoff(obj_ref).await
121    }
122}
123
124pub struct Stores {
125    pub stateful_set_store: Store<StatefulSet>,
126    pub service_store: Store<Service>,
127    pub ingress_store: Store<Ingress>,
128    pub secret_store: Store<Secret>,
129    pub http_route_store: Option<Store<HTTPRoute>>,
130    pub deployment_store: Store<Deployment>,
131    pub config_map_store: Store<ConfigMap>,
132}
133
134#[derive(Default)]
135struct ReplicaCertExpiration(HashMap<ObjectRef<Secret>, i64>);
136
137#[derive(Default)]
138struct ReplicaCertHost(HashMap<ObjectRef<Secret>, String>);
139
140fn parse_cert_expiration_and_host(cert_b64url: &str) -> Result<(i64, String)> {
141    let der_bytes = URL_SAFE.decode(cert_b64url).or_else(|padded_error| {
142        URL_SAFE_NO_PAD.decode(cert_b64url).map_err(|unpadded_error| {
143            Error::ParseError(format!(
144                "invalid base64url encoding: {padded_error}; unpadded decode also failed: {unpadded_error}"
145            ))
146        })
147    })?;
148
149    let cert = X509::from_der(&der_bytes)
150        .map_err(|e| Error::ParseError(format!("failed to parse DER certificate: {e}")))?;
151    let not_after = cert.not_after();
152    trace!(msg = format!("certificate not after: {not_after}"));
153
154    let epoch = Asn1Time::from_unix(0)
155        .map_err(|e| Error::ParseError(format!("failed to create epoch time: {e}")))?;
156    let duration = epoch
157        .diff(not_after)
158        .map_err(|e| Error::ParseError(format!("failed to calculate cert duration: {e}")))?;
159    let timestamp = duration.days as i64 * 86400 + duration.secs as i64;
160
161    let san = cert
162        .subject_alt_names()
163        .ok_or_else(|| Error::ParseError("no SAN extension".to_string()))?;
164    let host = san
165        .iter()
166        .find_map(|name| {
167            if let Some(dns) = name.dnsname() {
168                Some(dns.to_string())
169            } else if let Some(ip_bytes) = name.ipaddress() {
170                if ip_bytes.len() == 4 {
171                    // Safe: length check guarantees correct array size
172                    let ip = std::net::Ipv4Addr::from(<[u8; 4]>::try_from(ip_bytes).unwrap());
173                    Some(ip.to_string())
174                } else if ip_bytes.len() == 16 {
175                    // Safe: length check guarantees correct array size
176                    let ip = std::net::Ipv6Addr::from(<[u8; 16]>::try_from(ip_bytes).unwrap());
177                    Some(ip.to_string())
178                } else {
179                    None
180                }
181            } else {
182                None
183            }
184        })
185        .ok_or_else(|| Error::ParseError("no DNS or IP in SAN".to_string()))?;
186    Ok((timestamp, host))
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn test_get_cert_expiration_valid_cert() {
195        let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc=";
196        let (expiration, host) = parse_cert_expiration_and_host(cert_b64url).unwrap();
197        assert_eq!(expiration, 1857150807);
198        assert_eq!(host, "localhost");
199    }
200
201    #[test]
202    fn test_get_cert_expiration_valid_unpadded_cert() {
203        let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc";
204        let (expiration, host) = parse_cert_expiration_and_host(cert_b64url).unwrap();
205        assert_eq!(expiration, 1857150807);
206        assert_eq!(host, "localhost");
207    }
208}