kaniop_operator/kanidm/controller/
context.rs1use crate::controller::context::BackoffContext;
2use crate::error::{Error, Result};
3use crate::kanidm::reconcile::secret::REPLICA_SECRET_KEY;
4use crate::metrics::ControllerMetrics;
5use crate::{controller::context::Context as KaniopContext, kanidm::crd::Kanidm};
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::new(RwLock::new(ReplicaCertExpiration::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 {
67 self.repl_cert_exp_cache
68 .write()
69 .await
70 .0
71 .insert(obj_ref, expiration);
72 }
73 Ok(())
74 }
75 },
76 }
77 }
78
79 pub async fn remove_repl_cert_exp(&self, secret_ref: &ObjectRef<Secret>) {
80 trace!(msg = format!("removing replica certificate expiration for {secret_ref}",));
81 self.repl_cert_exp_cache.write().await.0.remove(secret_ref);
82 }
83}
84
85impl BackoffContext<Kanidm> for Context {
86 fn metrics(&self) -> &Arc<ControllerMetrics> {
87 self.kaniop_ctx.metrics()
88 }
89 async fn get_backoff(&self, obj_ref: ObjectRef<Kanidm>) -> Duration {
90 self.kaniop_ctx.get_backoff(obj_ref).await
91 }
92
93 async fn reset_backoff(&self, obj_ref: ObjectRef<Kanidm>) {
94 self.kaniop_ctx.reset_backoff(obj_ref).await
95 }
96}
97
98pub struct Stores {
99 pub stateful_set_store: Store<StatefulSet>,
100 pub service_store: Store<Service>,
101 pub ingress_store: Store<Ingress>,
102 pub secret_store: Store<Secret>,
103}
104
105#[derive(Default)]
106struct ReplicaCertExpiration(HashMap<ObjectRef<Secret>, i64>);
107
108fn get_cert_expiration(cert_b64url: &str) -> Result<i64> {
109 let der_bytes = URL_SAFE
110 .decode(cert_b64url)
111 .map_err(|e| Error::ParseError(format!("invalid base64url encoding: {e}")))?;
112
113 let cert = Certificate::from_der(&der_bytes)
114 .map_err(|e| Error::ParseError(format!("failed to parse DER certificate: {e}")))?;
115 let not_after = cert.tbs_certificate.validity.not_after;
116 trace!(msg = format!("certificate not after: {not_after}"));
117 let timestamp = not_after.to_unix_duration().as_secs() as i64;
118 Ok(timestamp)
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn test_get_cert_expiration_valid_cert() {
127 let cert_b64url = "MIIB_DCCAaGgAwIBAgIBATAKBggqhkjOPQQDAjBMMRswGQYDVQQKDBJLYW5pZG0gUmVwbGljYXRpb24xLTArBgNVBAMMJDJiYTgzMTZhLWViYWEtNGJjMS04NDkzLTVmODZmYWZhZTU5NDAeFw0yNDExMDYxOTEzMjdaFw0yODExMDYxOTEzMjdaMEwxGzAZBgNVBAoMEkthbmlkbSBSZXBsaWNhdGlvbjEtMCsGA1UEAwwkMmJhODMxNmEtZWJhYS00YmMxLTg0OTMtNWY4NmZhZmFlNTk0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuXp1hNNZerxDQbCh7rAGW6uM0CPECNd3IvbSh7qH34MkO_plwwDVKFbzcTG8HJE2ouIJlJYN8P4wf6qmrRQMAKN0MHIwDAYDVR0TAQH_BAIwADAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBTaOaPuXmtLDTJVv--VYBiQr9gHCTAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDSQAwRgIhAIZD_J4LyR7D0kg41GRg_TcRxm5mEVhM6WL9BO3XmfUsAiEA7Wpbkvd0b1e-Sg8AS9jP-CpBpmTnC7oEChkyhUYKyFc=";
128 let expiration = get_cert_expiration(cert_b64url).unwrap();
129 assert_eq!(expiration, 1857150807);
130 }
131}