Skip to main content

kaniop_person/
reconcile.rs

1use crate::controller::Context;
2use crate::crd::{KanidmPersonAccount, KanidmPersonAccountStatus, KanidmPersonAttributes};
3
4use kaniop_k8s_util::error::{Error, Result};
5use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
6use kaniop_operator::controller::{DEFAULT_RECONCILE_INTERVAL, context::IdmClientContext};
7use kaniop_operator::crd::KanidmAccountPosixAttributes;
8use kaniop_operator::telemetry;
9
10use std::collections::BTreeMap;
11use std::ops::Not;
12use std::sync::Arc;
13use std::time::Duration;
14
15use futures::TryFutureExt;
16use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
17use k8s_openapi::jiff::Timestamp;
18use kanidm_client::{ClientError, KanidmClient};
19use kanidm_proto::constants::{ATTR_ACCOUNT_EXPIRE, ATTR_ACCOUNT_VALID_FROM};
20use kanidm_proto::v1::Entry;
21use kube::api::{Api, Patch, PatchParams};
22use kube::runtime::controller::Action;
23use kube::runtime::events::{Event, EventType};
24use kube::runtime::finalizer::{Event as Finalizer, finalizer};
25use kube::runtime::reflector::ObjectRef;
26use kube::{Resource, ResourceExt};
27use time::format_description::well_known::Rfc3339;
28use time::{OffsetDateTime, UtcOffset};
29use tracing::{Span, debug, field, info, instrument, trace, warn};
30
31pub static PERSON_OPERATOR_NAME: &str = "kanidmpersonsaccounts.kaniop.rs";
32pub static PERSON_FINALIZER: &str = "kanidmpersonsaccounts.kaniop.rs/finalizer";
33
34const TYPE_CREDENTIAL: &str = "Credential";
35const TYPE_EXISTS: &str = "Exists";
36const TYPE_UPDATED: &str = "Updated";
37const TYPE_POSIX_INITIALIZED: &str = "PosixInitialized";
38const TYPE_POSIX_UPDATED: &str = "PosixUpdated";
39const TYPE_VALIDITY: &str = "Valid";
40const REASON_ATTRIBUTES_MATCH: &str = "AttributesMatch";
41const REASON_ATTRIBUTES_NOT_MATCH: &str = "AttributesNotMatch";
42const CONDITION_TRUE: &str = "True";
43const CONDITION_FALSE: &str = "False";
44
45pub async fn watched_resource(person: &KanidmPersonAccount, ctx: Arc<Context>) -> bool {
46    let kanidm = if let Some(k) = ctx.kaniop_ctx.get_kanidm(person) {
47        k
48    } else {
49        trace!(msg = "no kanidm found");
50        return false;
51    };
52
53    is_resource_watched(
54        person,
55        &kanidm,
56        &ctx.kaniop_ctx.namespace_store,
57        &ctx.kaniop_ctx.client,
58    )
59    .await
60}
61
62#[instrument(skip(ctx, person))]
63pub async fn reconcile_person_account(
64    person: Arc<KanidmPersonAccount>,
65    ctx: Arc<Context>,
66) -> Result<Action> {
67    let trace_id = telemetry::get_trace_id();
68    Span::current().record("trace_id", field::display(&trace_id));
69    let _timer = ctx
70        .kaniop_ctx
71        .metrics
72        .reconcile_count_and_measure(&trace_id);
73    let kanidm_client = ctx.get_idm_client(&person).await?;
74
75    if !watched_resource(&person, ctx.clone()).await {
76        debug!(msg = "resource not watched, skipping reconcile");
77        ctx.kaniop_ctx
78            .recorder
79            .publish(
80                &Event {
81                    type_: EventType::Warning,
82                    reason: "ResourceNotWatched".to_string(),
83                    note: Some("configure `personNamespaceSelector` on Kanidm resource to watch this namespace".to_string()),
84                    action: "Reconcile".to_string(),
85                    secondary: None,
86                },
87                &person.object_ref(&()),
88            )
89            .await
90            .map_err(|e| {
91                warn!(msg = "failed to publish ResourceNotWatched event", %e);
92                Error::KubeError("failed to publish event".to_string(), Box::new(e))
93            })?;
94        return Ok(Action::requeue(DEFAULT_RECONCILE_INTERVAL));
95    }
96    info!(msg = "reconciling person account");
97
98    let namespace = person.get_namespace();
99    let status = person
100        .update_status(kanidm_client.clone(), ctx.clone())
101        .await
102        .map_err(|e| {
103            debug!(msg = "failed to reconcile status", %e);
104            ctx.kaniop_ctx.metrics.status_update_errors_inc();
105            e
106        })?;
107    let persons_api: Api<KanidmPersonAccount> =
108        Api::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
109    finalizer(&persons_api, PERSON_FINALIZER, person, |event| async {
110        match event {
111            Finalizer::Apply(p) => p.reconcile(kanidm_client, status, ctx).await,
112            Finalizer::Cleanup(p) => p.cleanup(kanidm_client, status, ctx).await,
113        }
114    })
115    .await
116    .map_err(|e| {
117        Error::FinalizerError(
118            "failed on person account finalizer".to_string(),
119            Box::new(e),
120        )
121    })
122}
123
124impl KanidmPersonAccount {
125    #[inline]
126    fn get_namespace(&self) -> String {
127        // safe unwrap: person is namespaced scoped
128        self.namespace().unwrap()
129    }
130
131    #[inline]
132    async fn reconcile(
133        &self,
134        kanidm_client: Arc<KanidmClient>,
135        status: KanidmPersonAccountStatus,
136        ctx: Arc<Context>,
137    ) -> Result<Action> {
138        match self
139            .internal_reconcile(kanidm_client, status, ctx.clone())
140            .await
141        {
142            Ok(action) => Ok(action),
143            Err(e) => match e {
144                Error::KanidmClientError(_, _) => {
145                    ctx.kaniop_ctx
146                        .recorder
147                        .publish(
148                            &Event {
149                                type_: EventType::Warning,
150                                reason: "KanidmError".to_string(),
151                                note: Some(format!("{e:?}")),
152                                action: "KanidmRequest".to_string(),
153                                secondary: None,
154                            },
155                            &self.object_ref(&()),
156                        )
157                        .await
158                        .map_err(|e| {
159                            warn!(msg = "failed to publish KanidmError event", %e);
160                            Error::KubeError("failed to publish event".to_string(), Box::new(e))
161                        })?;
162                    Err(e)
163                }
164                _ => Err(e),
165            },
166        }
167    }
168
169    async fn internal_reconcile(
170        &self,
171        kanidm_client: Arc<KanidmClient>,
172        status: KanidmPersonAccountStatus,
173        ctx: Arc<Context>,
174    ) -> Result<Action> {
175        let name = &self.kanidm_entity_name();
176
177        let mut require_status_update = false;
178        if is_person_false(TYPE_EXISTS, status.clone()) {
179            self.create(&kanidm_client, name).await?;
180            require_status_update = true;
181        }
182        if is_person_false(TYPE_UPDATED, status.clone()) {
183            self.update(&kanidm_client, name).await?;
184            require_status_update = true;
185        }
186
187        if is_person_false(TYPE_POSIX_UPDATED, status.clone())
188            || (is_person_false(TYPE_POSIX_INITIALIZED, status.clone())
189                && is_person(TYPE_POSIX_UPDATED, status.clone()))
190        {
191            self.update_posix_attributes(&kanidm_client, name).await?;
192            require_status_update = true;
193        }
194
195        if is_person_false(TYPE_CREDENTIAL, status) {
196            let create_token = match ctx.internal_cache.read().await.get(&ObjectRef::from(self)) {
197                Some(expiry) if expiry > &OffsetDateTime::now_utc() => {
198                    trace!(msg = "token not expired, skipping creation");
199                    false
200                }
201                _ => true,
202            };
203            if create_token {
204                self.create_reset_token(&kanidm_client, name, ctx).await?;
205            };
206        };
207
208        if require_status_update {
209            trace!(msg = "status update required, requeueing in 500ms");
210            Ok(Action::requeue(Duration::from_millis(500)))
211        } else {
212            Ok(Action::requeue(DEFAULT_RECONCILE_INTERVAL))
213        }
214    }
215
216    async fn create(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
217        debug!(msg = "create");
218        kanidm_client
219            .idm_person_account_create(name, &self.spec.person_attributes.displayname)
220            .await
221            .map_err(|e| {
222                Error::KanidmClientError(
223                    format!(
224                        "failed to create {name} from {namespace}/{kanidm}",
225                        namespace = self.kanidm_namespace(),
226                        kanidm = self.kanidm_name(),
227                    ),
228                    Box::new(e),
229                )
230            })?;
231        Ok(())
232    }
233
234    async fn update(&self, kanidm_client: &KanidmClient, name: &str) -> Result<()> {
235        debug!(msg = "update");
236        trace!(msg = format!("update person attributes {:?}", self.spec.person_attributes));
237        kanidm_client
238            .idm_person_account_update(
239                name,
240                None,
241                Some(&self.spec.person_attributes.displayname),
242                self.spec.person_attributes.legalname.as_deref(),
243                self.spec.person_attributes.mail.as_deref(),
244            )
245            .await
246            .map_err(|e| {
247                Error::KanidmClientError(
248                    format!(
249                        "failed to update {name} from {namespace}/{kanidm}",
250                        namespace = self.kanidm_namespace(),
251                        kanidm = self.kanidm_name(),
252                    ),
253                    Box::new(e),
254                )
255            })?;
256        let mut update_entry = Entry {
257            attrs: BTreeMap::new(),
258        };
259        if let Some(account_expire) = self.spec.person_attributes.account_expire.as_ref() {
260            update_entry.attrs.insert(
261                ATTR_ACCOUNT_EXPIRE.to_string(),
262                vec![account_expire.0.to_string()],
263            );
264        }
265        if let Some(account_valid_from) = self.spec.person_attributes.account_valid_from.as_ref() {
266            update_entry.attrs.insert(
267                ATTR_ACCOUNT_VALID_FROM.to_string(),
268                vec![account_valid_from.0.to_string()],
269            );
270        }
271
272        if update_entry.attrs.is_empty().not() {
273            let _: Entry = kanidm_client
274                .perform_patch_request(&format!("/v1/person/{name}"), update_entry)
275                .await
276                .map_err(|e| {
277                    Error::KanidmClientError(
278                        format!(
279                            "failed to update {name} from {namespace}/{kanidm}",
280                            namespace = self.kanidm_namespace(),
281                            kanidm = self.kanidm_name(),
282                        ),
283                        Box::new(e),
284                    )
285                })?;
286        }
287        Ok(())
288    }
289
290    async fn update_posix_attributes(
291        &self,
292        kanidm_client: &KanidmClient,
293        name: &str,
294    ) -> Result<()> {
295        debug!(msg = "update posix attributes");
296        trace!(msg = format!("update posix attributes {:?}", self.spec.posix_attributes));
297        kanidm_client
298            .idm_person_account_unix_extend(
299                name,
300                self.spec
301                    .posix_attributes
302                    .as_ref()
303                    .and_then(|posix| posix.gidnumber),
304                self.spec
305                    .posix_attributes
306                    .as_ref()
307                    .and_then(|posix| posix.loginshell.as_deref()),
308            )
309            .await
310            .map_err(|e| {
311                Error::KanidmClientError(
312                    format!(
313                        "failed to update {name} from {namespace}/{kanidm}",
314                        namespace = self.kanidm_namespace(),
315                        kanidm = self.kanidm_name(),
316                    ),
317                    Box::new(e),
318                )
319            })?;
320        Ok(())
321    }
322
323    async fn create_reset_token(
324        &self,
325        kanidm_client: &KanidmClient,
326        name: &str,
327        ctx: Arc<Context>,
328    ) -> Result<()> {
329        debug!(msg = "create reset token");
330        let cu_token = kanidm_client
331            .idm_person_account_credential_update_intent(name, Some(self.spec.credentials_token_ttl))
332            .await
333            .map_err(|e| {
334                Error::KanidmClientError(
335                    format!(
336                        "failed to create a credential reset token for {name} from {namespace}/{kanidm}",
337                        namespace = self.kanidm_namespace(),
338                        kanidm = self.kanidm_name(),
339                    ),
340                    Box::new(e),
341                )
342            })?;
343        let token = cu_token.token.as_str();
344        let url = if let Some(base_url) = ctx.kaniop_ctx.get_kanidm(self).map(|k| {
345            k.spec
346                .origin
347                .clone()
348                .unwrap_or_else(|| format!("https://{}", k.spec.domain))
349        }) {
350            format!("{base_url}/ui/reset?token={token}")
351        } else {
352            let mut url = kanidm_client.make_url("/ui/reset");
353            url.query_pairs_mut().append_pair("token", token);
354            url.to_string()
355        };
356        let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
357        let expiry_time = cu_token.expiry_time.to_offset(local_offset);
358
359        let msg = format!(
360            "Update these user credentials with this link: {url}. This token will expire at: {}",
361            expiry_time
362                .format(&Rfc3339)
363                .expect("Failed to format date time!!!")
364        );
365        ctx.kaniop_ctx
366            .recorder
367            .publish(
368                &Event {
369                    type_: EventType::Normal,
370                    reason: "TokenCreated".to_string(),
371                    note: Some(msg),
372                    action: "CreateUpdateCredentialsToken".into(),
373                    secondary: None,
374                },
375                &self.object_ref(&()),
376            )
377            .await
378            .map_err(|e| {
379                warn!(msg = "failed to publish TokenCreated event", %e);
380                Error::KubeError("failed to publish event".to_string(), Box::new(e))
381            })?;
382        ctx.internal_cache
383            .write()
384            .await
385            .insert(ObjectRef::from(self), expiry_time);
386        Ok(())
387    }
388
389    async fn cleanup(
390        &self,
391        kanidm_client: Arc<KanidmClient>,
392        status: KanidmPersonAccountStatus,
393        ctx: Arc<Context>,
394    ) -> Result<Action> {
395        let name = &self.kanidm_entity_name();
396
397        if is_person(TYPE_EXISTS, status.clone()) {
398            debug!(msg = "delete");
399            kanidm_client
400                .idm_person_account_delete(name)
401                .await
402                .map_err(|e| {
403                    Error::KanidmClientError(
404                        format!(
405                            "failed to delete {name} from {namespace}/{kanidm}",
406                            namespace = self.kanidm_namespace(),
407                            kanidm = self.kanidm_name(),
408                        ),
409                        Box::new(e),
410                    )
411                })?;
412
413            ctx.internal_cache
414                .write()
415                .await
416                .remove(&ObjectRef::from(self));
417        }
418        Ok(Action::requeue(DEFAULT_RECONCILE_INTERVAL))
419    }
420
421    async fn update_status(
422        &self,
423        kanidm_client: Arc<KanidmClient>,
424        ctx: Arc<Context>,
425    ) -> Result<KanidmPersonAccountStatus> {
426        // safe unwrap: person is namespaced scoped
427        let namespace = self.get_namespace();
428        let name = self.kanidm_entity_name();
429        let current_person = kanidm_client
430            .idm_person_account_get(&name)
431            .map_err(|e| {
432                Error::KanidmClientError(
433                    format!(
434                        "failed to get {name} from {namespace}/{kanidm}",
435                        namespace = self.kanidm_namespace(),
436                        kanidm = self.kanidm_name(),
437                    ),
438                    Box::new(e),
439                )
440            })
441            .await?;
442        let credential_present = match kanidm_client
443            .idm_person_account_get_credential_status(&name)
444            .await
445        {
446            Ok(cs) => Some(cs.creds.is_empty().not()),
447            Err(ClientError::EmptyResponse) => Some(false),
448            Err(_) => None,
449        };
450
451        let status = self.generate_status(current_person, credential_present)?;
452        let status_patch = Patch::Apply(KanidmPersonAccount {
453            status: Some(status.clone()),
454            ..KanidmPersonAccount::default()
455        });
456        debug!(msg = "updating status");
457        trace!(msg = format!("status patch {:?}", status_patch));
458        let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
459        let kanidm_api =
460            Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
461        let _o = kanidm_api
462            .patch_status(&name, &patch, &status_patch)
463            .await
464            .map_err(|e| {
465                Error::KubeError(
466                    format!("failed to patch KanidmPersonAccount/status {namespace}/{name}"),
467                    Box::new(e),
468                )
469            })?;
470        Ok(status)
471    }
472
473    fn generate_status(
474        &self,
475        person: Option<Entry>,
476        credential_present: Option<bool>,
477    ) -> Result<KanidmPersonAccountStatus> {
478        let now = Timestamp::now();
479        match person {
480            Some(p) => {
481                let exist_condition = Condition {
482                    type_: TYPE_EXISTS.to_string(),
483                    status: CONDITION_TRUE.to_string(),
484                    reason: "Exists".to_string(),
485                    message: "Person exists.".to_string(),
486                    last_transition_time: Time(now),
487                    observed_generation: self.metadata.generation,
488                };
489
490                let current_person_attributes = KanidmPersonAttributes::from(p.clone());
491                let updated_condition = if self.spec.person_attributes == current_person_attributes
492                {
493                    Condition {
494                        type_: TYPE_UPDATED.to_string(),
495                        status: CONDITION_TRUE.to_string(),
496                        reason: REASON_ATTRIBUTES_MATCH.to_string(),
497                        message: "Person exists with desired attributes.".to_string(),
498                        last_transition_time: Time(now),
499                        observed_generation: self.metadata.generation,
500                    }
501                } else {
502                    Condition {
503                        type_: TYPE_UPDATED.to_string(),
504                        status: CONDITION_FALSE.to_string(),
505                        reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
506                        message: "Person exists with different attributes.".to_string(),
507                        last_transition_time: Time(now),
508                        observed_generation: self.metadata.generation,
509                    }
510                };
511
512                let current_person_posix = KanidmAccountPosixAttributes::from(p);
513                let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
514                    Condition {
515                        type_: TYPE_POSIX_INITIALIZED.to_string(),
516                        status: CONDITION_TRUE.to_string(),
517                        reason: "PosixInitialized".to_string(),
518                        message: "Person exists with POSIX attributes.".to_string(),
519                        last_transition_time: Time(now),
520                        observed_generation: self.metadata.generation,
521                    }
522                } else {
523                    Condition {
524                        type_: TYPE_POSIX_INITIALIZED.to_string(),
525                        status: CONDITION_FALSE.to_string(),
526                        reason: "PosixNotInitialized".to_string(),
527                        message: "Person exists without POSIX attributes.".to_string(),
528                        last_transition_time: Time(now),
529                        observed_generation: self.metadata.generation,
530                    }
531                };
532
533                let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
534                    if posix == &current_person_posix {
535                        Condition {
536                            type_: TYPE_POSIX_UPDATED.to_string(),
537                            status: CONDITION_TRUE.to_string(),
538                            reason: REASON_ATTRIBUTES_MATCH.to_string(),
539                            message: "Person exists with desired POSIX attributes.".to_string(),
540                            last_transition_time: Time(now),
541                            observed_generation: self.metadata.generation,
542                        }
543                    } else {
544                        Condition {
545                            type_: TYPE_POSIX_UPDATED.to_string(),
546                            status: CONDITION_FALSE.to_string(),
547                            reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
548                            message: "Person exists with different POSIX attributes.".to_string(),
549                            last_transition_time: Time(now),
550                            observed_generation: self.metadata.generation,
551                        }
552                    }
553                });
554
555                let credentials_condition = credential_present.map(|c| {
556                    if c {
557                        Condition {
558                            type_: TYPE_CREDENTIAL.to_string(),
559                            status: CONDITION_TRUE.to_string(),
560                            reason: "Present".to_string(),
561                            message: "Credentials are present.".to_string(),
562                            last_transition_time: Time(now),
563                            observed_generation: self.metadata.generation,
564                        }
565                    } else {
566                        Condition {
567                            type_: TYPE_CREDENTIAL.to_string(),
568                            status: CONDITION_FALSE.to_string(),
569                            reason: "NotPresent".to_string(),
570                            message: "Credentials are not present.".to_string(),
571                            last_transition_time: Time(now),
572                            observed_generation: self.metadata.generation,
573                        }
574                    }
575                });
576
577                let validity_condition = {
578                    let valid = if let Some(valid_from) =
579                        current_person_attributes.account_valid_from.as_ref()
580                    {
581                        now > valid_from.0
582                    } else {
583                        true
584                    } && if let Some(expire) =
585                        current_person_attributes.account_expire.as_ref()
586                    {
587                        now < expire.0
588                    } else {
589                        true
590                    };
591
592                    if valid {
593                        Condition {
594                            type_: TYPE_VALIDITY.to_string(),
595                            status: CONDITION_TRUE.to_string(),
596                            reason: "Valid".to_string(),
597                            message: "Account is valid.".to_string(),
598                            last_transition_time: Time(now),
599                            observed_generation: self.metadata.generation,
600                        }
601                    } else {
602                        Condition {
603                            type_: TYPE_VALIDITY.to_string(),
604                            status: CONDITION_FALSE.to_string(),
605                            reason: "Invalid".to_string(),
606                            message: "Account is invalid.".to_string(),
607                            last_transition_time: Time(now),
608                            observed_generation: self.metadata.generation,
609                        }
610                    }
611                };
612                let conditions = vec![
613                    exist_condition,
614                    updated_condition,
615                    posix_initialized_condition,
616                    validity_condition,
617                ]
618                .into_iter()
619                .chain(credentials_condition)
620                .chain(posix_updated_condition)
621                .collect::<Vec<_>>();
622                let status = conditions
623                    .iter()
624                    .filter(|c| {
625                        c.type_ != TYPE_POSIX_INITIALIZED
626                            && c.type_ != TYPE_CREDENTIAL
627                            && c.type_ != TYPE_VALIDITY
628                    })
629                    .all(|c| c.status == CONDITION_TRUE);
630                Ok(KanidmPersonAccountStatus {
631                    conditions: Some(conditions),
632                    ready: status,
633                    gid: current_person_posix.gidnumber,
634                    kanidm_ref: self.kanidm_ref(),
635                })
636            }
637            None => {
638                let conditions = vec![Condition {
639                    type_: TYPE_EXISTS.to_string(),
640                    status: CONDITION_FALSE.to_string(),
641                    reason: "NotExists".to_string(),
642                    message: "Person is not present.".to_string(),
643                    last_transition_time: Time(now),
644                    observed_generation: self.metadata.generation,
645                }];
646                Ok(KanidmPersonAccountStatus {
647                    conditions: Some(conditions),
648                    ready: false,
649                    gid: None,
650                    kanidm_ref: self.kanidm_ref(),
651                })
652            }
653        }
654    }
655}
656
657pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
658    status
659        .conditions
660        .unwrap_or_default()
661        .iter()
662        .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
663}
664
665pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
666    status
667        .conditions
668        .unwrap_or_default()
669        .iter()
670        .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
671}