Skip to main content

kaniop_person/
crd.rs

1use kaniop_k8s_util::types::{compare_mail, get_first_cloned, parse_time};
2use kaniop_operator::controller::kanidm::KanidmResource;
3use kaniop_operator::crd::{is_default, KanidmAccountPosixAttributes, KanidmRef};
4use kaniop_operator::kanidm::crd::Kanidm;
5
6use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector, Time};
7use kanidm_proto::constants::{
8    ATTR_ACCOUNT_EXPIRE, ATTR_ACCOUNT_VALID_FROM, ATTR_DISPLAYNAME, ATTR_LEGALNAME, ATTR_MAIL,
9};
10use kanidm_proto::v1::Entry;
11use kube::CustomResource;
12#[cfg(feature = "schemars")]
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16
17/// A person represents a human's account in Kanidm. The majority of your users will be a person who
18/// will use this account in their daily activities. These entries may contain personally
19/// identifying information that is considered by Kanidm to be sensitive. Because of this, there
20/// are default limits to who may access these data.
21/// More info:
22/// https://kanidm.github.io/kanidm/master/accounts/people_accounts.html
23#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
24#[cfg_attr(feature = "schemars", derive(JsonSchema))]
25#[kube(
26    category = "kaniop",
27    group = "kaniop.rs",
28    version = "v1beta1",
29    kind = "KanidmPersonAccount",
30    plural = "kanidmpersonaccounts",
31    singular = "kanidmpersonaccount",
32    shortname = "person",
33    namespaced,
34    status = "KanidmPersonAccountStatus",
35    doc = r#"The Kanidm person account custom resource definition (CRD) defines a person account in Kanidm."#,
36    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".status.kanidmRef"}"#,
37    printcolumn = r#"{"name":"GID","type":"integer","jsonPath":".status.gid"}"#,
38    printcolumn = r#"{"name":"Valid","type":"string","jsonPath":".status.conditions[?(@.type == 'Valid')].status"}"#,
39    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
40    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
41    derive = "Default"
42)]
43#[serde(rename_all = "camelCase")]
44pub struct KanidmPersonAccountSpec {
45    pub kanidm_ref: KanidmRef,
46
47    /// The name of the entity in Kanidm. If not specified, the Kubernetes resource name is used.
48    /// Use this field to manage Kanidm entities with names that don't conform to Kubernetes naming rules
49    /// (e.g., entities with underscores like `idm_admin` or `idm_all_persons`).
50    /// This field is immutable and cannot be changed after creation.
51    #[schemars(extend("x-kubernetes-validations" = [{"message": "kanidmName cannot be changed.", "rule": "self == oldSelf"}]))]
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub kanidm_name: Option<String>,
54
55    pub person_attributes: KanidmPersonAttributes,
56    /// POSIX attributes for the person account. When specified, the operator will activate them.
57    /// If omitted, the operator retains the attributes in the database but ceases to manage them.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub posix_attributes: Option<KanidmAccountPosixAttributes>,
60
61    /// SSH public keys managed by Kaniop, indexed by their Kanidm tag.
62    /// Keys added directly in Kanidm under other tags are preserved.
63    /// If omitted, SSH keys are not managed. An empty map removes previously managed keys.
64    /// Kanidm performs the validation of SSH key material.
65    /// The map is a single atomic unit for server-side apply ownership.
66    #[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-map-type" = "atomic")))]
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub ssh_public_keys: Option<BTreeMap<String, String>>,
69
70    /// If credentials are not defined, Kaniop will generate a link accessible when describing
71    /// the person account. This link will be valid for the number of seconds defined here.
72    /// The default is 3600 seconds (1 hour).
73    #[serde(
74        default = "default_credentials_token_ttl",
75        skip_serializing_if = "is_default"
76    )]
77    pub credentials_token_ttl: u32,
78
79    /// How to deliver initial credential bootstrap invitations. Defaults to Kubernetes Events.
80    /// Email delivery must be explicitly enabled per person. Re-sends use a metadata annotation.
81    #[serde(default, skip_serializing_if = "is_default")]
82    pub credential_bootstrap_delivery: CredentialBootstrapDelivery,
83}
84
85/// Available credential bootstrap delivery methods.
86#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
87#[cfg_attr(feature = "schemars", derive(JsonSchema))]
88#[serde(rename_all = "camelCase")]
89pub enum CredentialBootstrapDelivery {
90    #[default]
91    Event,
92    Email,
93}
94
95impl KanidmResource for KanidmPersonAccount {
96    #[inline]
97    fn kanidm_ref_spec(&self) -> &KanidmRef {
98        &self.spec.kanidm_ref
99    }
100
101    #[inline]
102    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
103        &kanidm.spec.person_namespace_selector
104    }
105
106    #[inline]
107    fn kanidm_name_override(&self) -> Option<&str> {
108        self.spec.kanidm_name.as_deref()
109    }
110}
111
112/// Attributes that personally identify a person account.
113///
114/// The attributes defined here are set by the operator. If you want to manage those attributes
115/// from the database, do not set them here.
116/// Additionally, if you unset them here, they will be kept in the database.
117#[derive(Serialize, Deserialize, Clone, Debug, Default)]
118#[cfg_attr(feature = "schemars", derive(JsonSchema))]
119#[serde(rename_all = "camelCase")]
120pub struct KanidmPersonAttributes {
121    /// Set the display name for the person.
122    pub displayname: String,
123
124    /// Set the mail address, can be set multiple times for multiple addresses. The first listed
125    /// mail address is the 'primary'.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub mail: Option<Vec<String>>,
128
129    /// Set the legal name for the person.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub legalname: Option<String>,
132
133    /// Set an account valid from time.
134    ///
135    /// If omitted, the account will be valid from the time of creation.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub account_valid_from: Option<Time>,
138
139    /// Set an accounts expiry time.
140    ///
141    /// If omitted, the account will not expire.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub account_expire: Option<Time>,
144}
145
146impl PartialEq for KanidmPersonAttributes {
147    fn eq(&self, other: &Self) -> bool {
148        self.displayname == other.displayname
149            && (self.mail.is_none()
150                || self.mail.as_ref().is_some_and(|m| {
151                    other.mail.as_ref().is_some_and(|o| compare_mail(m, o))
152                }))
153            && (self.legalname.is_none() || self.legalname == other.legalname)
154            && (self.account_valid_from.is_none()
155                || self.account_valid_from == other.account_valid_from)
156            && (self.account_expire.is_none() || self.account_expire == other.account_expire)
157    }
158}
159
160impl From<Entry> for KanidmPersonAttributes {
161    fn from(entry: Entry) -> Self {
162        KanidmPersonAttributes {
163            displayname: get_first_cloned(&entry, ATTR_DISPLAYNAME).unwrap_or_default(),
164            mail: entry.attrs.get(ATTR_MAIL).cloned(),
165            legalname: get_first_cloned(&entry, ATTR_LEGALNAME),
166            account_valid_from: parse_time(&entry, ATTR_ACCOUNT_VALID_FROM),
167            account_expire: parse_time(&entry, ATTR_ACCOUNT_EXPIRE),
168        }
169    }
170}
171
172fn default_credentials_token_ttl() -> u32 {
173    3600
174}
175
176/// Observed credential presence. `Unknown` is fail-closed: it must never trigger credential
177/// bootstrap or reset-token creation.
178#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
179#[cfg_attr(feature = "schemars", derive(JsonSchema))]
180#[serde(rename_all = "camelCase")]
181pub enum CredentialState {
182    #[default]
183    Unknown,
184    Present,
185    Absent,
186}
187
188/// Lifecycle of the initial credential bootstrap for a person account.
189#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
190#[cfg_attr(feature = "schemars", derive(JsonSchema))]
191#[serde(rename_all = "camelCase")]
192pub enum CredentialBootstrapState {
193    #[default]
194    Pending,
195    TokenIssued,
196    Complete,
197}
198
199/// Persistent bootstrap state. Keeping the token expiry in status prevents operator restarts from
200/// generating duplicate reset tokens while preserving the existing retry-after-expiry behaviour.
201#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
202#[cfg_attr(feature = "schemars", derive(JsonSchema))]
203#[serde(rename_all = "camelCase")]
204pub struct CredentialBootstrapStatus {
205    #[serde(default)]
206    pub state: CredentialBootstrapState,
207
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub token_expires_at: Option<Time>,
210
211    /// The successful delivery method for the current bootstrap attempt.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub delivery_method: Option<CredentialBootstrapDelivery>,
214
215    /// Highest resend revision whose email was accepted into Kanidm's queue.
216    /// Kept across changes to the configured delivery method.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub last_queued_resend_revision: Option<u32>,
219
220    /// When Kanidm accepted an email into its outgoing queue (not SMTP delivery).
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub email_queued_at: Option<Time>,
223
224    /// A known blocking reason; cleared after a successful bootstrap request.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub delivery_error: Option<String>,
227}
228
229/// Most recent observed status of the Kanidm Person Account. Read-only.
230/// More info:
231/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
232#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
233#[cfg_attr(feature = "schemars", derive(JsonSchema))]
234#[serde(rename_all = "camelCase")]
235pub struct KanidmPersonAccountStatus {
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    #[cfg_attr(
238        feature = "schemars",
239        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
240    )]
241    pub conditions: Option<Vec<Condition>>,
242
243    pub ready: bool,
244
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub gid: Option<u32>,
247
248    pub kanidm_ref: String,
249
250    #[serde(default)]
251    pub credential_state: CredentialState,
252
253    #[serde(default)]
254    pub credential_bootstrap: CredentialBootstrapStatus,
255
256    /// Tags claimed by this resource after successful synchronization with Kanidm.
257    /// Used to revoke only keys previously managed by Kaniop.
258    #[serde(default)]
259    #[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-list-type" = "set")))]
260    pub managed_ssh_public_key_tags: Vec<String>,
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use kanidm_proto::v1::Entry;
267    use std::collections::BTreeMap;
268    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
269    use k8s_openapi::jiff::Timestamp;
270
271    fn create_entry(attrs: BTreeMap<String, Vec<String>>) -> Entry {
272        Entry { attrs }
273    }
274
275    #[test]
276    fn credential_bootstrap_delivery_defaults_to_event_and_serializes_flat() {
277        let spec = KanidmPersonAccountSpec::default();
278        assert_eq!(
279            spec.credential_bootstrap_delivery,
280            CredentialBootstrapDelivery::Event
281        );
282        let default_json = serde_json::to_value(&spec).unwrap();
283        assert!(default_json.get("credentialBootstrap").is_none());
284        // The field is skipped while it holds the default, except in example generation where
285        // `is_default` always serializes so every option gets documented. A workspace-wide
286        // `cargo test` unifies that feature into this crate, so assert against the same predicate
287        // the serde attribute uses instead of a fixed expectation.
288        if is_default(&CredentialBootstrapDelivery::Event) {
289            assert!(default_json.get("credentialBootstrapDelivery").is_none());
290        } else {
291            assert_eq!(default_json["credentialBootstrapDelivery"], "event");
292        }
293
294        let minimal = serde_json::json!({
295            "kanidmRef": {"name": "idm"},
296            "personAttributes": {"displayname": "Alice"},
297        });
298        let omitted: KanidmPersonAccountSpec = serde_json::from_value(minimal).unwrap();
299        assert_eq!(
300            omitted.credential_bootstrap_delivery,
301            CredentialBootstrapDelivery::Event
302        );
303
304        let mut email = spec;
305        email.credential_bootstrap_delivery = CredentialBootstrapDelivery::Email;
306        let email_json = serde_json::to_value(&email).unwrap();
307        assert_eq!(email_json["credentialBootstrapDelivery"], "email");
308        assert!(email_json.get("credentialBootstrap").is_none());
309
310        let deserialized: KanidmPersonAccountSpec =
311            serde_json::from_value(email_json).unwrap();
312        assert_eq!(
313            deserialized.credential_bootstrap_delivery,
314            CredentialBootstrapDelivery::Email
315        );
316    }
317
318    #[test]
319    fn exact_match() {
320        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
321        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
322        let spec_attrs = KanidmPersonAttributes {
323            displayname: "Alice".to_string(),
324            mail: Some(vec!["alice@example.com".to_string()]),
325            legalname: Some("Alice Cooper".to_string()),
326            account_valid_from: Some(Time(timestamp1)),
327            account_expire: Some(Time(timestamp2)),
328        };
329
330        let mut attrs_map = BTreeMap::new();
331        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
332        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
333        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
334        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
335        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
336
337        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
338
339        assert_eq!(spec_attrs, kanidm_attrs);
340    }
341
342    #[test]
343    fn displayname_missing_in_kanidm() {
344        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
345        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
346        let spec_attrs = KanidmPersonAttributes {
347            displayname: "Alice".to_string(),
348            mail: Some(vec!["alice@example.com".to_string()]),
349            legalname: Some("Alice Cooper".to_string()),
350            account_valid_from: Some(Time(timestamp1)),
351            account_expire: Some(Time(timestamp2)),
352        };
353
354        let mut attrs_map = BTreeMap::new();
355        // Missing displayname attribute
356        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
357        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
358        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
359        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
360
361        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
362        // The kanidm_attrs.displayname will be "" due to unwrap_or_default()
363        // So "Alice" != "" -> not equal
364        assert_ne!(spec_attrs, kanidm_attrs);
365    }
366
367    #[test]
368    fn displayname_different() {
369        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
370        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
371        let spec_attrs = KanidmPersonAttributes {
372            displayname: "Alice".to_string(),
373            mail: Some(vec!["alice@example.com".to_string()]),
374            legalname: Some("Alice Cooper".to_string()),
375            account_valid_from: Some(Time(timestamp1)),
376            account_expire: Some(Time(timestamp2)),
377        };
378
379        let mut attrs_map = BTreeMap::new();
380        attrs_map.insert("displayname".to_string(), vec!["Bob".to_string()]); // Different from spec
381        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
382        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
383        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
384        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
385
386        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
387
388        assert_ne!(spec_attrs, kanidm_attrs);
389    }
390
391    #[test]
392    fn mail_missing_in_kanidm() {
393        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
394        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
395        let spec_attrs = KanidmPersonAttributes {
396            displayname: "Alice".to_string(),
397            mail: Some(vec!["alice@example.com".to_string()]), // Spec has mail
398            legalname: Some("Alice Cooper".to_string()),
399            account_valid_from: Some(Time(timestamp1)),
400            account_expire: Some(Time(timestamp2)),
401        };
402
403        let mut attrs_map = BTreeMap::new();
404        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
405        // Missing mail attribute
406        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
407        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
408        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
409
410        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
411        // The kanidm_attrs.mail will be None
412        // So Some(...) != None -> not equal
413        assert_ne!(spec_attrs, kanidm_attrs);
414    }
415
416    #[test]
417    fn mail_different_count() {
418        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
419        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
420        let spec_attrs = KanidmPersonAttributes {
421            displayname: "Alice".to_string(),
422            mail: Some(vec!["alice@example.com".to_string(), "a@test.com".to_string()]), // 2 emails
423            legalname: Some("Alice Cooper".to_string()),
424            account_valid_from: Some(Time(timestamp1)),
425            account_expire: Some(Time(timestamp2)),
426        };
427
428        let mut attrs_map = BTreeMap::new();
429        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
430        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]); // Only 1 email
431        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
432        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
433        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
434
435        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
436
437        assert_ne!(spec_attrs, kanidm_attrs);
438    }
439
440    #[test]
441    fn mail_reordered() {
442        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
443        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
444        let spec_attrs = KanidmPersonAttributes {
445            displayname: "Alice".to_string(),
446            mail: Some(vec!["primary@example.com".to_string(), "secondary@example.com".to_string(), "third@example.com".to_string()]),
447            legalname: Some("Alice Cooper".to_string()),
448            account_valid_from: Some(Time(timestamp1)),
449            account_expire: Some(Time(timestamp2)),
450        };
451
452        let mut attrs_map = BTreeMap::new();
453        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
454        attrs_map.insert("mail".to_string(), vec!["primary@example.com".to_string(), "third@example.com".to_string(), "secondary@example.com".to_string()]);
455        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
456        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
457        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
458
459        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
460        assert_eq!(spec_attrs, kanidm_attrs);
461    }
462
463    #[test]
464    fn mail_order_independent() {
465        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
466        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
467        let spec_attrs = KanidmPersonAttributes {
468            displayname: "Alice".to_string(),
469            mail: Some(vec!["primary@example.com".to_string(), "secondary@example.com".to_string()]),
470            legalname: Some("Alice Cooper".to_string()),
471            account_valid_from: Some(Time(timestamp1)),
472            account_expire: Some(Time(timestamp2)),
473        };
474
475        let mut attrs_map = BTreeMap::new();
476        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
477        attrs_map.insert("mail".to_string(), vec!["secondary@example.com".to_string(), "primary@example.com".to_string()]);
478        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
479        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
480        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
481
482        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
483        assert_eq!(spec_attrs, kanidm_attrs);
484    }
485
486    #[test]
487    fn mail_spec_none_kanidm_has_mail() {
488        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
489        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
490        let spec_attrs = KanidmPersonAttributes {
491            displayname: "Alice".to_string(),
492            mail: None, // Spec doesn't care about mail
493            legalname: Some("Alice Cooper".to_string()),
494            account_valid_from: Some(Time(timestamp1)),
495            account_expire: Some(Time(timestamp2)),
496        };
497
498        let mut attrs_map = BTreeMap::new();
499        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
500        attrs_map.insert("mail".to_string(), vec!["x@example.com".to_string()]); // Kanidm has mail
501        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
502        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
503        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
504
505        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
506        // Since spec.mail.is_none(), the comparison should skip mail
507        assert_eq!(spec_attrs, kanidm_attrs);
508    }
509
510    #[test]
511    fn legalname_spec_some_kanidm_missing() {
512        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
513        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
514        let spec_attrs = KanidmPersonAttributes {
515            displayname: "Alice".to_string(),
516            mail: Some(vec!["alice@example.com".to_string()]),
517            legalname: Some("Alice Cooper".to_string()), // Spec has legalname
518            account_valid_from: Some(Time(timestamp1)),
519            account_expire: Some(Time(timestamp2)),
520        };
521
522        let mut attrs_map = BTreeMap::new();
523        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
524        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
525        // Missing legalname attribute
526        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
527        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
528
529        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
530        // The kanidm_attrs.legalname will be None
531        // So Some("Alice Cooper") != None -> not equal
532        assert_ne!(spec_attrs, kanidm_attrs);
533    }
534
535    #[test]
536    fn legalname_spec_none_kanidm_has_value() {
537        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
538        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
539        let spec_attrs = KanidmPersonAttributes {
540            displayname: "Alice".to_string(),
541            mail: Some(vec!["alice@example.com".to_string()]),
542            legalname: None, // Spec doesn't care about legalname
543            account_valid_from: Some(Time(timestamp1)),
544            account_expire: Some(Time(timestamp2)),
545        };
546
547        let mut attrs_map = BTreeMap::new();
548        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
549        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
550        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]); // Kanidm has legalname
551        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
552        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
553
554        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
555        // Since spec.legalname.is_none(), the comparison should skip legalname
556        assert_eq!(spec_attrs, kanidm_attrs);
557    }
558
559    #[test]
560    fn account_valid_from_matching() {
561        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
562        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
563        let spec_attrs = KanidmPersonAttributes {
564            displayname: "Alice".to_string(),
565            mail: Some(vec!["alice@example.com".to_string()]),
566            legalname: Some("Alice Cooper".to_string()),
567            account_valid_from: Some(Time(timestamp1)),
568            account_expire: Some(Time(timestamp2)),
569        };
570
571        let mut attrs_map = BTreeMap::new();
572        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
573        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
574        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
575        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
576        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
577
578        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
579
580        assert_eq!(spec_attrs, kanidm_attrs);
581    }
582
583    #[test]
584    fn account_valid_from_spec_set_kanidm_missing() {
585        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
586        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
587        let spec_attrs = KanidmPersonAttributes {
588            displayname: "Alice".to_string(),
589            mail: Some(vec!["alice@example.com".to_string()]),
590            legalname: Some("Alice Cooper".to_string()),
591            account_valid_from: Some(Time(timestamp1)), // Spec has time
592            account_expire: Some(Time(timestamp2)),
593        };
594
595        let mut attrs_map = BTreeMap::new();
596        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
597        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
598        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
599        // Missing account_valid_from attribute
600        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
601
602        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
603        // The kanidm_attrs.account_valid_from will be None
604        // So Some(time) != None -> not equal
605        assert_ne!(spec_attrs, kanidm_attrs);
606    }
607
608    #[test]
609    fn account_expire_matching() {
610        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
611        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
612        let spec_attrs = KanidmPersonAttributes {
613            displayname: "Alice".to_string(),
614            mail: Some(vec!["alice@example.com".to_string()]),
615            legalname: Some("Alice Cooper".to_string()),
616            account_valid_from: Some(Time(timestamp1)),
617            account_expire: Some(Time(timestamp2)),
618        };
619
620        let mut attrs_map = BTreeMap::new();
621        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
622        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
623        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
624        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
625        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
626
627        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
628
629        assert_eq!(spec_attrs, kanidm_attrs);
630    }
631
632    #[test]
633    fn minimal_spec() {
634        let spec_attrs = KanidmPersonAttributes {
635            displayname: "Alice".to_string(),
636            mail: None,
637            legalname: None,
638            account_valid_from: None,
639            account_expire: None,
640        };
641
642        let mut attrs_map = BTreeMap::new();
643        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
644        // Other attributes are missing
645
646        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
647
648        assert_eq!(spec_attrs, kanidm_attrs);
649    }
650
651    #[test]
652    fn timestamp_format_roundtrip() {
653        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
654        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
655        let spec_attrs = KanidmPersonAttributes {
656            displayname: "Alice".to_string(),
657            mail: Some(vec!["alice@example.com".to_string()]),
658            legalname: Some("Alice Cooper".to_string()),
659            account_valid_from: Some(Time(timestamp1)),
660            account_expire: Some(Time(timestamp2)),
661        };
662
663        let mut attrs_map = BTreeMap::new();
664        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
665        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
666        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
667        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
668        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
669
670        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
671
672        assert_eq!(spec_attrs, kanidm_attrs);
673    }
674
675    #[test]
676    fn timestamp_different_format() {
677        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
678        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
679        let spec_attrs = KanidmPersonAttributes {
680            displayname: "Alice".to_string(),
681            mail: Some(vec!["alice@example.com".to_string()]),
682            legalname: Some("Alice Cooper".to_string()),
683            account_valid_from: Some(Time(timestamp1)),
684            account_expire: Some(Time(timestamp2)),
685        };
686
687        let mut attrs_map = BTreeMap::new();
688        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
689        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
690        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
691        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00+00:00".to_string()]); // Different format
692        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
693
694        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
695
696        assert_eq!(spec_attrs, kanidm_attrs);
697    }
698
699    #[test]
700    fn displayname_spec_empty_vs_kanidm_missing() {
701        // This is a critical test for the bug scenario
702        let spec_attrs = KanidmPersonAttributes {
703            displayname: "".to_string(), // Spec has empty string
704            mail: None,
705            legalname: None,
706            account_valid_from: None,
707            account_expire: None,
708        };
709
710        let attrs_map = BTreeMap::new();
711        // No displayname attribute at all in Kanidm
712        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
713
714        // Kanidm will have displayname as "" (due to unwrap_or_default())
715        // So "" == "" should be true
716        assert_eq!(spec_attrs, kanidm_attrs);
717    }
718
719    #[test]
720    fn displayname_spec_vs_kanidm_empty() {
721        let spec_attrs = KanidmPersonAttributes {
722            displayname: "Alice".to_string(),
723            mail: None,
724            legalname: None,
725            account_valid_from: None,
726            account_expire: None,
727        };
728
729        let mut attrs_map = BTreeMap::new();
730        attrs_map.insert("displayname".to_string(), vec!["".to_string()]); // Kanidm has empty string
731        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
732
733        // "Alice" != "" should be false
734        assert_ne!(spec_attrs, kanidm_attrs);
735    }
736
737    #[test]
738    fn mail_spec_none_vs_kanidm_empty_vec() {
739        // Test when spec has None but Kanidm has empty vec (not None)
740        let spec_attrs = KanidmPersonAttributes {
741            displayname: "Alice".to_string(),
742            mail: None, // Spec doesn't care about mail
743            legalname: None,
744            account_valid_from: None,
745            account_expire: None,
746        };
747
748        let mut attrs_map = BTreeMap::new();
749        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
750        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
751        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
752
753        // Since spec.mail.is_none(), the comparison should skip mail
754        assert_eq!(spec_attrs, kanidm_attrs);
755    }
756
757    #[test]
758    fn mail_spec_some_vs_kanidm_empty_vec() {
759        // Test when spec has Some but Kanidm has empty vec
760        let spec_attrs = KanidmPersonAttributes {
761            displayname: "Alice".to_string(),
762            mail: Some(vec!["test@example.com".to_string()]), // Spec has mail
763            legalname: None,
764            account_valid_from: None,
765            account_expire: None,
766        };
767
768        let mut attrs_map = BTreeMap::new();
769        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
770        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
771        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
772
773        // Some([..]) != Some([]) should be false
774        assert_ne!(spec_attrs, kanidm_attrs);
775    }
776
777    #[test]
778    fn partial_eq_asymmetry_is_intentional() {
779        // PartialEq is intentionally asymmetric for the "spec vs state" comparison pattern:
780        // - When comparing spec (self) against state (other), if spec has None for a field,
781        //   we skip comparison (operator doesn't manage that field)
782        // - This allows: spec.mail=None + state.mail=Some(...) to be "equal" (no reconcile needed)
783        // - The operator always compares spec vs state in that order, never reversed
784
785        let spec = KanidmPersonAttributes {
786            displayname: "Alice".to_string(),
787            mail: Some(vec!["alice@example.com".to_string()]),
788            legalname: None,
789            account_valid_from: None,
790            account_expire: None,
791        };
792
793        let state = KanidmPersonAttributes {
794            displayname: "Alice".to_string(),
795            mail: Some(vec!["alice@example.com".to_string()]),
796            legalname: Some("Alice Smith".to_string()),
797            account_valid_from: None,
798            account_expire: None,
799        };
800
801        // spec == state: legalname is None in spec, so comparison is skipped -> equal
802        assert_eq!(spec, state);
803
804        // state == spec: legalname is Some in state, compared against None in spec -> not equal
805        assert_ne!(state, spec);
806    }
807}