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