kaniop_operator/kanidm/controller/
context.rs1use 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 kanidm_lib_crypto::x509_cert::Certificate;
12use kanidm_lib_crypto::x509_cert::der::Decode;
13
14use base64::{Engine as _, engine::general_purpose::URL_SAFE};
15use k8s_openapi::api::apps::v1::StatefulSet;
16use k8s_openapi::api::core::v1::{Secret, Service};
17use k8s_openapi::api::networking::v1::Ingress;
18use kube::runtime::reflector::{ObjectRef, Store};
19use tokio::sync::RwLock;
20use tracing::trace;
21
22#[derive(Clone)]
23pub struct Context {
24 pub kaniop_ctx: KaniopContext<Kanidm>,
25 pub stores: Arc<Stores>,
27 repl_cert_exp_cache: Arc<RwLock<ReplicaCertExpiration>>,
28}
29
30impl Context {
31 pub fn new(kaniop_ctx: KaniopContext<Kanidm>, stores: Stores) -> Self {
32 Context {
33 kaniop_ctx,
34 stores: Arc::new(stores),
35 repl_cert_exp_cache: Arc::default(),
36 }
37 }
38
39 pub async fn get_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) -> Option<i64> {
40 trace!(msg = format!("getting replica certificate expiration for {secret_ref}"));
41 self.repl_cert_exp_cache
42 .read()
43 .await
44 .0
45 .get(secret_ref)
46 .cloned()
47 }
48
49 pub async fn insert_repl_cert_exp(&self, secret: &Secret) -> Result<()> {
50 trace!(
51 msg = format!(
52 "inserting replica certificate expiration for {:?}",
53 &ObjectRef::from(secret)
54 )
55 );
56 match &secret.data {
57 None => Err(Error::MissingData("secret data empty".to_string())),
58 Some(data) => match data.get(REPLICA_SECRET_KEY) {
59 None => Err(Error::MissingData(format!(
60 "secret data missing key {REPLICA_SECRET_KEY}"
61 ))),
62 Some(cert_b64url) => {
63 let expiration =
64 get_cert_expiration(String::from_utf8_lossy(&cert_b64url.0).as_ref())?;
65 let obj_ref = ObjectRef::from(secret);
66 self.repl_cert_exp_cache
67 .write()
68 .await
69 .0
70 .insert(obj_ref, expiration);
71 Ok(())
72 }
73 },
74 }
75 }
76
77 pub async fn remove_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) {
78 trace!(msg = format!("removing replica certificate expiration for {secret_ref}",));
79 self.repl_cert_exp_cache.write().await.0.remove(secret_ref);
80 }
81}
82
83impl BackoffContext<Kanidm> for Context {
84 fn metrics(&self) -> &Arc<ControllerMetrics> {
85 self.kaniop_ctx.metrics()
86 }
87 async fn get_backoff(&self, obj_ref: ObjectRef<Kanidm>) -> Duration {
88 self.kaniop_ctx.get_backoff(obj_ref).await
89 }
90
91 async fn reset_backoff(&self, obj_ref: ObjectRef<Kanidm>) {
92 self.kaniop_ctx.reset_backoff(obj_ref).await
93 }
94}
95
96pub struct Stores {
97 pub stateful_set_store: Store<StatefulSet>,
98 pub service_store: Store<Service>,
99 pub ingress_store: Store<Ingress>,
100 pub secret_store: Store<Secret>,
101}
102
103#[derive(Default)]
104struct ReplicaCertExpiration(HashMap<ObjectRef<Secret>, i64>);
105
106fn get_cert_expiration(cert_b64url: &str) -> Result<i64> {
107 let der_bytes = URL_SAFE
108 .decode(cert_b64url)
109 .map_err(|e| Error::ParseError(format!("invalid base64url encoding: {e}")))?;
110
111 let cert = Certificate::from_der(&der_bytes)
112 .map_err(|e| Error::ParseError(format!("failed to parse DER certificate: {e}")))?;
113 let not_after = cert.tbs_certificate.validity.not_after;
114 trace!(msg = format!("certificate not after: {not_after}"));
115 let timestamp = not_after.to_unix_duration().as_secs() as i64;
116 Ok(timestamp)
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 #[test]
124 fn test_get_cert_expiration_valid_cert() {
125 let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc=";
126 let expiration = get_cert_expiration(cert_b64url).unwrap();
127 assert_eq!(expiration, 1857150807);
128 }
129}