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::backendtlspolicies::BackendTLSPolicy;
16use gateway_api::apis::standard::httproutes::HTTPRoute;
17use k8s_openapi::api::apps::v1::{Deployment, StatefulSet};
18use k8s_openapi::api::core::v1::{ConfigMap, Secret, Service};
19use k8s_openapi::api::networking::v1::Ingress;
20use kube::runtime::reflector::{ObjectRef, Store};
21use openssl::asn1::Asn1Time;
22use openssl::x509::X509;
23use tokio::sync::RwLock;
24use tracing::trace;
25
26#[derive(Clone)]
27pub struct Context {
28    pub kaniop_ctx: KaniopContext<Kanidm>,
29    /// Shared store
30    pub stores: Arc<Stores>,
31    repl_cert_exp_cache: Arc<RwLock<ReplicaCertExpiration>>,
32    repl_cert_host_cache: Arc<RwLock<ReplicaCertHost>>,
33}
34
35impl Context {
36    pub fn new(kaniop_ctx: KaniopContext<Kanidm>, stores: Stores) -> Self {
37        Context {
38            kaniop_ctx,
39            stores: Arc::new(stores),
40            repl_cert_exp_cache: Arc::default(),
41            repl_cert_host_cache: Arc::default(),
42        }
43    }
44
45    pub async fn get_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) -> Option<i64> {
46        trace!("getting replica certificate expiration for {secret_ref}");
47        self.repl_cert_exp_cache
48            .read()
49            .await
50            .0
51            .get(secret_ref)
52            .cloned()
53    }
54
55    pub async fn insert_repl_cert_exp(&self, secret: &Secret) -> Result<()> {
56        trace!(
57            "inserting replica certificate expiration for {:?}",
58            &ObjectRef::from(secret)
59        );
60        match &secret.data {
61            None => Err(Error::MissingData("secret data empty".to_string())),
62            Some(data) => match data.get(REPLICA_SECRET_KEY) {
63                None => Err(Error::MissingData(format!(
64                    "secret data missing key {REPLICA_SECRET_KEY}"
65                ))),
66                Some(cert_b64url) => {
67                    let (expiration, host) = parse_cert_expiration_and_host(
68                        String::from_utf8_lossy(&cert_b64url.0).as_ref(),
69                    )?;
70                    let obj_ref = ObjectRef::from(secret);
71                    self.repl_cert_exp_cache
72                        .write()
73                        .await
74                        .0
75                        .insert(obj_ref.clone(), expiration);
76                    self.repl_cert_host_cache
77                        .write()
78                        .await
79                        .0
80                        .insert(obj_ref, host);
81                    Ok(())
82                }
83            },
84        }
85    }
86
87    #[inline]
88    pub async fn remove_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) {
89        trace!("removing replica certificate expiration for {secret_ref}",);
90        self.repl_cert_exp_cache.write().await.0.remove(secret_ref);
91    }
92
93    pub async fn get_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) -> Option<String> {
94        trace!("getting replica certificate host for {secret_ref}");
95        self.repl_cert_host_cache
96            .read()
97            .await
98            .0
99            .get(secret_ref)
100            .cloned()
101    }
102
103    #[inline]
104    pub async fn remove_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) {
105        trace!("removing replica certificate host for {secret_ref}",);
106        self.repl_cert_host_cache.write().await.0.remove(secret_ref);
107    }
108}
109
110impl BackoffContext<Kanidm> for Context {
111    fn metrics(&self) -> &Arc<ControllerMetrics> {
112        self.kaniop_ctx.metrics()
113    }
114    async fn get_backoff(&self, obj_ref: ObjectRef<Kanidm>) -> Duration {
115        self.kaniop_ctx.get_backoff(obj_ref).await
116    }
117
118    async fn reset_backoff(&self, obj_ref: ObjectRef<Kanidm>) {
119        self.kaniop_ctx.reset_backoff(obj_ref).await
120    }
121}
122
123pub struct Stores {
124    pub stateful_set_store: Store<StatefulSet>,
125    pub service_store: Store<Service>,
126    pub ingress_store: Store<Ingress>,
127    pub secret_store: Store<Secret>,
128    pub http_route_store: Option<Store<HTTPRoute>>,
129    pub backend_tls_policy_store: Option<Store<BackendTLSPolicy>>,
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!("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}