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