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};
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 = "kanidmpersonaccounts",
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    fn eq(&self, other: &Self) -> bool {
123        self.displayname == other.displayname
124            && (self.mail.is_none()
125                || self.mail.as_ref().is_some_and(|m| {
126                    other.mail.as_ref().is_some_and(|o| compare_mail(m, o))
127                }))
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    #[cfg_attr(
160        feature = "schemars",
161        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
162    )]
163    pub conditions: Option<Vec<Condition>>,
164
165    pub ready: bool,
166
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub gid: Option<u32>,
169
170    pub kanidm_ref: String,
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use kanidm_proto::v1::Entry;
177    use std::collections::BTreeMap;
178    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
179    use k8s_openapi::jiff::Timestamp;
180
181    fn create_entry(attrs: BTreeMap<String, Vec<String>>) -> Entry {
182        Entry { attrs }
183    }
184
185    #[test]
186    fn exact_match() {
187        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
188        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
189        let spec_attrs = KanidmPersonAttributes {
190            displayname: "Alice".to_string(),
191            mail: Some(vec!["alice@example.com".to_string()]),
192            legalname: Some("Alice Cooper".to_string()),
193            account_valid_from: Some(Time(timestamp1)),
194            account_expire: Some(Time(timestamp2)),
195        };
196
197        let mut attrs_map = BTreeMap::new();
198        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
199        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
200        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
201        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
202        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
203
204        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
205
206        assert_eq!(spec_attrs, kanidm_attrs);
207    }
208
209    #[test]
210    fn displayname_missing_in_kanidm() {
211        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
212        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
213        let spec_attrs = KanidmPersonAttributes {
214            displayname: "Alice".to_string(),
215            mail: Some(vec!["alice@example.com".to_string()]),
216            legalname: Some("Alice Cooper".to_string()),
217            account_valid_from: Some(Time(timestamp1)),
218            account_expire: Some(Time(timestamp2)),
219        };
220
221        let mut attrs_map = BTreeMap::new();
222        // Missing displayname attribute
223        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
224        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
225        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
226        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
227
228        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
229        // The kanidm_attrs.displayname will be "" due to unwrap_or_default()
230        // So "Alice" != "" -> not equal
231        assert_ne!(spec_attrs, kanidm_attrs);
232    }
233
234    #[test]
235    fn displayname_different() {
236        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
237        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
238        let spec_attrs = KanidmPersonAttributes {
239            displayname: "Alice".to_string(),
240            mail: Some(vec!["alice@example.com".to_string()]),
241            legalname: Some("Alice Cooper".to_string()),
242            account_valid_from: Some(Time(timestamp1)),
243            account_expire: Some(Time(timestamp2)),
244        };
245
246        let mut attrs_map = BTreeMap::new();
247        attrs_map.insert("displayname".to_string(), vec!["Bob".to_string()]); // Different from spec
248        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
249        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
250        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
251        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
252
253        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
254
255        assert_ne!(spec_attrs, kanidm_attrs);
256    }
257
258    #[test]
259    fn mail_missing_in_kanidm() {
260        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
261        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
262        let spec_attrs = KanidmPersonAttributes {
263            displayname: "Alice".to_string(),
264            mail: Some(vec!["alice@example.com".to_string()]), // Spec has mail
265            legalname: Some("Alice Cooper".to_string()),
266            account_valid_from: Some(Time(timestamp1)),
267            account_expire: Some(Time(timestamp2)),
268        };
269
270        let mut attrs_map = BTreeMap::new();
271        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
272        // Missing mail attribute
273        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
274        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
275        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
276
277        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
278        // The kanidm_attrs.mail will be None
279        // So Some(...) != None -> not equal
280        assert_ne!(spec_attrs, kanidm_attrs);
281    }
282
283    #[test]
284    fn mail_different_count() {
285        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
286        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
287        let spec_attrs = KanidmPersonAttributes {
288            displayname: "Alice".to_string(),
289            mail: Some(vec!["alice@example.com".to_string(), "a@test.com".to_string()]), // 2 emails
290            legalname: Some("Alice Cooper".to_string()),
291            account_valid_from: Some(Time(timestamp1)),
292            account_expire: Some(Time(timestamp2)),
293        };
294
295        let mut attrs_map = BTreeMap::new();
296        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
297        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]); // Only 1 email
298        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
299        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
300        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
301
302        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
303
304        assert_ne!(spec_attrs, kanidm_attrs);
305    }
306
307    #[test]
308    fn mail_reordered() {
309        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
310        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
311        let spec_attrs = KanidmPersonAttributes {
312            displayname: "Alice".to_string(),
313            mail: Some(vec!["primary@example.com".to_string(), "secondary@example.com".to_string(), "third@example.com".to_string()]),
314            legalname: Some("Alice Cooper".to_string()),
315            account_valid_from: Some(Time(timestamp1)),
316            account_expire: Some(Time(timestamp2)),
317        };
318
319        let mut attrs_map = BTreeMap::new();
320        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
321        attrs_map.insert("mail".to_string(), vec!["primary@example.com".to_string(), "third@example.com".to_string(), "secondary@example.com".to_string()]);
322        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
323        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
324        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
325
326        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
327        assert_eq!(spec_attrs, kanidm_attrs);
328    }
329
330    #[test]
331    fn mail_order_independent() {
332        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
333        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
334        let spec_attrs = KanidmPersonAttributes {
335            displayname: "Alice".to_string(),
336            mail: Some(vec!["primary@example.com".to_string(), "secondary@example.com".to_string()]),
337            legalname: Some("Alice Cooper".to_string()),
338            account_valid_from: Some(Time(timestamp1)),
339            account_expire: Some(Time(timestamp2)),
340        };
341
342        let mut attrs_map = BTreeMap::new();
343        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
344        attrs_map.insert("mail".to_string(), vec!["secondary@example.com".to_string(), "primary@example.com".to_string()]);
345        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
346        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
347        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
348
349        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
350        assert_eq!(spec_attrs, kanidm_attrs);
351    }
352
353    #[test]
354    fn mail_spec_none_kanidm_has_mail() {
355        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
356        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
357        let spec_attrs = KanidmPersonAttributes {
358            displayname: "Alice".to_string(),
359            mail: None, // Spec doesn't care about mail
360            legalname: Some("Alice Cooper".to_string()),
361            account_valid_from: Some(Time(timestamp1)),
362            account_expire: Some(Time(timestamp2)),
363        };
364
365        let mut attrs_map = BTreeMap::new();
366        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
367        attrs_map.insert("mail".to_string(), vec!["x@example.com".to_string()]); // Kanidm has mail
368        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
369        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
370        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
371
372        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
373        // Since spec.mail.is_none(), the comparison should skip mail
374        assert_eq!(spec_attrs, kanidm_attrs);
375    }
376
377    #[test]
378    fn legalname_spec_some_kanidm_missing() {
379        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
380        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
381        let spec_attrs = KanidmPersonAttributes {
382            displayname: "Alice".to_string(),
383            mail: Some(vec!["alice@example.com".to_string()]),
384            legalname: Some("Alice Cooper".to_string()), // Spec has legalname
385            account_valid_from: Some(Time(timestamp1)),
386            account_expire: Some(Time(timestamp2)),
387        };
388
389        let mut attrs_map = BTreeMap::new();
390        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
391        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
392        // Missing legalname attribute
393        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
394        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
395
396        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
397        // The kanidm_attrs.legalname will be None
398        // So Some("Alice Cooper") != None -> not equal
399        assert_ne!(spec_attrs, kanidm_attrs);
400    }
401
402    #[test]
403    fn legalname_spec_none_kanidm_has_value() {
404        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
405        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
406        let spec_attrs = KanidmPersonAttributes {
407            displayname: "Alice".to_string(),
408            mail: Some(vec!["alice@example.com".to_string()]),
409            legalname: None, // Spec doesn't care about legalname
410            account_valid_from: Some(Time(timestamp1)),
411            account_expire: Some(Time(timestamp2)),
412        };
413
414        let mut attrs_map = BTreeMap::new();
415        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
416        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
417        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]); // Kanidm has legalname
418        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
419        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
420
421        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
422        // Since spec.legalname.is_none(), the comparison should skip legalname
423        assert_eq!(spec_attrs, kanidm_attrs);
424    }
425
426    #[test]
427    fn account_valid_from_matching() {
428        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
429        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
430        let spec_attrs = KanidmPersonAttributes {
431            displayname: "Alice".to_string(),
432            mail: Some(vec!["alice@example.com".to_string()]),
433            legalname: Some("Alice Cooper".to_string()),
434            account_valid_from: Some(Time(timestamp1)),
435            account_expire: Some(Time(timestamp2)),
436        };
437
438        let mut attrs_map = BTreeMap::new();
439        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
440        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
441        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
442        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
443        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
444
445        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
446
447        assert_eq!(spec_attrs, kanidm_attrs);
448    }
449
450    #[test]
451    fn account_valid_from_spec_set_kanidm_missing() {
452        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
453        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
454        let spec_attrs = KanidmPersonAttributes {
455            displayname: "Alice".to_string(),
456            mail: Some(vec!["alice@example.com".to_string()]),
457            legalname: Some("Alice Cooper".to_string()),
458            account_valid_from: Some(Time(timestamp1)), // Spec has time
459            account_expire: Some(Time(timestamp2)),
460        };
461
462        let mut attrs_map = BTreeMap::new();
463        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
464        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
465        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
466        // Missing account_valid_from attribute
467        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
468
469        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
470        // The kanidm_attrs.account_valid_from will be None
471        // So Some(time) != None -> not equal
472        assert_ne!(spec_attrs, kanidm_attrs);
473    }
474
475    #[test]
476    fn account_expire_matching() {
477        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
478        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
479        let spec_attrs = KanidmPersonAttributes {
480            displayname: "Alice".to_string(),
481            mail: Some(vec!["alice@example.com".to_string()]),
482            legalname: Some("Alice Cooper".to_string()),
483            account_valid_from: Some(Time(timestamp1)),
484            account_expire: Some(Time(timestamp2)),
485        };
486
487        let mut attrs_map = BTreeMap::new();
488        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
489        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
490        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
491        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
492        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
493
494        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
495
496        assert_eq!(spec_attrs, kanidm_attrs);
497    }
498
499    #[test]
500    fn minimal_spec() {
501        let spec_attrs = KanidmPersonAttributes {
502            displayname: "Alice".to_string(),
503            mail: None,
504            legalname: None,
505            account_valid_from: None,
506            account_expire: None,
507        };
508
509        let mut attrs_map = BTreeMap::new();
510        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
511        // Other attributes are missing
512
513        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
514
515        assert_eq!(spec_attrs, kanidm_attrs);
516    }
517
518    #[test]
519    fn timestamp_format_roundtrip() {
520        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
521        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
522        let spec_attrs = KanidmPersonAttributes {
523            displayname: "Alice".to_string(),
524            mail: Some(vec!["alice@example.com".to_string()]),
525            legalname: Some("Alice Cooper".to_string()),
526            account_valid_from: Some(Time(timestamp1)),
527            account_expire: Some(Time(timestamp2)),
528        };
529
530        let mut attrs_map = BTreeMap::new();
531        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
532        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
533        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
534        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
535        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
536
537        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
538
539        assert_eq!(spec_attrs, kanidm_attrs);
540    }
541
542    #[test]
543    fn timestamp_different_format() {
544        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
545        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
546        let spec_attrs = KanidmPersonAttributes {
547            displayname: "Alice".to_string(),
548            mail: Some(vec!["alice@example.com".to_string()]),
549            legalname: Some("Alice Cooper".to_string()),
550            account_valid_from: Some(Time(timestamp1)),
551            account_expire: Some(Time(timestamp2)),
552        };
553
554        let mut attrs_map = BTreeMap::new();
555        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
556        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
557        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
558        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00+00:00".to_string()]); // Different format
559        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
560
561        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
562
563        assert_eq!(spec_attrs, kanidm_attrs);
564    }
565
566    #[test]
567    fn displayname_spec_empty_vs_kanidm_missing() {
568        // This is a critical test for the bug scenario
569        let spec_attrs = KanidmPersonAttributes {
570            displayname: "".to_string(), // Spec has empty string
571            mail: None,
572            legalname: None,
573            account_valid_from: None,
574            account_expire: None,
575        };
576
577        let attrs_map = BTreeMap::new();
578        // No displayname attribute at all in Kanidm
579        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
580
581        // Kanidm will have displayname as "" (due to unwrap_or_default())
582        // So "" == "" should be true
583        assert_eq!(spec_attrs, kanidm_attrs);
584    }
585
586    #[test]
587    fn displayname_spec_vs_kanidm_empty() {
588        let spec_attrs = KanidmPersonAttributes {
589            displayname: "Alice".to_string(),
590            mail: None,
591            legalname: None,
592            account_valid_from: None,
593            account_expire: None,
594        };
595
596        let mut attrs_map = BTreeMap::new();
597        attrs_map.insert("displayname".to_string(), vec!["".to_string()]); // Kanidm has empty string
598        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
599
600        // "Alice" != "" should be false
601        assert_ne!(spec_attrs, kanidm_attrs);
602    }
603
604    #[test]
605    fn mail_spec_none_vs_kanidm_empty_vec() {
606        // Test when spec has None but Kanidm has empty vec (not None)
607        let spec_attrs = KanidmPersonAttributes {
608            displayname: "Alice".to_string(),
609            mail: None, // Spec doesn't care about mail
610            legalname: None,
611            account_valid_from: None,
612            account_expire: None,
613        };
614
615        let mut attrs_map = BTreeMap::new();
616        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
617        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
618        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
619
620        // Since spec.mail.is_none(), the comparison should skip mail
621        assert_eq!(spec_attrs, kanidm_attrs);
622    }
623
624    #[test]
625    fn mail_spec_some_vs_kanidm_empty_vec() {
626        // Test when spec has Some but Kanidm has empty vec
627        let spec_attrs = KanidmPersonAttributes {
628            displayname: "Alice".to_string(),
629            mail: Some(vec!["test@example.com".to_string()]), // Spec has mail
630            legalname: None,
631            account_valid_from: None,
632            account_expire: None,
633        };
634
635        let mut attrs_map = BTreeMap::new();
636        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
637        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
638        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
639
640        // Some([..]) != Some([]) should be false
641        assert_ne!(spec_attrs, kanidm_attrs);
642    }
643
644    #[test]
645    fn partial_eq_asymmetry_is_intentional() {
646        // PartialEq is intentionally asymmetric for the "spec vs state" comparison pattern:
647        // - When comparing spec (self) against state (other), if spec has None for a field,
648        //   we skip comparison (operator doesn't manage that field)
649        // - This allows: spec.mail=None + state.mail=Some(...) to be "equal" (no reconcile needed)
650        // - The operator always compares spec vs state in that order, never reversed
651
652        let spec = KanidmPersonAttributes {
653            displayname: "Alice".to_string(),
654            mail: Some(vec!["alice@example.com".to_string()]),
655            legalname: None,
656            account_valid_from: None,
657            account_expire: None,
658        };
659
660        let state = KanidmPersonAttributes {
661            displayname: "Alice".to_string(),
662            mail: Some(vec!["alice@example.com".to_string()]),
663            legalname: Some("Alice Smith".to_string()),
664            account_valid_from: None,
665            account_expire: None,
666        };
667
668        // spec == state: legalname is None in spec, so comparison is skipped -> equal
669        assert_eq!(spec, state);
670
671        // state == spec: legalname is Some in state, compared against None in spec -> not equal
672        assert_ne!(state, spec);
673    }
674}