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!(msg = format!("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            msg = format!(
58                "inserting replica certificate expiration for {:?}",
59                &ObjectRef::from(secret)
60            )
61        );
62        match &secret.data {
63            None => Err(Error::MissingData("secret data empty".to_string())),
64            Some(data) => match data.get(REPLICA_SECRET_KEY) {
65                None => Err(Error::MissingData(format!(
66                    "secret data missing key {REPLICA_SECRET_KEY}"
67                ))),
68                Some(cert_b64url) => {
69                    let (expiration, host) = parse_cert_expiration_and_host(
70                        String::from_utf8_lossy(&cert_b64url.0).as_ref(),
71                    )?;
72                    let obj_ref = ObjectRef::from(secret);
73                    self.repl_cert_exp_cache
74                        .write()
75                        .await
76                        .0
77                        .insert(obj_ref.clone(), expiration);
78                    self.repl_cert_host_cache
79                        .write()
80                        .await
81                        .0
82                        .insert(obj_ref, host);
83                    Ok(())
84                }
85            },
86        }
87    }
88
89    #[inline]
90    pub async fn remove_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) {
91        trace!(msg = format!("removing replica certificate expiration for {secret_ref}",));
92        self.repl_cert_exp_cache.write().await.0.remove(secret_ref);
93    }
94
95    pub async fn get_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) -> Option<String> {
96        trace!(msg = format!("getting replica certificate host for {secret_ref}"));
97        self.repl_cert_host_cache
98            .read()
99            .await
100            .0
101            .get(secret_ref)
102            .cloned()
103    }
104
105    #[inline]
106    pub async fn remove_repl_cert_host(&self, secret_ref: &ObjectRef<Secret>) {
107        trace!(msg = format!("removing replica certificate host for {secret_ref}",));
108        self.repl_cert_host_cache.write().await.0.remove(secret_ref);
109    }
110}
111
112impl BackoffContext<Kanidm> for Context {
113    fn metrics(&self) -> &Arc<ControllerMetrics> {
114        self.kaniop_ctx.metrics()
115    }
116    async fn get_backoff(&self, obj_ref: ObjectRef<Kanidm>) -> Duration {
117        self.kaniop_ctx.get_backoff(obj_ref).await
118    }
119
120    async fn reset_backoff(&self, obj_ref: ObjectRef<Kanidm>) {
121        self.kaniop_ctx.reset_backoff(obj_ref).await
122    }
123}
124
125pub struct Stores {
126    pub stateful_set_store: Store<StatefulSet>,
127    pub service_store: Store<Service>,
128    pub ingress_store: Store<Ingress>,
129    pub secret_store: Store<Secret>,
130    pub http_route_store: Option<Store<HTTPRoute>>,
131    pub backend_tls_policy_store: Option<Store<BackendTLSPolicy>>,
132    pub deployment_store: Store<Deployment>,
133    pub config_map_store: Store<ConfigMap>,
134}
135
136#[derive(Default)]
137struct ReplicaCertExpiration(HashMap<ObjectRef<Secret>, i64>);
138
139#[derive(Default)]
140struct ReplicaCertHost(HashMap<ObjectRef<Secret>, String>);
141
142fn parse_cert_expiration_and_host(cert_b64url: &str) -> Result<(i64, String)> {
143    let der_bytes = URL_SAFE.decode(cert_b64url).or_else(|padded_error| {
144        URL_SAFE_NO_PAD.decode(cert_b64url).map_err(|unpadded_error| {
145            Error::ParseError(format!(
146                "invalid base64url encoding: {padded_error}; unpadded decode also failed: {unpadded_error}"
147            ))
148        })
149    })?;
150
151    let cert = X509::from_der(&der_bytes)
152        .map_err(|e| Error::ParseError(format!("failed to parse DER certificate: {e}")))?;
153    let not_after = cert.not_after();
154    trace!(msg = format!("certificate not after: {not_after}"));
155
156    let epoch = Asn1Time::from_unix(0)
157        .map_err(|e| Error::ParseError(format!("failed to create epoch time: {e}")))?;
158    let duration = epoch
159        .diff(not_after)
160        .map_err(|e| Error::ParseError(format!("failed to calculate cert duration: {e}")))?;
161    let timestamp = duration.days as i64 * 86400 + duration.secs as i64;
162
163    let san = cert
164        .subject_alt_names()
165        .ok_or_else(|| Error::ParseError("no SAN extension".to_string()))?;
166    let host = san
167        .iter()
168        .find_map(|name| {
169            if let Some(dns) = name.dnsname() {
170                Some(dns.to_string())
171            } else if let Some(ip_bytes) = name.ipaddress() {
172                if ip_bytes.len() == 4 {
173                    // Safe: length check guarantees correct array size
174                    let ip = std::net::Ipv4Addr::from(<[u8; 4]>::try_from(ip_bytes).unwrap());
175                    Some(ip.to_string())
176                } else if ip_bytes.len() == 16 {
177                    // Safe: length check guarantees correct array size
178                    let ip = std::net::Ipv6Addr::from(<[u8; 16]>::try_from(ip_bytes).unwrap());
179                    Some(ip.to_string())
180                } else {
181                    None
182                }
183            } else {
184                None
185            }
186        })
187        .ok_or_else(|| Error::ParseError("no DNS or IP in SAN".to_string()))?;
188    Ok((timestamp, host))
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn test_get_cert_expiration_valid_cert() {
197        let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc=";
198        let (expiration, host) = parse_cert_expiration_and_host(cert_b64url).unwrap();
199        assert_eq!(expiration, 1857150807);
200        assert_eq!(host, "localhost");
201    }
202
203    #[test]
204    fn test_get_cert_expiration_valid_unpadded_cert() {
205        let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc";
206        let (expiration, host) = parse_cert_expiration_and_host(cert_b64url).unwrap();
207        assert_eq!(expiration, 1857150807);
208        assert_eq!(host, "localhost");
209    }
210}