Skip to main content

kaniop_person/
crd.rs

1use kaniop_k8s_util::types::{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};
15
16/// A person represents a human's account in Kanidm. The majority of your users will be a person who
17/// will use this account in their daily activities. These entries may contain personally
18/// identifying information that is considered by Kanidm to be sensitive. Because of this, there
19/// are default limits to who may access these data.
20/// More info:
21/// https://kanidm.github.io/kanidm/master/accounts/people_accounts.html
22#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
23#[cfg_attr(feature = "schemars", derive(JsonSchema))]
24#[kube(
25    category = "kaniop",
26    group = "kaniop.rs",
27    version = "v1beta1",
28    kind = "KanidmPersonAccount",
29    plural = "kanidmpersonsaccounts",
30    singular = "kanidmpersonaccount",
31    shortname = "person",
32    namespaced,
33    status = "KanidmPersonAccountStatus",
34    doc = r#"The Kanidm person account custom resource definition (CRD) defines a person account in Kanidm."#,
35    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".status.kanidmRef"}"#,
36    printcolumn = r#"{"name":"GID","type":"integer","jsonPath":".status.gid"}"#,
37    printcolumn = r#"{"name":"Valid","type":"string","jsonPath":".status.conditions[?(@.type == 'Valid')].status"}"#,
38    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
39    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
40    derive = "Default"
41)]
42#[serde(rename_all = "camelCase")]
43pub struct KanidmPersonAccountSpec {
44    pub kanidm_ref: KanidmRef,
45
46    /// The name of the entity in Kanidm. If not specified, the Kubernetes resource name is used.
47    /// Use this field to manage Kanidm entities with names that don't conform to Kubernetes naming rules
48    /// (e.g., entities with underscores like `idm_admin` or `idm_all_persons`).
49    /// This field is immutable and cannot be changed after creation.
50    #[schemars(extend("x-kubernetes-validations" = [{"message": "kanidmName cannot be changed.", "rule": "self == oldSelf"}]))]
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub kanidm_name: Option<String>,
53
54    pub person_attributes: KanidmPersonAttributes,
55    /// POSIX attributes for the person account. When specified, the operator will activate them.
56    /// If omitted, the operator retains the attributes in the database but ceases to manage them.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub posix_attributes: Option<KanidmAccountPosixAttributes>,
59
60    /// If credentials are not defined, Kaniop will generate a link accessible when describing
61    /// the person account. This link will be valid for the number of seconds defined here.
62    /// The default is 3600 seconds (1 hour).
63    #[serde(
64        default = "default_credentials_token_ttl",
65        skip_serializing_if = "is_default"
66    )]
67    pub credentials_token_ttl: u32,
68}
69
70impl KanidmResource for KanidmPersonAccount {
71    #[inline]
72    fn kanidm_ref_spec(&self) -> &KanidmRef {
73        &self.spec.kanidm_ref
74    }
75
76    #[inline]
77    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
78        &kanidm.spec.person_namespace_selector
79    }
80
81    #[inline]
82    fn kanidm_name_override(&self) -> Option<&str> {
83        self.spec.kanidm_name.as_deref()
84    }
85}
86
87/// Attributes that personally identify a person account.
88///
89/// The attributes defined here are set by the operator. If you want to manage those attributes
90/// from the database, do not set them here.
91/// Additionally, if you unset them here, they will be kept in the database.
92#[derive(Serialize, Deserialize, Clone, Debug, Default)]
93#[cfg_attr(feature = "schemars", derive(JsonSchema))]
94#[serde(rename_all = "camelCase")]
95pub struct KanidmPersonAttributes {
96    /// Set the display name for the person.
97    pub displayname: String,
98
99    /// Set the mail address, can be set multiple times for multiple addresses. The first listed
100    /// mail address is the 'primary'.
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub mail: Option<Vec<String>>,
103
104    /// Set the legal name for the person.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub legalname: Option<String>,
107
108    /// Set an account valid from time.
109    ///
110    /// If omitted, the account will be valid from the time of creation.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub account_valid_from: Option<Time>,
113
114    /// Set an accounts expiry time.
115    ///
116    /// If omitted, the account will not expire.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub account_expire: Option<Time>,
119}
120
121impl PartialEq for KanidmPersonAttributes {
122    /// Compare attributes defined in the first object with the second object values.
123    /// If the second object has more attributes defined, they will be ignored.
124    fn eq(&self, other: &Self) -> bool {
125        self.displayname == other.displayname
126            // comparison is ordered because first mail is primary
127            && (self.mail.is_none() || self.mail == other.mail)
128            && (self.legalname.is_none() || self.legalname == other.legalname)
129            && (self.account_valid_from.is_none()
130                || self.account_valid_from == other.account_valid_from)
131            && (self.account_expire.is_none() || self.account_expire == other.account_expire)
132    }
133}
134
135impl From<Entry> for KanidmPersonAttributes {
136    fn from(entry: Entry) -> Self {
137        KanidmPersonAttributes {
138            displayname: get_first_cloned(&entry, ATTR_DISPLAYNAME).unwrap_or_default(),
139            mail: entry.attrs.get(ATTR_MAIL).cloned(),
140            legalname: get_first_cloned(&entry, ATTR_LEGALNAME),
141            account_valid_from: parse_time(&entry, ATTR_ACCOUNT_VALID_FROM),
142            account_expire: parse_time(&entry, ATTR_ACCOUNT_EXPIRE),
143        }
144    }
145}
146
147fn default_credentials_token_ttl() -> u32 {
148    3600
149}
150
151/// Most recent observed status of the Kanidm Person Account. Read-only.
152/// More info:
153/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
154#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
155#[cfg_attr(feature = "schemars", derive(JsonSchema))]
156#[serde(rename_all = "camelCase")]
157pub struct KanidmPersonAccountStatus {
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub conditions: Option<Vec<Condition>>,
160
161    pub ready: bool,
162
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub gid: Option<u32>,
165
166    pub kanidm_ref: String,
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use kanidm_proto::v1::Entry;
173    use std::collections::BTreeMap;
174    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
175    use k8s_openapi::jiff::Timestamp;
176
177    fn create_entry(attrs: BTreeMap<String, Vec<String>>) -> Entry {
178        Entry { attrs }
179    }
180
181    #[test]
182    fn exact_match() {
183        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
184        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
185        let spec_attrs = KanidmPersonAttributes {
186            displayname: "Alice".to_string(),
187            mail: Some(vec!["alice@example.com".to_string()]),
188            legalname: Some("Alice Cooper".to_string()),
189            account_valid_from: Some(Time(timestamp1)),
190            account_expire: Some(Time(timestamp2)),
191        };
192
193        let mut attrs_map = BTreeMap::new();
194        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
195        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
196        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
197        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
198        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
199
200        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
201
202        assert_eq!(spec_attrs, kanidm_attrs);
203    }
204
205    #[test]
206    fn displayname_missing_in_kanidm() {
207        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
208        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
209        let spec_attrs = KanidmPersonAttributes {
210            displayname: "Alice".to_string(),
211            mail: Some(vec!["alice@example.com".to_string()]),
212            legalname: Some("Alice Cooper".to_string()),
213            account_valid_from: Some(Time(timestamp1)),
214            account_expire: Some(Time(timestamp2)),
215        };
216
217        let mut attrs_map = BTreeMap::new();
218        // Missing displayname attribute
219        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
220        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
221        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
222        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
223
224        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
225        // The kanidm_attrs.displayname will be "" due to unwrap_or_default()
226        // So "Alice" != "" -> not equal
227        assert_ne!(spec_attrs, kanidm_attrs);
228    }
229
230    #[test]
231    fn displayname_different() {
232        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
233        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
234        let spec_attrs = KanidmPersonAttributes {
235            displayname: "Alice".to_string(),
236            mail: Some(vec!["alice@example.com".to_string()]),
237            legalname: Some("Alice Cooper".to_string()),
238            account_valid_from: Some(Time(timestamp1)),
239            account_expire: Some(Time(timestamp2)),
240        };
241
242        let mut attrs_map = BTreeMap::new();
243        attrs_map.insert("displayname".to_string(), vec!["Bob".to_string()]); // Different from spec
244        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
245        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
246        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
247        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
248
249        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
250
251        assert_ne!(spec_attrs, kanidm_attrs);
252    }
253
254    #[test]
255    fn mail_missing_in_kanidm() {
256        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
257        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
258        let spec_attrs = KanidmPersonAttributes {
259            displayname: "Alice".to_string(),
260            mail: Some(vec!["alice@example.com".to_string()]), // Spec has mail
261            legalname: Some("Alice Cooper".to_string()),
262            account_valid_from: Some(Time(timestamp1)),
263            account_expire: Some(Time(timestamp2)),
264        };
265
266        let mut attrs_map = BTreeMap::new();
267        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
268        // Missing mail attribute
269        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
270        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
271        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
272
273        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
274        // The kanidm_attrs.mail will be None
275        // So Some(...) != None -> not equal
276        assert_ne!(spec_attrs, kanidm_attrs);
277    }
278
279    #[test]
280    fn mail_different_count() {
281        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
282        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
283        let spec_attrs = KanidmPersonAttributes {
284            displayname: "Alice".to_string(),
285            mail: Some(vec!["alice@example.com".to_string(), "a@test.com".to_string()]), // 2 emails
286            legalname: Some("Alice Cooper".to_string()),
287            account_valid_from: Some(Time(timestamp1)),
288            account_expire: Some(Time(timestamp2)),
289        };
290
291        let mut attrs_map = BTreeMap::new();
292        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
293        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]); // Only 1 email
294        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
295        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
296        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
297
298        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
299
300        assert_ne!(spec_attrs, kanidm_attrs);
301    }
302
303    #[test]
304    fn mail_reordered() {
305        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
306        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
307        let spec_attrs = KanidmPersonAttributes {
308            displayname: "Alice".to_string(),
309            mail: Some(vec!["a@b.com".to_string(), "c@d.com".to_string()]), // Order matters
310            legalname: Some("Alice Cooper".to_string()),
311            account_valid_from: Some(Time(timestamp1)),
312            account_expire: Some(Time(timestamp2)),
313        };
314
315        let mut attrs_map = BTreeMap::new();
316        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
317        attrs_map.insert("mail".to_string(), vec!["c@d.com".to_string(), "a@b.com".to_string()]); // Reordered
318        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
319        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
320        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
321
322        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
323        // Mail order is different, so they're not equal
324        assert_ne!(spec_attrs, kanidm_attrs);
325    }
326
327    #[test]
328    fn mail_spec_none_kanidm_has_mail() {
329        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
330        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
331        let spec_attrs = KanidmPersonAttributes {
332            displayname: "Alice".to_string(),
333            mail: None, // Spec doesn't care about mail
334            legalname: Some("Alice Cooper".to_string()),
335            account_valid_from: Some(Time(timestamp1)),
336            account_expire: Some(Time(timestamp2)),
337        };
338
339        let mut attrs_map = BTreeMap::new();
340        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
341        attrs_map.insert("mail".to_string(), vec!["x@example.com".to_string()]); // Kanidm has mail
342        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
343        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
344        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
345
346        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
347        // Since spec.mail.is_none(), the comparison should skip mail
348        assert_eq!(spec_attrs, kanidm_attrs);
349    }
350
351    #[test]
352    fn legalname_spec_some_kanidm_missing() {
353        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
354        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
355        let spec_attrs = KanidmPersonAttributes {
356            displayname: "Alice".to_string(),
357            mail: Some(vec!["alice@example.com".to_string()]),
358            legalname: Some("Alice Cooper".to_string()), // Spec has legalname
359            account_valid_from: Some(Time(timestamp1)),
360            account_expire: Some(Time(timestamp2)),
361        };
362
363        let mut attrs_map = BTreeMap::new();
364        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
365        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
366        // Missing legalname attribute
367        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
368        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
369
370        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
371        // The kanidm_attrs.legalname will be None
372        // So Some("Alice Cooper") != None -> not equal
373        assert_ne!(spec_attrs, kanidm_attrs);
374    }
375
376    #[test]
377    fn legalname_spec_none_kanidm_has_value() {
378        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
379        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
380        let spec_attrs = KanidmPersonAttributes {
381            displayname: "Alice".to_string(),
382            mail: Some(vec!["alice@example.com".to_string()]),
383            legalname: None, // Spec doesn't care about legalname
384            account_valid_from: Some(Time(timestamp1)),
385            account_expire: Some(Time(timestamp2)),
386        };
387
388        let mut attrs_map = BTreeMap::new();
389        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
390        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
391        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]); // Kanidm has legalname
392        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
393        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
394
395        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
396        // Since spec.legalname.is_none(), the comparison should skip legalname
397        assert_eq!(spec_attrs, kanidm_attrs);
398    }
399
400    #[test]
401    fn account_valid_from_matching() {
402        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
403        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
404        let spec_attrs = KanidmPersonAttributes {
405            displayname: "Alice".to_string(),
406            mail: Some(vec!["alice@example.com".to_string()]),
407            legalname: Some("Alice Cooper".to_string()),
408            account_valid_from: Some(Time(timestamp1)),
409            account_expire: Some(Time(timestamp2)),
410        };
411
412        let mut attrs_map = BTreeMap::new();
413        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
414        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
415        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
416        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
417        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
418
419        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
420
421        assert_eq!(spec_attrs, kanidm_attrs);
422    }
423
424    #[test]
425    fn account_valid_from_spec_set_kanidm_missing() {
426        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
427        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
428        let spec_attrs = KanidmPersonAttributes {
429            displayname: "Alice".to_string(),
430            mail: Some(vec!["alice@example.com".to_string()]),
431            legalname: Some("Alice Cooper".to_string()),
432            account_valid_from: Some(Time(timestamp1)), // Spec has time
433            account_expire: Some(Time(timestamp2)),
434        };
435
436        let mut attrs_map = BTreeMap::new();
437        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
438        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
439        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
440        // Missing account_valid_from attribute
441        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
442
443        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
444        // The kanidm_attrs.account_valid_from will be None
445        // So Some(time) != None -> not equal
446        assert_ne!(spec_attrs, kanidm_attrs);
447    }
448
449    #[test]
450    fn account_expire_matching() {
451        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
452        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
453        let spec_attrs = KanidmPersonAttributes {
454            displayname: "Alice".to_string(),
455            mail: Some(vec!["alice@example.com".to_string()]),
456            legalname: Some("Alice Cooper".to_string()),
457            account_valid_from: Some(Time(timestamp1)),
458            account_expire: Some(Time(timestamp2)),
459        };
460
461        let mut attrs_map = BTreeMap::new();
462        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
463        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
464        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
465        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
466        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
467
468        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
469
470        assert_eq!(spec_attrs, kanidm_attrs);
471    }
472
473    #[test]
474    fn minimal_spec() {
475        let spec_attrs = KanidmPersonAttributes {
476            displayname: "Alice".to_string(),
477            mail: None,
478            legalname: None,
479            account_valid_from: None,
480            account_expire: None,
481        };
482
483        let mut attrs_map = BTreeMap::new();
484        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
485        // Other attributes are missing
486
487        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
488
489        assert_eq!(spec_attrs, kanidm_attrs);
490    }
491
492    #[test]
493    fn timestamp_format_roundtrip() {
494        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
495        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
496        let spec_attrs = KanidmPersonAttributes {
497            displayname: "Alice".to_string(),
498            mail: Some(vec!["alice@example.com".to_string()]),
499            legalname: Some("Alice Cooper".to_string()),
500            account_valid_from: Some(Time(timestamp1)),
501            account_expire: Some(Time(timestamp2)),
502        };
503
504        let mut attrs_map = BTreeMap::new();
505        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
506        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
507        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
508        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
509        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
510
511        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
512
513        assert_eq!(spec_attrs, kanidm_attrs);
514    }
515
516    #[test]
517    fn timestamp_different_format() {
518        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
519        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
520        let spec_attrs = KanidmPersonAttributes {
521            displayname: "Alice".to_string(),
522            mail: Some(vec!["alice@example.com".to_string()]),
523            legalname: Some("Alice Cooper".to_string()),
524            account_valid_from: Some(Time(timestamp1)),
525            account_expire: Some(Time(timestamp2)),
526        };
527
528        let mut attrs_map = BTreeMap::new();
529        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
530        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
531        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
532        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00+00:00".to_string()]); // Different format
533        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
534
535        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
536
537        assert_eq!(spec_attrs, kanidm_attrs);
538    }
539
540    #[test]
541    fn displayname_spec_empty_vs_kanidm_missing() {
542        // This is a critical test for the bug scenario
543        let spec_attrs = KanidmPersonAttributes {
544            displayname: "".to_string(), // Spec has empty string
545            mail: None,
546            legalname: None,
547            account_valid_from: None,
548            account_expire: None,
549        };
550
551        let attrs_map = BTreeMap::new();
552        // No displayname attribute at all in Kanidm
553        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
554
555        // Kanidm will have displayname as "" (due to unwrap_or_default())
556        // So "" == "" should be true
557        assert_eq!(spec_attrs, kanidm_attrs);
558    }
559
560    #[test]
561    fn displayname_spec_vs_kanidm_empty() {
562        let spec_attrs = KanidmPersonAttributes {
563            displayname: "Alice".to_string(),
564            mail: None,
565            legalname: None,
566            account_valid_from: None,
567            account_expire: None,
568        };
569
570        let mut attrs_map = BTreeMap::new();
571        attrs_map.insert("displayname".to_string(), vec!["".to_string()]); // Kanidm has empty string
572        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
573
574        // "Alice" != "" should be false
575        assert_ne!(spec_attrs, kanidm_attrs);
576    }
577
578    #[test]
579    fn mail_spec_none_vs_kanidm_empty_vec() {
580        // Test when spec has None but Kanidm has empty vec (not None)
581        let spec_attrs = KanidmPersonAttributes {
582            displayname: "Alice".to_string(),
583            mail: None, // Spec doesn't care about mail
584            legalname: None,
585            account_valid_from: None,
586            account_expire: None,
587        };
588
589        let mut attrs_map = BTreeMap::new();
590        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
591        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
592        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
593
594        // Since spec.mail.is_none(), the comparison should skip mail
595        assert_eq!(spec_attrs, kanidm_attrs);
596    }
597
598    #[test]
599    fn mail_spec_some_vs_kanidm_empty_vec() {
600        // Test when spec has Some but Kanidm has empty vec
601        let spec_attrs = KanidmPersonAttributes {
602            displayname: "Alice".to_string(),
603            mail: Some(vec!["test@example.com".to_string()]), // Spec has mail
604            legalname: None,
605            account_valid_from: None,
606            account_expire: None,
607        };
608
609        let mut attrs_map = BTreeMap::new();
610        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
611        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
612        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
613
614        // Some([..]) != Some([]) should be false
615        assert_ne!(spec_attrs, kanidm_attrs);
616    }
617
618    #[test]
619    fn asymmetry_bug_test() {
620        // This test demonstrates the asymmetry bug in the PartialEq implementation
621        // The issue: when comparing spec vs current state, the logic is:
622        // "if spec has None for a field, ignore that field"
623        // But this doesn't work correctly when comparing in both directions
624
625        let spec_with_mail = KanidmPersonAttributes {
626            displayname: "Alice".to_string(),
627            mail: Some(vec!["alice@example.com".to_string()]),
628            legalname: None, // Spec doesn't specify legalname
629            account_valid_from: None,
630            account_expire: None,
631        };
632
633        let current_state = KanidmPersonAttributes {
634            displayname: "Alice".to_string(),
635            mail: Some(vec!["alice@example.com".to_string()]),
636            legalname: Some("Alice Smith".to_string()), // Current state has legalname
637            account_valid_from: None,
638            account_expire: None,
639        };
640
641        // According to the current logic:
642        // - displayname: "Alice" == "Alice" -> true
643        // - mail: Some(...) == Some(...) -> true
644        // - legalname: spec.legalname.is_none() so skip -> true (equality achieved by ignoring)
645        // So spec_with_mail == current_state should be true
646        assert_eq!(spec_with_mail, current_state);
647
648        // Now let's flip the comparison (should be symmetric for PartialEq)
649        // BUT in the reverse, legalname: Some("Alice Smith") vs None
650        // Since current_state.legalname is Some, we compare: Some("Alice Smith") == None -> false
651        // So current_state == spec_with_mail should be false
652        // If this assertion fails, it means the PartialEq is violating symmetry!
653        assert_ne!(current_state, spec_with_mail);
654
655        // This proves the asymmetry: a == b is true but b == a is false!
656        // This violates the symmetry contract of PartialEq and can cause infinite loops
657    }
658}