Skip to main content

kaniop_oauth2/
crd.rs

1use kaniop_k8s_util::types::normalize_spn;
2use kaniop_operator::controller::kanidm::KanidmResource;
3use kaniop_operator::crd::{KanidmRef, SecretRotation, MetadataTemplate};
4use kaniop_operator::kanidm::crd::Kanidm;
5
6use std::{
7    collections::{BTreeSet, HashMap},
8    ops::Not,
9};
10
11use kanidm_proto::internal::Oauth2ClaimMapJoin;
12
13use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
14use kube::CustomResource;
15#[cfg(feature = "schemars")]
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// The KanidmOAuth2Client custom resource definition (CRD) defines an OAuth2 client integration in
20/// Kanidm. This resource allows you to configure OAuth2 clients that can interact with the Kanidm
21/// authorization server. The CRD supports various configurations, including scope maps,
22/// claim maps, and other OAuth2 client settings.
23/// More info:
24/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
25#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
26#[cfg_attr(feature = "schemars", derive(JsonSchema))]
27#[kube(
28    category = "kaniop",
29    group = "kaniop.rs",
30    version = "v1beta1",
31    kind = "KanidmOAuth2Client",
32    plural = "kanidmoauth2clients",
33    singular = "kanidmoauth2client",
34    shortname = "oauth2",
35    namespaced,
36    status = "KanidmOAuth2ClientStatus",
37    doc = r#"The Kanidm OAuth2 client custom resource definition (CRD) defines an OAuth2 client
38    integration in Kanidm."#,
39    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".status.kanidmRef"}"#,
40    printcolumn = r#"{"name":"Public","type":"string","jsonPath":".spec.public"}"#,
41    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
42    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
43    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
44    derive = "Default"
45)]
46#[serde(rename_all = "camelCase")]
47pub struct KanidmOAuth2ClientSpec {
48    pub kanidm_ref: KanidmRef,
49
50    /// The name of the entity in Kanidm. If not specified, the Kubernetes resource name is used.
51    /// Use this field to manage Kanidm entities with names that don't conform to Kubernetes naming rules
52    /// (e.g., entities with underscores like `idm_admin` or `idm_all_persons`).
53    /// This field is immutable and cannot be changed after creation.
54    #[schemars(extend("x-kubernetes-validations" = [{"message": "kanidmName cannot be changed.", "rule": "self == oldSelf"}]))]
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub kanidm_name: Option<String>,
57
58    /// Set the display name for the OAuth2 client.
59    pub displayname: String,
60
61    /// Set the landing page (home page) of the client. The landing page is where users will be
62    /// redirected to from the Kanidm application portal.
63    pub origin: String,
64
65    /// Set the URL where the application expects OAuth2 requests to be sent.
66    pub redirect_url: Vec<String>,
67
68    /// Create a new OAuth2 public client that requires PKCE. You should prefer using confidential
69    /// client types if possible over public ones.
70    ///
71    /// Public clients have many limitations and can not access all API's of OAuth2. For example
72    /// rfc7662 token introspection requires client authentication.
73    ///
74    /// This cannot be changed after creation. Default value is false.
75    /// This field is immutable.
76    /// If public is false, the operator will create a secret containing the client secret with
77    /// the name `<oauth2-client-name>-kanidm-oauth2-credentials` in the same namespace as the OAuth2 client.
78    #[schemars(extend("x-kubernetes-validations" = [{"message": "Public cannot be changed.", "rule": "self == oldSelf"}]))]
79    #[serde(default)]
80    pub public: bool,
81
82    /// Main scope map for the OAuth2 client. For an authorization to proceed, all scopes requested
83    /// by the client must be available in the final scope set that is granted to the account.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub scope_map: Option<BTreeSet<KanidmScopeMap>>,
86
87    /// Supplementary scope maps for the OAuth2 client. These function the same as scope maps where
88    /// membership of a group provides a set of scopes to the account.
89    /// However these scopes are NOT consulted during authorization decisions made by Kanidm.
90    /// These scopes exist to allow optional properties to be provided (such as personal
91    /// information about a subset of accounts to be revealed) or so that the service may make its
92    /// own authorization decisions based on the provided scopes.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub sup_scope_map: Option<BTreeSet<KanidmScopeMap>>,
95
96    /// Mapping from a group to a custom claims that it provides to members.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub claim_map: Option<BTreeSet<KanidmClaimMap>>,
99
100    /// Enable strict validation of redirect URLs. Previously redirect URLs only validated the
101    /// origin of the URL matched. When enabled, redirect URLs must match exactly.
102    ///
103    /// Enabled by default.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub strict_redirect_url: Option<bool>,
106
107    /// Use the 'name' attribute instead of 'spn' for the preferred_username.
108    ///
109    /// Disabled by default.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub prefer_short_username: Option<bool>,
112
113    /// Allow public clients to redirect to localhost.
114    ///
115    /// Just public clients can allow localhost redirect.
116    /// Disabled by default.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub allow_localhost_redirect: Option<bool>,
119
120    /// Disable PKCE on this oauth2 client to work around insecure clients that may not support it.
121    /// You should request the client to enable PKCE!
122    ///
123    /// Public clients cannot disable PKCE.
124    /// PKCE is enabled by default.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub allow_insecure_client_disable_pkce: Option<bool>,
127
128    /// Enable legacy signing crypto on this oauth2 client. This defaults to being disabled.
129    /// You only need to enable this for openid clients that do not support modern cryptographic
130    /// operations.
131    ///
132    /// Disabled by default.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub jwt_legacy_crypto_enable: Option<bool>,
135
136    /// Disable the consent prompt for this OAuth2 client. This allows skipping the user
137    /// consent screen for well-known admin-managed applications. When enabled, users will
138    /// not be prompted to grant consent when authorizing with this client.
139    ///
140    /// Disabled by default.
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub disable_consent_prompt: Option<bool>,
143
144    /// Refresh token lifetime in seconds for this OAuth2 client.
145    /// If omitted, Kaniop leaves the Kanidm attribute unchanged (and new clients use
146    /// Kanidm's default of 16 hours). Removing this field does not reset a value
147    /// previously managed by Kaniop. Longer lifetimes increase the impact of token theft.
148    #[schemars(range(min = 1))]
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub refresh_token_expiry: Option<u32>,
151
152    /// Automatic rotation configuration for the OAuth2 client secret. Only applies to confidential
153    /// clients (public: false). When enabled, the operator will regenerate the client secret
154    /// periodically based on the configured rotation period.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub secret_rotation: Option<SecretRotation>,
157
158    /// Template applied to the Secret created for confidential clients (public: false).
159    /// Allows attaching custom annotations and labels to the generated Secret. The operator's own
160    /// labels and annotations take precedence over any conflicting keys in the template.
161    /// Changes to this template are enforced on the next reconciliation, overwriting any manual
162    /// modifications made to the Secret
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub secret_template: Option<MetadataTemplate>,
165
166    /// Aliases for the canonical secret keys (CLIENT_ID and CLIENT_SECRET).
167    /// Allows consumers that require different fixed key names to access the same credentials.
168    /// The canonical keys CLIENT_ID and CLIENT_SECRET are always present.
169    /// Only applies to confidential clients (public: false).
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub secret_key_aliases: Option<SecretKeyAliases>,
172
173    /// Optional URL to an image for the OAuth2 client application.
174    /// The image will be downloaded and set in Kanidm for display in the application portal.
175    /// Constraints:
176    /// - Maximum size: 256 KB
177    /// - Maximum dimensions: 1024 x 1024 pixels
178    /// - Supported formats: png, jpg, gif, svg, webp
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub image: Option<OAuth2ClientImageSpec>,
181}
182
183#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
184#[cfg_attr(feature = "schemars", derive(JsonSchema))]
185#[serde(rename_all = "camelCase")]
186pub struct OAuth2ClientImageSpec {
187    /// URL to fetch the image from (HTTP/HTTPS only).
188    /// The operator will periodically check this URL for changes using HEAD requests
189    /// and re-download the image when changes are detected.
190    pub url: String,
191}
192
193/// Aliases for canonical secret keys.
194/// Allows specifying additional key names for CLIENT_ID and CLIENT_SECRET values.
195/// Duplicate aliases are deduplicated. Invalid key names are rejected by the webhook.
196#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
197#[cfg_attr(feature = "schemars", derive(JsonSchema))]
198#[serde(rename_all = "camelCase")]
199pub struct SecretKeyAliases {
200    /// Aliases for the CLIENT_ID key.
201    /// Each alias will be added as an additional key containing the same client ID value.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub client_id: Option<Vec<String>>,
204
205    /// Aliases for the CLIENT_SECRET key.
206    /// Each alias will be added as an additional key containing the same client secret value.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub client_secret: Option<Vec<String>>,
209}
210
211impl SecretKeyAliases {
212    pub fn collect_aliases(&self) -> (Vec<String>, Vec<String>) {
213        let client_id_aliases = self
214            .client_id
215            .as_ref()
216            .map(|v| {
217                let mut deduped: Vec<String> = v.to_vec();
218                deduped.sort();
219                deduped.dedup();
220                deduped
221            })
222            .unwrap_or_default();
223
224        let client_secret_aliases = self
225            .client_secret
226            .as_ref()
227            .map(|v| {
228                let mut deduped: Vec<String> = v.to_vec();
229                deduped.sort();
230                deduped.dedup();
231                deduped
232            })
233            .unwrap_or_default();
234
235        (client_id_aliases, client_secret_aliases)
236    }
237}
238
239impl KanidmResource for KanidmOAuth2Client {
240    #[inline]
241    fn kanidm_ref_spec(&self) -> &KanidmRef {
242        &self.spec.kanidm_ref
243    }
244
245    #[inline]
246    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
247        &kanidm.spec.oauth2_client_namespace_selector
248    }
249
250    #[inline]
251    fn kanidm_name_override(&self) -> Option<&str> {
252        self.spec.kanidm_name.as_deref()
253    }
254}
255
256/// The `KanidmScopeMap` struct represents a mapping of a group to a set of OAuth2 scopes in Kanidm.
257///
258/// Scope maps in Kanidm are used to define the permissions that a client application can request on
259/// behalf of a user. These scopes determine what resources the client can access and what
260/// operations it can perform.
261///
262/// These provide a set of scopes if a user is a member of a specific group within Kanidm. This
263/// allows you to create a relationship between the scopes of a service, and the groups/roles in
264/// Kanidm which can be specific to that service.
265#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
266#[cfg_attr(feature = "schemars", derive(JsonSchema))]
267#[serde(rename_all = "camelCase")]
268pub struct KanidmScopeMap {
269    /// Group name or SPN. Members of this group will be granted the scopes defined in the `scopes` field.
270    pub group: String,
271
272    /// A scope is a string that represents a specific permission or set of permissions that a
273    /// client application can request from an authorization server. Scopes define the level of
274    /// access that the client application is granted to the user's resources.
275    ///
276    /// OpenID Connect allows a number of scopes that affect the content of the resulting authorization
277    /// token. If one of the following scopes is requested by the OpenID client, then the associated
278    /// claims may be added to the authorization token. It is not guaranteed that all of the associated
279    /// claims will be added.
280    ///
281    /// - `profile`: name, family_name, given_name, middle_name, nickname, preferred_username, profile,
282    ///    picture, website, gender, birthdate, zoneinfo, locale, and updated_at
283    /// - `email`: email, email_verified
284    /// - `address`: address
285    /// - `phone`: phone_number, phone_number_verified
286    /// - `groups`: groups
287    ///
288    /// If you are creating an OpenID Connect (OIDC) client, you MUST provide a scope map containing `openid`.
289    /// Without this, OpenID Connect clients WILL NOT WORK!
290    #[allow(clippy::doc_overindented_list_items)]
291    pub scopes: Vec<String>,
292}
293
294impl KanidmScopeMap {
295    pub fn normalize(self) -> Self {
296        let mut scopes = self.scopes;
297        scopes.sort();
298        Self {
299            group: normalize_spn(&self.group),
300            scopes,
301        }
302    }
303    pub fn from(s: &str) -> Option<Self> {
304        let parts = s.split(':').collect::<Vec<_>>();
305        if parts.len() != 2 {
306            return None;
307        }
308        let group = parts[0].to_string();
309        let proto_scopes = parts[1];
310        if proto_scopes.starts_with(" {").not() || proto_scopes.ends_with('}').not() {
311            return None;
312        }
313
314        let scopes = proto_scopes[2..proto_scopes.len() - 1]
315            .split(", ")
316            .map(|s| s.replace('"', ""))
317            .collect();
318        Some(Self { group, scopes })
319    }
320}
321
322/// Some OAuth2 services may consume custom claims from an id token for access control or other
323/// policy decisions. Each custom claim is a key:values set, where there can be many values
324/// associated to a claim name. Different applications may expect these values to be formatted
325/// (joined) in different ways.
326///
327/// Claim values are mapped based on membership to groups. When an account is a member of multiple
328/// groups that would receive the same claim, the values of these maps are merged.
329#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
330#[cfg_attr(feature = "schemars", derive(JsonSchema))]
331#[serde(rename_all = "camelCase")]
332pub struct KanidmClaimMap {
333    /// The name of the claim that will be provided to the client.
334    pub name: String,
335
336    pub values_map: BTreeSet<KanidmClaimsValuesMap>,
337
338    /// The strategy to join the values together.
339    /// Possible strategies to join the values of a claim map:
340    /// `csv` -> "value_a,value_b"
341    /// `ssv` -> "value_a value_b"
342    /// `array` -> ["value_a", "value_b"]
343    #[serde(default)]
344    pub join_strategy: KanidmClaimMapJoinStrategy,
345}
346
347impl KanidmClaimMap {
348    pub fn normalize(self) -> Self {
349        Self {
350            values_map: self
351                .values_map
352                .iter()
353                .map(|vm| vm.clone().normalize())
354                .collect(),
355            ..self
356        }
357    }
358
359    pub fn from(s: &str) -> Option<Self> {
360        let parts = s.split(':').collect::<Vec<_>>();
361        if parts.len() != 4 {
362            return None;
363        }
364        let name = parts[0].to_string();
365        let group = parts[1].to_string();
366        let join_strategy = match parts[2] {
367            "," => KanidmClaimMapJoinStrategy::Csv,
368            " " => KanidmClaimMapJoinStrategy::Ssv,
369            ";" => KanidmClaimMapJoinStrategy::Array,
370            _ => return None,
371        };
372        let proto_values = parts[3];
373        if proto_values.starts_with('"').not() || proto_values.ends_with('"').not() {
374            return None;
375        }
376        let values = proto_values[1..proto_values.len() - 1]
377            .split(",")
378            .map(|s| s.to_string())
379            .collect();
380        Some(Self {
381            name,
382            join_strategy,
383            values_map: BTreeSet::from([KanidmClaimsValuesMap { group, values }]),
384        })
385    }
386
387    pub fn group(v: &[KanidmClaimMap]) -> BTreeSet<KanidmClaimMap> {
388        let mut map: HashMap<String, KanidmClaimMap> = HashMap::new();
389
390        for claim in v {
391            if let Some(existing) = map.get_mut(&claim.name) {
392                existing.values_map.extend(claim.values_map.clone());
393            } else {
394                map.insert(claim.name.clone(), claim.clone());
395            }
396        }
397
398        map.into_values().collect()
399    }
400}
401
402#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
403#[cfg_attr(feature = "schemars", derive(JsonSchema))]
404#[serde(rename_all = "camelCase")]
405pub struct KanidmClaimsValuesMap {
406    /// The group name or SPN that will provide the claim.
407    pub group: String,
408
409    /// The values that will be provided to the client.
410    pub values: Vec<String>,
411}
412
413impl KanidmClaimsValuesMap {
414    pub fn normalize(self) -> Self {
415        let mut values = self.values;
416        values.sort();
417        Self {
418            group: normalize_spn(&self.group),
419            values,
420        }
421    }
422}
423
424#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
425#[cfg_attr(feature = "schemars", derive(JsonSchema))]
426#[serde(rename_all = "snake_case")]
427pub enum KanidmClaimMapJoinStrategy {
428    /// Comma-separated values: "value_a,value_b"
429    Csv,
430    /// Space-separated values: "value_a value_b"
431    Ssv,
432    /// Array format: ["value_a", "value_b"]
433    #[default]
434    Array,
435}
436
437impl KanidmClaimMapJoinStrategy {
438    pub fn to_oauth2_claim_map_join(&self) -> Oauth2ClaimMapJoin {
439        match self {
440            KanidmClaimMapJoinStrategy::Csv => Oauth2ClaimMapJoin::Csv,
441            KanidmClaimMapJoinStrategy::Ssv => Oauth2ClaimMapJoin::Ssv,
442            KanidmClaimMapJoinStrategy::Array => Oauth2ClaimMapJoin::Array,
443        }
444    }
445}
446
447/// Most recent observed status of the Kanidm Group. Read-only.
448/// More info:
449/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
450#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
451#[cfg_attr(feature = "schemars", derive(JsonSchema))]
452#[serde(rename_all = "camelCase")]
453pub struct KanidmOAuth2ClientStatus {
454    #[serde(skip_serializing_if = "Option::is_none")]
455    #[cfg_attr(
456        feature = "schemars",
457        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
458    )]
459    pub conditions: Option<Vec<Condition>>,
460
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub origin: Option<Vec<String>>,
463
464    #[serde(skip_serializing_if = "Option::is_none")]
465    pub scope_map: Option<Vec<String>>,
466
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub sup_scope_map: Option<Vec<String>>,
469
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub claims_map: Option<Vec<String>>,
472
473    pub ready: bool,
474
475    #[serde(skip_serializing_if = "Option::is_none")]
476    pub secret_name: Option<String>,
477
478    pub kanidm_ref: String,
479
480    /// Status of the OAuth2 client image.
481    #[serde(skip_serializing_if = "Option::is_none")]
482    pub image: Option<OAuth2ClientImageStatus>,
483}
484
485#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
486#[cfg_attr(feature = "schemars", derive(JsonSchema))]
487#[serde(rename_all = "camelCase")]
488pub struct OAuth2ClientImageStatus {
489    /// The URL from which the image was last fetched.
490    pub url: String,
491    /// ETag header from the last fetch (for change detection).
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub etag: Option<String>,
494    /// Last-Modified header from the last fetch.
495    #[serde(skip_serializing_if = "Option::is_none")]
496    pub last_modified: Option<String>,
497    /// Content-Length from the last fetch.
498    #[serde(skip_serializing_if = "Option::is_none")]
499    pub content_length: Option<u64>,
500    /// Hash of the image content (SHA-256, for validation).
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub content_hash: Option<String>,
503}
504
505#[cfg(test)]
506mod tests {
507    use super::{
508        KanidmClaimMap, KanidmClaimMapJoinStrategy, KanidmClaimsValuesMap, KanidmOAuth2ClientSpec,
509        KanidmScopeMap,
510    };
511
512    use std::collections::BTreeSet;
513
514    #[test]
515    fn test_refresh_token_expiry_serde() {
516        let base = serde_json::json!({
517            "kanidmRef": {"name": "idm"},
518            "displayname": "Test Client",
519            "origin": "https://example.com",
520            "redirectUrl": [],
521        });
522        let mut configured = base.clone();
523        configured["refreshTokenExpiry"] = serde_json::json!(7_776_000);
524
525        let spec: KanidmOAuth2ClientSpec = serde_json::from_value(configured).unwrap();
526        assert_eq!(spec.refresh_token_expiry, Some(7_776_000));
527        assert_eq!(
528            serde_json::to_value(&spec).unwrap()["refreshTokenExpiry"],
529            serde_json::json!(7_776_000)
530        );
531
532        let unset: KanidmOAuth2ClientSpec = serde_json::from_value(base.clone()).unwrap();
533        assert_eq!(unset.refresh_token_expiry, None);
534        assert!(serde_json::to_value(&unset)
535            .unwrap()
536            .get("refreshTokenExpiry")
537            .is_none());
538
539        for invalid in [serde_json::json!(-1), serde_json::json!(4_294_967_296_u64)] {
540            let mut value = base.clone();
541            value["refreshTokenExpiry"] = invalid;
542            assert!(serde_json::from_value::<KanidmOAuth2ClientSpec>(value).is_err());
543        }
544    }
545
546    #[test]
547    fn test_kanidm_scope_map_from() {
548        let scope_map = KanidmScopeMap {
549            group: "test_group".to_string(),
550            scopes: vec!["scope1".to_string(), "scope2".to_string()],
551        };
552
553        assert_eq!(
554            KanidmScopeMap::from(r#"test_group@test.example.com: {"scope1", "scope2"}"#)
555                .unwrap()
556                .normalize(),
557            scope_map,
558        );
559
560        assert_eq!(
561            KanidmScopeMap::from(r#"test_group: {"scope1", "scope2"}"#)
562                .unwrap()
563                .normalize(),
564            scope_map,
565        );
566
567        assert!(KanidmScopeMap::from(r#"test_group:{"scope1", "scope2"}"#).is_none(),);
568        assert_eq!(
569            KanidmScopeMap::from(r#"test_group: {"scope1"}"#)
570                .unwrap()
571                .normalize(),
572            KanidmScopeMap {
573                group: "test_group".to_string(),
574                scopes: vec!["scope1".to_string()],
575            }
576        );
577    }
578
579    #[test]
580    fn test_group_kanidm_claims_map() {
581        let claim1 = KanidmClaimMap {
582            name: "claim1".to_string(),
583            values_map: BTreeSet::from([KanidmClaimsValuesMap {
584                group: "group1".to_string(),
585                values: vec!["value1".to_string()],
586            }]),
587            join_strategy: KanidmClaimMapJoinStrategy::Array,
588        };
589
590        let claim2 = KanidmClaimMap {
591            name: "claim1".to_string(),
592            values_map: BTreeSet::from([KanidmClaimsValuesMap {
593                group: "group2".to_string(),
594                values: vec!["value2".to_string()],
595            }]),
596            join_strategy: KanidmClaimMapJoinStrategy::Array,
597        };
598
599        let claim3 = KanidmClaimMap {
600            name: "claim2".to_string(),
601            values_map: BTreeSet::from([KanidmClaimsValuesMap {
602                group: "group3".to_string(),
603                values: vec!["value3".to_string()],
604            }]),
605            join_strategy: KanidmClaimMapJoinStrategy::Array,
606        };
607
608        let claims = vec![claim1.clone(), claim2.clone(), claim3.clone()];
609
610        let grouped_claims = KanidmClaimMap::group(&claims);
611
612        assert_eq!(grouped_claims.len(), 2);
613
614        let grouped_claim1 = grouped_claims.iter().find(|c| c.name == "claim1").unwrap();
615        assert_eq!(grouped_claim1.values_map.len(), 2);
616        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
617            group: "group1".to_string(),
618            values: vec!["value1".to_string()],
619        }));
620        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
621            group: "group2".to_string(),
622            values: vec!["value2".to_string()],
623        }));
624
625        let grouped_claim2 = grouped_claims.iter().find(|c| c.name == "claim2").unwrap();
626        assert_eq!(grouped_claim2.values_map.len(), 1);
627        assert!(grouped_claim2.values_map.contains(&KanidmClaimsValuesMap {
628            group: "group3".to_string(),
629            values: vec!["value3".to_string()],
630        }));
631    }
632
633    #[test]
634    fn test_kanidm_claim_map_from() {
635        let mut claim_map = KanidmClaimMap {
636            name: "claim_name".to_string(),
637            join_strategy: KanidmClaimMapJoinStrategy::Array,
638            values_map: BTreeSet::from([KanidmClaimsValuesMap {
639                group: "group_name".to_string(),
640                // Sorted values after normalization
641                values: vec!["boo".to_string(), "foo".to_string()],
642            }]),
643        };
644
645        assert_eq!(
646            KanidmClaimMap::from(r#"claim_name:group_name@test.example.com:;:"foo,boo""#)
647                .unwrap()
648                .normalize(),
649            claim_map,
650        );
651        assert_eq!(
652            KanidmClaimMap::from(r#"claim_name:group_name:;:"foo,boo""#)
653                .unwrap()
654                .normalize(),
655            claim_map,
656        );
657
658        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Csv;
659        assert_eq!(
660            KanidmClaimMap::from(r#"claim_name:group_name:,:"foo,boo""#)
661                .unwrap()
662                .normalize(),
663            claim_map,
664        );
665
666        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Ssv;
667        assert_eq!(
668            KanidmClaimMap::from(r#"claim_name:group_name: :"foo,boo""#)
669                .unwrap()
670                .normalize(),
671            claim_map,
672        );
673    }
674}