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::KubeError("failed to publish event".to_string(), Box::new(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::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(idm_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 .unwrap_or_else(|_| expiry_time.to_string())
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(idm_reconcile_interval()))
419 }
420
421 async fn update_status(
422 &self,
423 kanidm_client: Arc<KanidmClient>,
424 ctx: Arc<Context>,
425 ) -> Result<KanidmPersonAccountStatus> {
426 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(&self.name_any(), &patch, &status_patch)
463 .await
464 .map_err(|e| {
465 Error::KubeError(
466 format!(
467 "failed to patch KanidmPersonAccount/status {namespace}/{name}",
468 name = self.name_any()
469 ),
470 Box::new(e),
471 )
472 })?;
473 Ok(status)
474 }
475
476 fn generate_status(
477 &self,
478 person: Option<Entry>,
479 credential_present: Option<bool>,
480 ) -> Result<KanidmPersonAccountStatus> {
481 let now = Timestamp::now();
482 match person {
483 Some(p) => {
484 let exist_condition = Condition {
485 type_: TYPE_EXISTS.to_string(),
486 status: CONDITION_TRUE.to_string(),
487 reason: "Exists".to_string(),
488 message: "Person exists.".to_string(),
489 last_transition_time: Time(now),
490 observed_generation: self.metadata.generation,
491 };
492
493 let current_person_attributes = KanidmPersonAttributes::from(p.clone());
494 let updated_condition = if self.spec.person_attributes == current_person_attributes
495 {
496 Condition {
497 type_: TYPE_UPDATED.to_string(),
498 status: CONDITION_TRUE.to_string(),
499 reason: REASON_ATTRIBUTES_MATCH.to_string(),
500 message: "Person exists with desired attributes.".to_string(),
501 last_transition_time: Time(now),
502 observed_generation: self.metadata.generation,
503 }
504 } else {
505 Condition {
506 type_: TYPE_UPDATED.to_string(),
507 status: CONDITION_FALSE.to_string(),
508 reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
509 message: "Person exists with different attributes.".to_string(),
510 last_transition_time: Time(now),
511 observed_generation: self.metadata.generation,
512 }
513 };
514
515 let current_person_posix = KanidmAccountPosixAttributes::from(p);
516 let posix_initialized_condition = if current_person_posix.gidnumber.is_some() {
517 Condition {
518 type_: TYPE_POSIX_INITIALIZED.to_string(),
519 status: CONDITION_TRUE.to_string(),
520 reason: "PosixInitialized".to_string(),
521 message: "Person exists with POSIX attributes.".to_string(),
522 last_transition_time: Time(now),
523 observed_generation: self.metadata.generation,
524 }
525 } else {
526 Condition {
527 type_: TYPE_POSIX_INITIALIZED.to_string(),
528 status: CONDITION_FALSE.to_string(),
529 reason: "PosixNotInitialized".to_string(),
530 message: "Person exists without POSIX attributes.".to_string(),
531 last_transition_time: Time(now),
532 observed_generation: self.metadata.generation,
533 }
534 };
535
536 let posix_updated_condition = self.spec.posix_attributes.as_ref().map(|posix| {
537 if posix == ¤t_person_posix {
538 Condition {
539 type_: TYPE_POSIX_UPDATED.to_string(),
540 status: CONDITION_TRUE.to_string(),
541 reason: REASON_ATTRIBUTES_MATCH.to_string(),
542 message: "Person exists with desired POSIX attributes.".to_string(),
543 last_transition_time: Time(now),
544 observed_generation: self.metadata.generation,
545 }
546 } else {
547 Condition {
548 type_: TYPE_POSIX_UPDATED.to_string(),
549 status: CONDITION_FALSE.to_string(),
550 reason: REASON_ATTRIBUTES_NOT_MATCH.to_string(),
551 message: "Person exists with different POSIX attributes.".to_string(),
552 last_transition_time: Time(now),
553 observed_generation: self.metadata.generation,
554 }
555 }
556 });
557
558 let credentials_condition = credential_present.map(|c| {
559 if c {
560 Condition {
561 type_: TYPE_CREDENTIAL.to_string(),
562 status: CONDITION_TRUE.to_string(),
563 reason: "Present".to_string(),
564 message: "Credentials are present.".to_string(),
565 last_transition_time: Time(now),
566 observed_generation: self.metadata.generation,
567 }
568 } else {
569 Condition {
570 type_: TYPE_CREDENTIAL.to_string(),
571 status: CONDITION_FALSE.to_string(),
572 reason: "NotPresent".to_string(),
573 message: "Credentials are not present.".to_string(),
574 last_transition_time: Time(now),
575 observed_generation: self.metadata.generation,
576 }
577 }
578 });
579
580 let validity_condition = {
581 let valid = if let Some(valid_from) =
582 current_person_attributes.account_valid_from.as_ref()
583 {
584 now > valid_from.0
585 } else {
586 true
587 } && if let Some(expire) =
588 current_person_attributes.account_expire.as_ref()
589 {
590 now < expire.0
591 } else {
592 true
593 };
594
595 if valid {
596 Condition {
597 type_: TYPE_VALIDITY.to_string(),
598 status: CONDITION_TRUE.to_string(),
599 reason: "Valid".to_string(),
600 message: "Account is valid.".to_string(),
601 last_transition_time: Time(now),
602 observed_generation: self.metadata.generation,
603 }
604 } else {
605 Condition {
606 type_: TYPE_VALIDITY.to_string(),
607 status: CONDITION_FALSE.to_string(),
608 reason: "Invalid".to_string(),
609 message: "Account is invalid.".to_string(),
610 last_transition_time: Time(now),
611 observed_generation: self.metadata.generation,
612 }
613 }
614 };
615 let conditions = vec![
616 exist_condition,
617 updated_condition,
618 posix_initialized_condition,
619 validity_condition,
620 ]
621 .into_iter()
622 .chain(credentials_condition)
623 .chain(posix_updated_condition)
624 .collect::<Vec<_>>();
625 let status = conditions
626 .iter()
627 .filter(|c| {
628 c.type_ != TYPE_POSIX_INITIALIZED
629 && c.type_ != TYPE_CREDENTIAL
630 && c.type_ != TYPE_VALIDITY
631 })
632 .all(|c| c.status == CONDITION_TRUE);
633 Ok(KanidmPersonAccountStatus {
634 conditions: Some(conditions),
635 ready: status,
636 gid: current_person_posix.gidnumber,
637 kanidm_ref: self.kanidm_ref(),
638 })
639 }
640 None => {
641 let conditions = vec![Condition {
642 type_: TYPE_EXISTS.to_string(),
643 status: CONDITION_FALSE.to_string(),
644 reason: "NotExists".to_string(),
645 message: "Person is not present.".to_string(),
646 last_transition_time: Time(now),
647 observed_generation: self.metadata.generation,
648 }];
649 Ok(KanidmPersonAccountStatus {
650 conditions: Some(conditions),
651 ready: false,
652 gid: None,
653 kanidm_ref: self.kanidm_ref(),
654 })
655 }
656 }
657 }
658}
659
660pub fn is_person(type_: &str, status: KanidmPersonAccountStatus) -> bool {
661 status
662 .conditions
663 .unwrap_or_default()
664 .iter()
665 .any(|c| c.type_ == type_ && c.status == CONDITION_TRUE)
666}
667
668pub fn is_person_false(type_: &str, status: KanidmPersonAccountStatus) -> bool {
669 status
670 .conditions
671 .unwrap_or_default()
672 .iter()
673 .any(|c| c.type_ == type_ && c.status == CONDITION_FALSE)
674}