Skip to main content

kaniop_person/
crd.rs

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