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