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    /// Automatic rotation configuration for the OAuth2 client secret. Only applies to confidential
145    /// clients (public: false). When enabled, the operator will regenerate the client secret
146    /// periodically based on the configured rotation period.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub secret_rotation: Option<SecretRotation>,
149
150    /// Template applied to the Secret created for confidential clients (public: false).
151    /// Allows attaching custom annotations and labels to the generated Secret. The operator's own
152    /// labels and annotations take precedence over any conflicting keys in the template.
153    /// Changes to this template are enforced on the next reconciliation, overwriting any manual
154    /// modifications made to the Secret
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub secret_template: Option<MetadataTemplate>,
157
158    /// Aliases for the canonical secret keys (CLIENT_ID and CLIENT_SECRET).
159    /// Allows consumers that require different fixed key names to access the same credentials.
160    /// The canonical keys CLIENT_ID and CLIENT_SECRET are always present.
161    /// Only applies to confidential clients (public: false).
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub secret_key_aliases: Option<SecretKeyAliases>,
164
165    /// Optional URL to an image for the OAuth2 client application.
166    /// The image will be downloaded and set in Kanidm for display in the application portal.
167    /// Constraints:
168    /// - Maximum size: 256 KB
169    /// - Maximum dimensions: 1024 x 1024 pixels
170    /// - Supported formats: png, jpg, gif, svg, webp
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub image: Option<OAuth2ClientImageSpec>,
173}
174
175#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
176#[cfg_attr(feature = "schemars", derive(JsonSchema))]
177#[serde(rename_all = "camelCase")]
178pub struct OAuth2ClientImageSpec {
179    /// URL to fetch the image from (HTTP/HTTPS only).
180    /// The operator will periodically check this URL for changes using HEAD requests
181    /// and re-download the image when changes are detected.
182    pub url: String,
183}
184
185/// Aliases for canonical secret keys.
186/// Allows specifying additional key names for CLIENT_ID and CLIENT_SECRET values.
187/// Duplicate aliases are deduplicated. Invalid key names are rejected by the webhook.
188#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
189#[cfg_attr(feature = "schemars", derive(JsonSchema))]
190#[serde(rename_all = "camelCase")]
191pub struct SecretKeyAliases {
192    /// Aliases for the CLIENT_ID key.
193    /// Each alias will be added as an additional key containing the same client ID value.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub client_id: Option<Vec<String>>,
196
197    /// Aliases for the CLIENT_SECRET key.
198    /// Each alias will be added as an additional key containing the same client secret value.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub client_secret: Option<Vec<String>>,
201}
202
203impl SecretKeyAliases {
204    pub fn collect_aliases(&self) -> (Vec<String>, Vec<String>) {
205        let client_id_aliases = self
206            .client_id
207            .as_ref()
208            .map(|v| {
209                let mut deduped: Vec<String> = v.to_vec();
210                deduped.sort();
211                deduped.dedup();
212                deduped
213            })
214            .unwrap_or_default();
215
216        let client_secret_aliases = self
217            .client_secret
218            .as_ref()
219            .map(|v| {
220                let mut deduped: Vec<String> = v.to_vec();
221                deduped.sort();
222                deduped.dedup();
223                deduped
224            })
225            .unwrap_or_default();
226
227        (client_id_aliases, client_secret_aliases)
228    }
229}
230
231impl KanidmResource for KanidmOAuth2Client {
232    #[inline]
233    fn kanidm_ref_spec(&self) -> &KanidmRef {
234        &self.spec.kanidm_ref
235    }
236
237    #[inline]
238    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
239        &kanidm.spec.oauth2_client_namespace_selector
240    }
241
242    #[inline]
243    fn kanidm_name_override(&self) -> Option<&str> {
244        self.spec.kanidm_name.as_deref()
245    }
246}
247
248/// The `KanidmScopeMap` struct represents a mapping of a group to a set of OAuth2 scopes in Kanidm.
249///
250/// Scope maps in Kanidm are used to define the permissions that a client application can request on
251/// behalf of a user. These scopes determine what resources the client can access and what
252/// operations it can perform.
253///
254/// These provide a set of scopes if a user is a member of a specific group within Kanidm. This
255/// allows you to create a relationship between the scopes of a service, and the groups/roles in
256/// Kanidm which can be specific to that service.
257#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
258#[cfg_attr(feature = "schemars", derive(JsonSchema))]
259#[serde(rename_all = "camelCase")]
260pub struct KanidmScopeMap {
261    /// Group name or SPN. Members of this group will be granted the scopes defined in the `scopes` field.
262    pub group: String,
263
264    /// A scope is a string that represents a specific permission or set of permissions that a
265    /// client application can request from an authorization server. Scopes define the level of
266    /// access that the client application is granted to the user's resources.
267    ///
268    /// OpenID Connect allows a number of scopes that affect the content of the resulting authorization
269    /// token. If one of the following scopes is requested by the OpenID client, then the associated
270    /// claims may be added to the authorization token. It is not guaranteed that all of the associated
271    /// claims will be added.
272    ///
273    /// - `profile`: name, family_name, given_name, middle_name, nickname, preferred_username, profile,
274    ///    picture, website, gender, birthdate, zoneinfo, locale, and updated_at
275    /// - `email`: email, email_verified
276    /// - `address`: address
277    /// - `phone`: phone_number, phone_number_verified
278    /// - `groups`: groups
279    ///
280    /// If you are creating an OpenID Connect (OIDC) client, you MUST provide a scope map containing `openid`.
281    /// Without this, OpenID Connect clients WILL NOT WORK!
282    #[allow(clippy::doc_overindented_list_items)]
283    pub scopes: Vec<String>,
284}
285
286impl KanidmScopeMap {
287    pub fn normalize(self) -> Self {
288        let mut scopes = self.scopes;
289        scopes.sort();
290        Self {
291            group: normalize_spn(&self.group),
292            scopes,
293        }
294    }
295    pub fn from(s: &str) -> Option<Self> {
296        let parts = s.split(':').collect::<Vec<_>>();
297        if parts.len() != 2 {
298            return None;
299        }
300        let group = parts[0].to_string();
301        let proto_scopes = parts[1];
302        if proto_scopes.starts_with(" {").not() || proto_scopes.ends_with('}').not() {
303            return None;
304        }
305
306        let scopes = proto_scopes[2..proto_scopes.len() - 1]
307            .split(", ")
308            .map(|s| s.replace('"', ""))
309            .collect();
310        Some(Self { group, scopes })
311    }
312}
313
314/// Some OAuth2 services may consume custom claims from an id token for access control or other
315/// policy decisions. Each custom claim is a key:values set, where there can be many values
316/// associated to a claim name. Different applications may expect these values to be formatted
317/// (joined) in different ways.
318///
319/// Claim values are mapped based on membership to groups. When an account is a member of multiple
320/// groups that would receive the same claim, the values of these maps are merged.
321#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
322#[cfg_attr(feature = "schemars", derive(JsonSchema))]
323#[serde(rename_all = "camelCase")]
324pub struct KanidmClaimMap {
325    /// The name of the claim that will be provided to the client.
326    pub name: String,
327
328    pub values_map: BTreeSet<KanidmClaimsValuesMap>,
329
330    /// The strategy to join the values together.
331    /// Possible strategies to join the values of a claim map:
332    /// `csv` -> "value_a,value_b"
333    /// `ssv` -> "value_a value_b"
334    /// `array` -> ["value_a", "value_b"]
335    #[serde(default)]
336    pub join_strategy: KanidmClaimMapJoinStrategy,
337}
338
339impl KanidmClaimMap {
340    pub fn normalize(self) -> Self {
341        Self {
342            values_map: self
343                .values_map
344                .iter()
345                .map(|vm| vm.clone().normalize())
346                .collect(),
347            ..self
348        }
349    }
350
351    pub fn from(s: &str) -> Option<Self> {
352        let parts = s.split(':').collect::<Vec<_>>();
353        if parts.len() != 4 {
354            return None;
355        }
356        let name = parts[0].to_string();
357        let group = parts[1].to_string();
358        let join_strategy = match parts[2] {
359            "," => KanidmClaimMapJoinStrategy::Csv,
360            " " => KanidmClaimMapJoinStrategy::Ssv,
361            ";" => KanidmClaimMapJoinStrategy::Array,
362            _ => return None,
363        };
364        let proto_values = parts[3];
365        if proto_values.starts_with('"').not() || proto_values.ends_with('"').not() {
366            return None;
367        }
368        let values = proto_values[1..proto_values.len() - 1]
369            .split(",")
370            .map(|s| s.to_string())
371            .collect();
372        Some(Self {
373            name,
374            join_strategy,
375            values_map: BTreeSet::from([KanidmClaimsValuesMap { group, values }]),
376        })
377    }
378
379    pub fn group(v: &[KanidmClaimMap]) -> BTreeSet<KanidmClaimMap> {
380        let mut map: HashMap<String, KanidmClaimMap> = HashMap::new();
381
382        for claim in v {
383            if let Some(existing) = map.get_mut(&claim.name) {
384                existing.values_map.extend(claim.values_map.clone());
385            } else {
386                map.insert(claim.name.clone(), claim.clone());
387            }
388        }
389
390        map.into_values().collect()
391    }
392}
393
394#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
395#[cfg_attr(feature = "schemars", derive(JsonSchema))]
396#[serde(rename_all = "camelCase")]
397pub struct KanidmClaimsValuesMap {
398    /// The group name or SPN that will provide the claim.
399    pub group: String,
400
401    /// The values that will be provided to the client.
402    pub values: Vec<String>,
403}
404
405impl KanidmClaimsValuesMap {
406    pub fn normalize(self) -> Self {
407        let mut values = self.values;
408        values.sort();
409        Self {
410            group: normalize_spn(&self.group),
411            values,
412        }
413    }
414}
415
416#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
417#[cfg_attr(feature = "schemars", derive(JsonSchema))]
418#[serde(rename_all = "snake_case")]
419pub enum KanidmClaimMapJoinStrategy {
420    /// Comma-separated values: "value_a,value_b"
421    Csv,
422    /// Space-separated values: "value_a value_b"
423    Ssv,
424    /// Array format: ["value_a", "value_b"]
425    #[default]
426    Array,
427}
428
429impl KanidmClaimMapJoinStrategy {
430    pub fn to_oauth2_claim_map_join(&self) -> Oauth2ClaimMapJoin {
431        match self {
432            KanidmClaimMapJoinStrategy::Csv => Oauth2ClaimMapJoin::Csv,
433            KanidmClaimMapJoinStrategy::Ssv => Oauth2ClaimMapJoin::Ssv,
434            KanidmClaimMapJoinStrategy::Array => Oauth2ClaimMapJoin::Array,
435        }
436    }
437}
438
439/// Most recent observed status of the Kanidm Group. Read-only.
440/// More info:
441/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
442#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
443#[cfg_attr(feature = "schemars", derive(JsonSchema))]
444#[serde(rename_all = "camelCase")]
445pub struct KanidmOAuth2ClientStatus {
446    #[serde(skip_serializing_if = "Option::is_none")]
447    #[cfg_attr(
448        feature = "schemars",
449        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
450    )]
451    pub conditions: Option<Vec<Condition>>,
452
453    #[serde(skip_serializing_if = "Option::is_none")]
454    pub origin: Option<Vec<String>>,
455
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub scope_map: Option<Vec<String>>,
458
459    #[serde(skip_serializing_if = "Option::is_none")]
460    pub sup_scope_map: Option<Vec<String>>,
461
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub claims_map: Option<Vec<String>>,
464
465    pub ready: bool,
466
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub secret_name: Option<String>,
469
470    pub kanidm_ref: String,
471
472    /// Status of the OAuth2 client image.
473    #[serde(skip_serializing_if = "Option::is_none")]
474    pub image: Option<OAuth2ClientImageStatus>,
475}
476
477#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
478#[cfg_attr(feature = "schemars", derive(JsonSchema))]
479#[serde(rename_all = "camelCase")]
480pub struct OAuth2ClientImageStatus {
481    /// The URL from which the image was last fetched.
482    pub url: String,
483    /// ETag header from the last fetch (for change detection).
484    #[serde(skip_serializing_if = "Option::is_none")]
485    pub etag: Option<String>,
486    /// Last-Modified header from the last fetch.
487    #[serde(skip_serializing_if = "Option::is_none")]
488    pub last_modified: Option<String>,
489    /// Content-Length from the last fetch.
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub content_length: Option<u64>,
492    /// Hash of the image content (SHA-256, for validation).
493    #[serde(skip_serializing_if = "Option::is_none")]
494    pub content_hash: Option<String>,
495}
496
497#[cfg(test)]
498mod tests {
499    use super::{
500        KanidmClaimMap, KanidmClaimMapJoinStrategy, KanidmClaimsValuesMap, KanidmScopeMap,
501    };
502
503    use std::collections::BTreeSet;
504
505    #[test]
506    fn test_kanidm_scope_map_from() {
507        let scope_map = KanidmScopeMap {
508            group: "test_group".to_string(),
509            scopes: vec!["scope1".to_string(), "scope2".to_string()],
510        };
511
512        assert_eq!(
513            KanidmScopeMap::from(r#"test_group@test.example.com: {"scope1", "scope2"}"#)
514                .unwrap()
515                .normalize(),
516            scope_map,
517        );
518
519        assert_eq!(
520            KanidmScopeMap::from(r#"test_group: {"scope1", "scope2"}"#)
521                .unwrap()
522                .normalize(),
523            scope_map,
524        );
525
526        assert!(KanidmScopeMap::from(r#"test_group:{"scope1", "scope2"}"#).is_none(),);
527        assert_eq!(
528            KanidmScopeMap::from(r#"test_group: {"scope1"}"#)
529                .unwrap()
530                .normalize(),
531            KanidmScopeMap {
532                group: "test_group".to_string(),
533                scopes: vec!["scope1".to_string()],
534            }
535        );
536    }
537
538    #[test]
539    fn test_group_kanidm_claims_map() {
540        let claim1 = KanidmClaimMap {
541            name: "claim1".to_string(),
542            values_map: BTreeSet::from([KanidmClaimsValuesMap {
543                group: "group1".to_string(),
544                values: vec!["value1".to_string()],
545            }]),
546            join_strategy: KanidmClaimMapJoinStrategy::Array,
547        };
548
549        let claim2 = KanidmClaimMap {
550            name: "claim1".to_string(),
551            values_map: BTreeSet::from([KanidmClaimsValuesMap {
552                group: "group2".to_string(),
553                values: vec!["value2".to_string()],
554            }]),
555            join_strategy: KanidmClaimMapJoinStrategy::Array,
556        };
557
558        let claim3 = KanidmClaimMap {
559            name: "claim2".to_string(),
560            values_map: BTreeSet::from([KanidmClaimsValuesMap {
561                group: "group3".to_string(),
562                values: vec!["value3".to_string()],
563            }]),
564            join_strategy: KanidmClaimMapJoinStrategy::Array,
565        };
566
567        let claims = vec![claim1.clone(), claim2.clone(), claim3.clone()];
568
569        let grouped_claims = KanidmClaimMap::group(&claims);
570
571        assert_eq!(grouped_claims.len(), 2);
572
573        let grouped_claim1 = grouped_claims.iter().find(|c| c.name == "claim1").unwrap();
574        assert_eq!(grouped_claim1.values_map.len(), 2);
575        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
576            group: "group1".to_string(),
577            values: vec!["value1".to_string()],
578        }));
579        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
580            group: "group2".to_string(),
581            values: vec!["value2".to_string()],
582        }));
583
584        let grouped_claim2 = grouped_claims.iter().find(|c| c.name == "claim2").unwrap();
585        assert_eq!(grouped_claim2.values_map.len(), 1);
586        assert!(grouped_claim2.values_map.contains(&KanidmClaimsValuesMap {
587            group: "group3".to_string(),
588            values: vec!["value3".to_string()],
589        }));
590    }
591
592    #[test]
593    fn test_kanidm_claim_map_from() {
594        let mut claim_map = KanidmClaimMap {
595            name: "claim_name".to_string(),
596            join_strategy: KanidmClaimMapJoinStrategy::Array,
597            values_map: BTreeSet::from([KanidmClaimsValuesMap {
598                group: "group_name".to_string(),
599                // Sorted values after normalization
600                values: vec!["boo".to_string(), "foo".to_string()],
601            }]),
602        };
603
604        assert_eq!(
605            KanidmClaimMap::from(r#"claim_name:group_name@test.example.com:;:"foo,boo""#)
606                .unwrap()
607                .normalize(),
608            claim_map,
609        );
610        assert_eq!(
611            KanidmClaimMap::from(r#"claim_name:group_name:;:"foo,boo""#)
612                .unwrap()
613                .normalize(),
614            claim_map,
615        );
616
617        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Csv;
618        assert_eq!(
619            KanidmClaimMap::from(r#"claim_name:group_name:,:"foo,boo""#)
620                .unwrap()
621                .normalize(),
622            claim_map,
623        );
624
625        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Ssv;
626        assert_eq!(
627            KanidmClaimMap::from(r#"claim_name:group_name: :"foo,boo""#)
628                .unwrap()
629                .normalize(),
630            claim_map,
631        );
632    }
633}