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    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!["primary@example.com".to_string(), "secondary@example.com".to_string(), "third@example.com".to_string()]),
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!["primary@example.com".to_string(), "third@example.com".to_string(), "secondary@example.com".to_string()]);
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        assert_eq!(spec_attrs, kanidm_attrs);
324    }
325
326    #[test]
327    fn mail_primary_different() {
328        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
329        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
330        let spec_attrs = KanidmPersonAttributes {
331            displayname: "Alice".to_string(),
332            mail: Some(vec!["primary@example.com".to_string(), "secondary@example.com".to_string()]),
333            legalname: Some("Alice Cooper".to_string()),
334            account_valid_from: Some(Time(timestamp1)),
335            account_expire: Some(Time(timestamp2)),
336        };
337
338        let mut attrs_map = BTreeMap::new();
339        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
340        attrs_map.insert("mail".to_string(), vec!["secondary@example.com".to_string(), "primary@example.com".to_string()]);
341        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
342        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
343        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
344
345        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
346        assert_ne!(spec_attrs, kanidm_attrs);
347    }
348
349    #[test]
350    fn mail_spec_none_kanidm_has_mail() {
351        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
352        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
353        let spec_attrs = KanidmPersonAttributes {
354            displayname: "Alice".to_string(),
355            mail: None, // Spec doesn't care about mail
356            legalname: Some("Alice Cooper".to_string()),
357            account_valid_from: Some(Time(timestamp1)),
358            account_expire: Some(Time(timestamp2)),
359        };
360
361        let mut attrs_map = BTreeMap::new();
362        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
363        attrs_map.insert("mail".to_string(), vec!["x@example.com".to_string()]); // Kanidm has mail
364        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
365        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
366        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
367
368        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
369        // Since spec.mail.is_none(), the comparison should skip mail
370        assert_eq!(spec_attrs, kanidm_attrs);
371    }
372
373    #[test]
374    fn legalname_spec_some_kanidm_missing() {
375        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
376        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
377        let spec_attrs = KanidmPersonAttributes {
378            displayname: "Alice".to_string(),
379            mail: Some(vec!["alice@example.com".to_string()]),
380            legalname: Some("Alice Cooper".to_string()), // Spec has legalname
381            account_valid_from: Some(Time(timestamp1)),
382            account_expire: Some(Time(timestamp2)),
383        };
384
385        let mut attrs_map = BTreeMap::new();
386        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
387        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
388        // Missing legalname attribute
389        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
390        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
391
392        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
393        // The kanidm_attrs.legalname will be None
394        // So Some("Alice Cooper") != None -> not equal
395        assert_ne!(spec_attrs, kanidm_attrs);
396    }
397
398    #[test]
399    fn legalname_spec_none_kanidm_has_value() {
400        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
401        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
402        let spec_attrs = KanidmPersonAttributes {
403            displayname: "Alice".to_string(),
404            mail: Some(vec!["alice@example.com".to_string()]),
405            legalname: None, // Spec doesn't care about legalname
406            account_valid_from: Some(Time(timestamp1)),
407            account_expire: Some(Time(timestamp2)),
408        };
409
410        let mut attrs_map = BTreeMap::new();
411        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
412        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
413        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]); // Kanidm has legalname
414        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
415        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
416
417        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
418        // Since spec.legalname.is_none(), the comparison should skip legalname
419        assert_eq!(spec_attrs, kanidm_attrs);
420    }
421
422    #[test]
423    fn account_valid_from_matching() {
424        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
425        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
426        let spec_attrs = KanidmPersonAttributes {
427            displayname: "Alice".to_string(),
428            mail: Some(vec!["alice@example.com".to_string()]),
429            legalname: Some("Alice Cooper".to_string()),
430            account_valid_from: Some(Time(timestamp1)),
431            account_expire: Some(Time(timestamp2)),
432        };
433
434        let mut attrs_map = BTreeMap::new();
435        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
436        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
437        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
438        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
439        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
440
441        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
442
443        assert_eq!(spec_attrs, kanidm_attrs);
444    }
445
446    #[test]
447    fn account_valid_from_spec_set_kanidm_missing() {
448        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
449        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
450        let spec_attrs = KanidmPersonAttributes {
451            displayname: "Alice".to_string(),
452            mail: Some(vec!["alice@example.com".to_string()]),
453            legalname: Some("Alice Cooper".to_string()),
454            account_valid_from: Some(Time(timestamp1)), // Spec has time
455            account_expire: Some(Time(timestamp2)),
456        };
457
458        let mut attrs_map = BTreeMap::new();
459        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
460        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
461        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
462        // Missing account_valid_from attribute
463        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
464
465        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
466        // The kanidm_attrs.account_valid_from will be None
467        // So Some(time) != None -> not equal
468        assert_ne!(spec_attrs, kanidm_attrs);
469    }
470
471    #[test]
472    fn account_expire_matching() {
473        let timestamp1 = Timestamp::from_second(1672531200).unwrap();
474        let timestamp2 = Timestamp::from_second(1704067200).unwrap();
475        let spec_attrs = KanidmPersonAttributes {
476            displayname: "Alice".to_string(),
477            mail: Some(vec!["alice@example.com".to_string()]),
478            legalname: Some("Alice Cooper".to_string()),
479            account_valid_from: Some(Time(timestamp1)),
480            account_expire: Some(Time(timestamp2)),
481        };
482
483        let mut attrs_map = BTreeMap::new();
484        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
485        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
486        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
487        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
488        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
489
490        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
491
492        assert_eq!(spec_attrs, kanidm_attrs);
493    }
494
495    #[test]
496    fn minimal_spec() {
497        let spec_attrs = KanidmPersonAttributes {
498            displayname: "Alice".to_string(),
499            mail: None,
500            legalname: None,
501            account_valid_from: None,
502            account_expire: None,
503        };
504
505        let mut attrs_map = BTreeMap::new();
506        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
507        // Other attributes are missing
508
509        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
510
511        assert_eq!(spec_attrs, kanidm_attrs);
512    }
513
514    #[test]
515    fn timestamp_format_roundtrip() {
516        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
517        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
518        let spec_attrs = KanidmPersonAttributes {
519            displayname: "Alice".to_string(),
520            mail: Some(vec!["alice@example.com".to_string()]),
521            legalname: Some("Alice Cooper".to_string()),
522            account_valid_from: Some(Time(timestamp1)),
523            account_expire: Some(Time(timestamp2)),
524        };
525
526        let mut attrs_map = BTreeMap::new();
527        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
528        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
529        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
530        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00Z".to_string()]);
531        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
532
533        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
534
535        assert_eq!(spec_attrs, kanidm_attrs);
536    }
537
538    #[test]
539    fn timestamp_different_format() {
540        let timestamp1 = Timestamp::from_second(1672531200).unwrap(); // 2023-01-01T00:00:00Z
541        let timestamp2 = Timestamp::from_second(1704067200).unwrap(); // 2024-01-01T00:00:00Z
542        let spec_attrs = KanidmPersonAttributes {
543            displayname: "Alice".to_string(),
544            mail: Some(vec!["alice@example.com".to_string()]),
545            legalname: Some("Alice Cooper".to_string()),
546            account_valid_from: Some(Time(timestamp1)),
547            account_expire: Some(Time(timestamp2)),
548        };
549
550        let mut attrs_map = BTreeMap::new();
551        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
552        attrs_map.insert("mail".to_string(), vec!["alice@example.com".to_string()]);
553        attrs_map.insert("legalname".to_string(), vec!["Alice Cooper".to_string()]);
554        attrs_map.insert("account_valid_from".to_string(), vec!["2023-01-01T00:00:00+00:00".to_string()]); // Different format
555        attrs_map.insert("account_expire".to_string(), vec!["2024-01-01T00:00:00Z".to_string()]);
556
557        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
558
559        assert_eq!(spec_attrs, kanidm_attrs);
560    }
561
562    #[test]
563    fn displayname_spec_empty_vs_kanidm_missing() {
564        // This is a critical test for the bug scenario
565        let spec_attrs = KanidmPersonAttributes {
566            displayname: "".to_string(), // Spec has empty string
567            mail: None,
568            legalname: None,
569            account_valid_from: None,
570            account_expire: None,
571        };
572
573        let attrs_map = BTreeMap::new();
574        // No displayname attribute at all in Kanidm
575        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
576
577        // Kanidm will have displayname as "" (due to unwrap_or_default())
578        // So "" == "" should be true
579        assert_eq!(spec_attrs, kanidm_attrs);
580    }
581
582    #[test]
583    fn displayname_spec_vs_kanidm_empty() {
584        let spec_attrs = KanidmPersonAttributes {
585            displayname: "Alice".to_string(),
586            mail: None,
587            legalname: None,
588            account_valid_from: None,
589            account_expire: None,
590        };
591
592        let mut attrs_map = BTreeMap::new();
593        attrs_map.insert("displayname".to_string(), vec!["".to_string()]); // Kanidm has empty string
594        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
595
596        // "Alice" != "" should be false
597        assert_ne!(spec_attrs, kanidm_attrs);
598    }
599
600    #[test]
601    fn mail_spec_none_vs_kanidm_empty_vec() {
602        // Test when spec has None but Kanidm has empty vec (not None)
603        let spec_attrs = KanidmPersonAttributes {
604            displayname: "Alice".to_string(),
605            mail: None, // Spec doesn't care about mail
606            legalname: None,
607            account_valid_from: None,
608            account_expire: None,
609        };
610
611        let mut attrs_map = BTreeMap::new();
612        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
613        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
614        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
615
616        // Since spec.mail.is_none(), the comparison should skip mail
617        assert_eq!(spec_attrs, kanidm_attrs);
618    }
619
620    #[test]
621    fn mail_spec_some_vs_kanidm_empty_vec() {
622        // Test when spec has Some but Kanidm has empty vec
623        let spec_attrs = KanidmPersonAttributes {
624            displayname: "Alice".to_string(),
625            mail: Some(vec!["test@example.com".to_string()]), // Spec has mail
626            legalname: None,
627            account_valid_from: None,
628            account_expire: None,
629        };
630
631        let mut attrs_map = BTreeMap::new();
632        attrs_map.insert("displayname".to_string(), vec!["Alice".to_string()]);
633        attrs_map.insert("mail".to_string(), vec![]); // Kanidm has empty mail vector
634        let kanidm_attrs = KanidmPersonAttributes::from(create_entry(attrs_map));
635
636        // Some([..]) != Some([]) should be false
637        assert_ne!(spec_attrs, kanidm_attrs);
638    }
639
640    #[test]
641    fn partial_eq_asymmetry_is_intentional() {
642        // PartialEq is intentionally asymmetric for the "spec vs state" comparison pattern:
643        // - When comparing spec (self) against state (other), if spec has None for a field,
644        //   we skip comparison (operator doesn't manage that field)
645        // - This allows: spec.mail=None + state.mail=Some(...) to be "equal" (no reconcile needed)
646        // - The operator always compares spec vs state in that order, never reversed
647
648        let spec = KanidmPersonAttributes {
649            displayname: "Alice".to_string(),
650            mail: Some(vec!["alice@example.com".to_string()]),
651            legalname: None,
652            account_valid_from: None,
653            account_expire: None,
654        };
655
656        let state = KanidmPersonAttributes {
657            displayname: "Alice".to_string(),
658            mail: Some(vec!["alice@example.com".to_string()]),
659            legalname: Some("Alice Smith".to_string()),
660            account_valid_from: None,
661            account_expire: None,
662        };
663
664        // spec == state: legalname is None in spec, so comparison is skipped -> equal
665        assert_eq!(spec, state);
666
667        // state == spec: legalname is Some in state, compared against None in spec -> not equal
668        assert_ne!(state, spec);
669    }
670}