1use crate::controller::Context;
2use crate::crd::{KanidmPersonAccount, KanidmPersonAccountStatus, KanidmPersonAttributes};
3
4use kaniop_operator::controller::kanidm::{KanidmResource, is_resource_watched};
5use kaniop_operator::controller::{DEFAULT_RECONCILE_INTERVAL, context::IdmClientContext};
6use kaniop_operator::crd::KanidmAccountPosixAttributes;
7use kaniop_operator::error::{Error, Result};
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(domain) = ctx
339 .kaniop_ctx
340 .get_kanidm(self)
341 .map(|k| k.spec.domain.clone())
342 {
343 format!("https://{domain}/ui/reset?token={token}")
344 } else {
345 let mut url = kanidm_client.make_url("/ui/reset");
346 url.query_pairs_mut().append_pair("token", token);
347 url.to_string()
348 };
349 let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
350 let expiry_time = cu_token.expiry_time.to_offset(local_offset);
351
352 let msg = format!(
353 "Update these user credentials with this link: {url}. This token will expire at: {}",
354 expiry_time
355 .format(&Rfc3339)
356 .expect("Failed to format date time!!!")
357 );
358 ctx.kaniop_ctx
359 .recorder
360 .publish(
361 &Event {
362 type_: EventType::Normal,
363 reason: "TokenCreated".to_string(),
364 note: Some(msg),
365 action: "CreateUpdateCredentialsToken".into(),
366 secondary: None,
367 },
368 &self.object_ref(&()),
369 )
370 .await
371 .map_err(|e| {
372 warn!(msg = "failed to publish TokenCreated event", %e);
373 Error::KubeError("failed to publish event".to_string(), Box::new(e))
374 })?;
375 ctx.internal_cache
376 .write()
377 .await
378 .insert(ObjectRef::from(self), expiry_time);
379 Ok(())
380 }
381
382 async fn cleanup(
383 &self,
384 kanidm_client: Arc<KanidmClient>,
385 status: KanidmPersonAccountStatus,
386 ctx: Arc<Context>,
387 ) -> Result<Action> {
388 let name = &self.name_any();
389
390 if is_person(TYPE_EXISTS, status.clone()) {
391 debug!(msg = "delete");
392 kanidm_client
393 .idm_person_account_delete(name)
394 .await
395 .map_err(|e| {
396 Error::KanidmClientError(
397 format!(
398 "failed to delete {name} from {namespace}/{kanidm}",
399 namespace = self.kanidm_namespace(),
400 kanidm = self.kanidm_name(),
401 ),
402 Box::new(e),
403 )
404 })?;
405
406 ctx.internal_cache
407 .write()
408 .await
409 .remove(&ObjectRef::from(self));
410 }
411 Ok(Action::requeue(DEFAULT_RECONCILE_INTERVAL))
412 }
413
414 async fn update_status(
415 &self,
416 kanidm_client: Arc<KanidmClient>,
417 ctx: Arc<Context>,
418 ) -> Result<KanidmPersonAccountStatus> {
419 let namespace = self.get_namespace();
421 let name = self.name_any();
422 let current_person = kanidm_client
423 .idm_person_account_get(&name)
424 .map_err(|e| {
425 Error::KanidmClientError(
426 format!(
427 "failed to get {name} from {namespace}/{kanidm}",
428 namespace = self.kanidm_namespace(),
429 kanidm = self.kanidm_name(),
430 ),
431 Box::new(e),
432 )
433 })
434 .await?;
435 let credential_present = match kanidm_client
436 .idm_person_account_get_credential_status(&name)
437 .await
438 {
439 Ok(cs) => Some(cs.creds.is_empty().not()),
440 Err(ClientError::EmptyResponse) => Some(false),
441 Err(_) => None,
442 };
443
444 let status = self.generate_status(current_person, credential_present)?;
445 let status_patch = Patch::Apply(KanidmPersonAccount {
446 status: Some(status.clone()),
447 ..KanidmPersonAccount::default()
448 });
449 debug!(msg = "updating status");
450 trace!(msg = format!("status patch {:?}", status_patch));
451 let patch = PatchParams::apply(PERSON_OPERATOR_NAME).force();
452 let kanidm_api =
453 Api::<KanidmPersonAccount>::namespaced(ctx.kaniop_ctx.client.clone(), &namespace);
454 let _o = kanidm_api
455 .patch_status(&name, &patch, &status_patch)
456 .await
457 .map_err(|e| {
458 Error::KubeError(
459 format!("failed to patch KanidmPersonAccount/status {namespace}/{name}"),
460 Box::new(e),
461 )
462 })?;
463 Ok(status)
464 }
465
466 fn generate_status(
467 &self,
468 person: Option<Entry>,
469 credential_present: Option<bool>,
470 ) -> Result<KanidmPersonAccountStatus> {
471 let now = Utc::now();
472 match person {
473 Some(p) => {
474 let exist_condition = Condition {
475 type_: TYPE_EXISTS.to_string(),
476 status: CONDITION_TRUE.to_string(),
477 reason: "Exists".to_string(),
478 message: "Person exists.".to_string(),
479 last_transition_time: Time(now),
480 observed_generation: self.metadata.generation,
481 };
482
483 let current_person_attributes = KanidmPersonAttributes::from(p.clone());
484 let updated_condition = if self.spec.person_attributes == current_person_attributes
485 {
486 Condition {
487 type_: TYPE_UPDATED.to_string(),
488 status: CONDITION_TRUE.to_string(),
489 reason: REASON_ATTRIBUTES_MATCH.to_string(),
490 message: "Person exists with desired attributes.".to_string(),
491 last_transition_time: Time(now),
492 observed_generation: self.metadata.generation,
493 }
494 } else {
495 Condition {
496 type_: TYPE_UPDATED.to_string(),
497 status: CONDITION_FALSE.to_string(),
498 reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
499 message: "Person exists with different attributes.".to_string(),
500 last_transition_time: Time(now),
501 observed_generation: self.metadata.generation,
502 }
503 };
504
505 let current_person_posix = KanidmAccountPosixAttributes::from(p);
506 let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
507 Condition {
508 type_: TYPE_POSIX_INITIALIZED.to_string(),
509 status: CONDITION_TRUE.to_string(),
510 reason: "PosixInitialized".to_string(),
511 message: "Person exists with POSIX attributes.".to_string(),
512 last_transition_time: Time(now),
513 observed_generation: self.metadata.generation,
514 }
515 } else {
516 Condition {
517 type_: TYPE_POSIX_INITIALIZED.to_string(),
518 status: CONDITION_FALSE.to_string(),
519 reason: "PosixNotInitialized".to_string(),
520 message: "Person exists without POSIX attributes.".to_string(),
521 last_transition_time: Time(now),
522 observed_generation: self.metadata.generation,
523 }
524 };
525
526 let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
527 if posix == ¤t_person_posix {
528 Condition {
529 type_: TYPE_POSIX_UPDATED.to_string(),
530 status: CONDITION_TRUE.to_string(),
531 reason: REASON_ATTRIBUTES_MATCH.to_string(),
532 message: "Person exists with desired POSIX attributes.".to_string(),
533 last_transition_time: Time(now),
534 observed_generation: self.metadata.generation,
535 }
536 } else {
537 Condition {
538 type_: TYPE_POSIX_UPDATED.to_string(),
539 status: CONDITION_FALSE.to_string(),
540 reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
541 message: "Person exists with different POSIX attributes.".to_string(),
542 last_transition_time: Time(now),
543 observed_generation: self.metadata.generation,
544 }
545 }
546 });
547
548 let credentials_condition = credential_present.map(|c| {
549 if c {
550 Condition {
551 type_: TYPE_CREDENTIAL.to_string(),
552 status: CONDITION_TRUE.to_string(),
553 reason: "Present".to_string(),
554 message: "Credentials are present.".to_string(),
555 last_transition_time: Time(now),
556 observed_generation: self.metadata.generation,
557 }
558 } else {
559 Condition {
560 type_: TYPE_CREDENTIAL.to_string(),
561 status: CONDITION_FALSE.to_string(),
562 reason: "NotPresent".to_string(),
563 message: "Credentials are not present.".to_string(),
564 last_transition_time: Time(now),
565 observed_generation: self.metadata.generation,
566 }
567 }
568 });
569
570 let validity_condition = {
571 let valid = if let Some(valid_from) =
572 current_person_attributes.account_valid_from.as_ref()
573 {
574 now > valid_from.0
575 } else {
576 true
577 } && if let Some(expire) =
578 current_person_attributes.account_expire.as_ref()
579 {
580 now < expire.0
581 } else {
582 true
583 };
584
585 if valid {
586 Condition {
587 type_: TYPE_VALIDITY.to_string(),
588 status: CONDITION_TRUE.to_string(),
589 reason: "Valid".to_string(),
590 message: "Account is valid.".to_string(),
591 last_transition_time: Time(now),
592 observed_generation: self.metadata.generation,
593 }
594 } else {
595 Condition {
596 type_: TYPE_VALIDITY.to_string(),
597 status: CONDITION_FALSE.to_string(),
598 reason: "Invalid".to_string(),
599 message: "Account is invalid.".to_string(),
600 last_transition_time: Time(now),
601 observed_generation: self.metadata.generation,
602 }
603 }
604 };
605 let conditions = vec![
606 exist_condition,
607 updated_condition,
608 posix_initialized_condition,
609 validity_condition,
610 ]
611 .into_iter()
612 .chain(credentials_condition)
613 .chain(posix_updated_condition)
614 .collect::<Vec<_>>();
615 let status = conditions
616 .iter()
617 .filter(|c| {
618 c.type_ != TYPE_POSIX_INITIALIZED
619 && c.type_ != TYPE_CREDENTIAL
620 && c.type_ != TYPE_VALIDITY
621 })
622 .all(|c| c.status == CONDITION_TRUE);
623 Ok(KanidmPersonAccountStatus {
624 conditions: Some(conditions),
625 ready: status,
626 gid: current_person_posix.gidnumber,
627 kanidm_ref: self.kanidm_ref(),
628 })
629 }
630 None => {
631 let conditions = vec![Condition {
632 type_: TYPE_EXISTS.to_string(),
633 status: CONDITION_FALSE.to_string(),
634 reason: "NotExists".to_string(),
635 message: "Person is not present.".to_string(),
636 last_transition_time: Time(now),
637 observed_generation: self.metadata.generation,
638 }];
639 Ok(KanidmPersonAccountStatus {
640 conditions: Some(conditions),
641 ready: false,
642 gid: None,
643 kanidm_ref: self.kanidm_ref(),
644 })
645 }
646 }
647 }
648}
649
650pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
651 status
652 .conditions
653 .unwrap_or_default()
654 .iter()
655 .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
656}
657
658pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
659 status
660 .conditions
661 .unwrap_or_default()
662 .iter()
663 .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
664}